"""Application factory. Importing this module does not open a database connection.""" from __future__ import annotations import logging from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from app.api.routes import router from app.api.sources import router as sources_router from app.core.errors import Problem, problem_response from app.core.settings import get_settings from app.db.pool import open_pool logger = logging.getLogger("tsumugu") def _database_ok(app: FastAPI) -> bool: pool = getattr(app.state, "pool", None) if pool is None: return False try: with pool.connection() as conn: conn.execute("SELECT 1") conn.rollback() return True except Exception: logger.warning("database check failed") return False def create_app() -> FastAPI: settings = get_settings() logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s") @asynccontextmanager async def lifespan(app: FastAPI): app.state.pool = open_pool(settings) try: yield finally: app.state.pool.close() app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan) app.state.settings = settings @app.middleware("http") async def origin_guard(request: Request, call_next): if request.method not in {"GET", "HEAD", "OPTIONS"} and request.url.path.startswith("/api/"): origin = request.headers.get("origin") if origin not in settings.origin_set: problem = Problem(403, "Keine Berechtigung", "Der Ursprung der Anfrage ist nicht erlaubt.", "forbidden") return problem_response(problem, request) response = await call_next(request) logger.info("%s %s -> %s", request.method, request.url.path, response.status_code) return response @app.exception_handler(Problem) async def handle_problem(request: Request, exc: Problem): return problem_response(exc, request) @app.exception_handler(RequestValidationError) async def handle_validation(request: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content={ "type": "about:blank", "title": "Eingabe ungültig", "status": 422, "detail": "Die Eingabe ist unvollständig oder ungültig.", "instance": request.url.path, "code": "unprocessable", }, media_type="application/problem+json", ) @app.exception_handler(Exception) async def handle_unexpected(request: Request, exc: Exception): logger.exception("unhandled error") return JSONResponse( status_code=500, content={ "type": "about:blank", "title": "Unerwarteter Fehler", "status": 500, "detail": "Die Aktion konnte nicht abgeschlossen werden.", "instance": request.url.path, "code": "internal", }, media_type="application/problem+json", ) @app.get("/api/health") def api_health(): ok = _database_ok(app) return JSONResponse( status_code=200 if ok else 503, content={"status": "ok" if ok else "degraded", "app": "tsumugu"}, ) @app.get("/health/live") def health_live(): return {"status": "ok", "app": "tsumugu"} @app.get("/health/ready") def health_ready(): ok = _database_ok(app) return JSONResponse( status_code=200 if ok else 503, content={"status": "ok" if ok else "degraded", "app": "tsumugu"}, ) app.include_router(router) app.include_router(sources_router) return app app = create_app()