"""Application factory, CORS setup and global error handling. Every non-2xx response uses the standardized envelope (``schemas.common.ErrorDetail``):: {"detail": "", "code": ""} with an additional ``errors`` array for validation failures (HTTP 422). """ import logging from contextlib import asynccontextmanager from collections.abc import AsyncIterator from fastapi import FastAPI, Request, status from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from sqlalchemy import inspect, text from starlette.exceptions import HTTPException as StarletteHTTPException from api.v1 import router as api_v1_router from config import API_V1_PREFIX, APP_NAME, APP_VERSION, get_settings from db.session import engine from models import Base logger = logging.getLogger("newzy") # Machine-readable codes for the most common HTTP errors. _HTTP_ERROR_CODES: dict[int, str] = { 400: "bad_request", 401: "unauthorized", 403: "forbidden", 404: "not_found", 405: "method_not_allowed", 409: "conflict", 422: "validation_error", 429: "too_many_requests", } def _error_response(status_code: int, detail: str, code: str, errors=None) -> JSONResponse: """Build the standardized error envelope as a JSON response.""" payload: dict = {"detail": detail, "code": code} if errors is not None: payload["errors"] = jsonable_encoder(errors) return JSONResponse(status_code=status_code, content=payload) def _ensure_user_columns() -> None: """Lightweight schema upgrade for pre-existing databases. ``Base.metadata.create_all`` creates missing *tables* but never alters existing ones, so databases created before M6 (which added ``users.is_admin``) are patched here. Idempotent: inspects the table and only issues ``ALTER TABLE`` for columns that are absent. """ inspector = inspect(engine) if "users" not in inspector.get_table_names(): return existing = {column["name"] for column in inspector.get_columns("users")} if "is_admin" not in existing: with engine.begin() as connection: connection.execute( text("ALTER TABLE users ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT 0") ) logger.info("Added users.is_admin column to pre-existing database") @asynccontextmanager async def lifespan(_app: FastAPI) -> AsyncIterator[None]: """Create database tables (and patch old schemas) on startup. Idempotent for SQLite volumes: new tables are created and existing ones only receive the missing-column upgrades (see ``_ensure_user_columns``). """ Base.metadata.create_all(bind=engine) _ensure_user_columns() logger.info("Database tables ensured (engine: %s)", engine.url) yield def create_app() -> FastAPI: """Build and configure the FastAPI application.""" settings = get_settings() app = FastAPI( title=APP_NAME, version=APP_VERSION, description="Backend API for the newzy news web application.", openapi_url=f"{API_V1_PREFIX}/openapi.json", lifespan=lifespan, ) # --- CORS (frontend development) ------------------------------------ app.add_middleware( CORSMiddleware, allow_origins=settings.cors_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # --- Global error handlers ------------------------------------------- @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse: code = _HTTP_ERROR_CODES.get(exc.status_code, "http_error") return _error_response(exc.status_code, str(exc.detail), code) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse: return _error_response( 422, "Request validation failed.", "validation_error", errors=exc.errors(), ) @app.exception_handler(Exception) async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse: logger.exception("Unhandled error processing %s %s", request.method, request.url.path) return _error_response( status.HTTP_500_INTERNAL_SERVER_ERROR, "An unexpected error occurred.", "internal_error", ) # --- Routes ----------------------------------------------------------- app.include_router(api_v1_router, prefix=API_V1_PREFIX, tags=["v1"]) @app.get("/health", tags=["health"], summary="Root health check") async def health() -> dict: """Liveness probe (mirrors ``GET /api/v1/health``).""" return {"status": "ok", "version": APP_VERSION} return app