import asyncio import logging import time import uuid from contextlib import asynccontextmanager, suppress from pathlib import Path from fastapi import FastAPI, HTTPException, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from sqlalchemy import text from app.api.auth import router as auth_router from app.api.users import router as users_router from app.api.chats import router as chats_router from app.api.messages import router as messages_router from app.api.attachments import router as attachments_router import app.core.mtls_protocol from app.core.config import settings from app.core.telemetry import setup_telemetry from app.db.session import engine from app.services.object_storage import client as s3_client from app.services.attachment_cleanup import cleanup_expired_uploads logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s", ) logger = logging.getLogger(__name__) async def attachment_cleanup_loop(): while True: try: # Synchronous boto3/SQLAlchemy I/O must not block the event loop. await asyncio.to_thread(cleanup_expired_uploads) except Exception: logger.exception("Attachment cleanup worker iteration failed") await asyncio.sleep(settings.attachment_cleanup_interval_seconds) @asynccontextmanager async def lifespan(app: FastAPI): logger.info("Application startup instance_id=%s", settings.instance_id) cleanup_task = asyncio.create_task(attachment_cleanup_loop()) try: yield finally: cleanup_task.cancel() with suppress(asyncio.CancelledError): await cleanup_task engine.dispose() logger.info("Application shutdown instance_id=%s", settings.instance_id) app = FastAPI( title=settings.app_name, version="1.4.0", lifespan=lifespan, ) app.include_router(users_router) app.include_router(auth_router) app.include_router(chats_router) app.include_router(messages_router) app.include_router(attachments_router) @app.middleware("http") async def response_headers(request: Request, call_next): request_id = str(uuid.uuid4()) request.state.request_id = request_id # API only accepts requests carrying the fixed identity of the private # ingress. The TLS listener additionally requires a client certificate # issued by the dedicated ingress CA. peer_cert = getattr(request.state, "tls_client_cert", None) uri_sans = [ value for kind, value in (peer_cert or {}).get("subjectAltName", ()) if kind == "URI" ] if "spiffe://lab7/ingress/nginx" not in uri_sans: return JSONResponse( status_code=403, content={"detail": "Untrusted client certificate identity"}, ) started_at = time.perf_counter() try: response = await call_next(request) except Exception: logger.exception( "Unhandled request error; request_id=%s", request_id, ) response = JSONResponse( status_code=500, content={ "error": { "code": "internal_error", "message": "Unexpected error", "request_id": request_id, } }, ) duration_ms = (time.perf_counter() - started_at) * 1000 route = request.scope.get("route") route_template = getattr(route, "path", "unmatched") if route_template not in ("/health/live", "/health/ready"): logger.info( "HTTP request completed", extra={ "event": "http_request_completed", "http_method": request.method, "http_route": route_template, "http_status_code": response.status_code, "http_duration_ms": round(duration_ms, 3), }, ) response.headers["X-Request-Id"] = request_id response.headers["X-Instance-Id"] = settings.instance_id response.headers["X-Content-Type-Options"] = "nosniff" return response # Initialize OpenTelemetry AFTER registering the application middleware. # This makes OpenTelemetry middleware outermost, keeping the server span # active while response_headers writes the completed-request log. setup_telemetry(app, engine) @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): request_id = getattr( request.state, "request_id", str(uuid.uuid4()), ) code = { 400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited", 500: "internal_error", 503: "unavailable", }.get(exc.status_code, "internal_error") headers = dict(exc.headers or {}) headers["X-Request-Id"] = request_id headers["X-Instance-Id"] = settings.instance_id return JSONResponse( status_code=exc.status_code, content={ "error": { "code": code, "message": ( exc.detail if isinstance(exc.detail, str) else "Request failed" ), "request_id": request_id, } }, headers=headers, ) @app.exception_handler(RequestValidationError) async def validation_exception_handler( request: Request, exc: RequestValidationError, ): request_id = getattr( request.state, "request_id", str(uuid.uuid4()), ) return JSONResponse( status_code=400, content={ "error": { "code": "invalid_request", "message": "Validation error", "request_id": request_id, } }, headers={ "X-Request-Id": request_id, "X-Instance-Id": settings.instance_id, }, ) @app.get("/health/live") def liveness(): return {"status": "ok"} DRAIN_FILE = Path("/tmp/api-draining") @app.get("/health/ready") def readiness(): if DRAIN_FILE.exists(): raise HTTPException( status_code=503, detail="Instance is draining", ) try: with engine.connect() as connection: connection.execute(text("SELECT 1")) s3_client().head_bucket(Bucket=settings.s3_bucket) return {"status": "ok"} except Exception: logger.exception( "PostgreSQL or S3 readiness check failed" ) raise HTTPException( status_code=503, detail="Required storage unavailable", ) from None