"""Modular API: startup reconciliation gates admission; no prototype imports.""" import asyncio from contextlib import asynccontextmanager from uuid import UUID, uuid4 from fastapi import FastAPI, Request, HTTPException from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException from fastapi.middleware.cors import CORSMiddleware from app.api.v1.auth import router as auth_router, identity_router from app.api.v1.conversations import router as conversations_router from app.api.v1.live import router as voice_router from app.api.v1.documents import router as documents_router from app.api.v1.knowledge import router as knowledge_router from app.api.v1 import dependencies from app.infrastructure.blocking import blocking, shutdown_pool from app.modules.voice.configuration import VoiceSettings from app.modules.voice.registry import shutdown @asynccontextmanager async def lifespan(app): app.state.ready = False engine = None startup_error = None try: engine = dependencies.get_engine() lifecycle = dependencies.get_lifecycle_service(engine) await blocking(dependencies.prepare_search_tools) await blocking(lifecycle.reconcile_startup) app.state.ready = True yield except BaseException as exc: startup_error = exc raise finally: app.state.ready = False async def cleanup(): try: await asyncio.wait_for(shutdown(), 6) finally: try: runner = dependencies._TOOL_RUNNER if runner is not None: await asyncio.wait_for(asyncio.to_thread(runner.close), 6) finally: try: if engine is not None: engine.dispose() finally: dependencies._TOOL_RUNNER = None dependencies._ENGINE = dependencies._AUTH_SERVICE = dependencies._LIFECYCLE_SERVICE = dependencies._SEARCH_SERVICE = None shutdown_pool() task = asyncio.create_task(cleanup()) try: await asyncio.shield(task) except asyncio.CancelledError: # Cleanup retains ownership after cancellation, including startup. try: await asyncio.shield(task) except Exception: if startup_error is None: raise if startup_error is None: raise except Exception: if startup_error is None: raise app = FastAPI(title='Technical Documentation Assistant API', lifespan=lifespan) app.state.ready = False config = VoiceSettings() app.add_middleware(CORSMiddleware, allow_origins=list(config.trusted_origins), allow_credentials=True, allow_methods=['GET','POST','PATCH'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID','Idempotency-Key'], expose_headers=['X-Request-ID','Idempotency-Replayed']) @app.middleware('http') async def transport(request, call_next): try: request_id = str(UUID(request.headers.get('x-request-id', ''))) except (ValueError, TypeError): request_id = str(uuid4()) request.state.request_id = request_id if request.headers.get('host') not in config.trusted_hosts: result = envelope(request, 'FORBIDDEN', 403) elif not app.state.ready and request.url.path not in ('/health/live','/health/ready'): result = envelope(request, 'DEPENDENCY_UNAVAILABLE', 503) else: result = await call_next(request) result.headers['X-Request-ID'] = request_id return result def envelope(request, code, status, details=None): return JSONResponse(status_code=status, headers={'Retry-After':'60'} if status == 429 else {}, content={'error': {'code': code, 'message': 'Request could not be completed.', 'request_id': getattr(request.state, 'request_id', str(uuid4())), 'retryable': status in (429,503), **({'details':details} if details else {})}}) @app.exception_handler(StarletteHTTPException) @app.exception_handler(HTTPException) async def http_error(request, exc): detail = exc.detail if isinstance(exc.detail, dict) else {} return envelope(request, detail.get('code', 'NOT_FOUND' if exc.status_code == 404 else 'REQUEST_FAILED'), exc.status_code, detail.get('details')) @app.exception_handler(RequestValidationError) async def dto_error(request, exc): return envelope(request, 'VALIDATION_ERROR', 422) @app.exception_handler(Exception) async def unexpected_error(request, exc): return envelope(request, 'DEPENDENCY_UNAVAILABLE', 503) for router in (auth_router, identity_router, conversations_router, voice_router, documents_router, knowledge_router): app.include_router(router, prefix='/api/v1') @app.get('/health/live') def live(): return {'status': 'ok'} @app.get('/health/ready') def ready(): return JSONResponse(status_code=200 if app.state.ready else 503, content={'status': 'ready', 'ingestion': 'available'} if app.state.ready else {'status': 'not_ready'})