feat(voice): add authenticated Phase 2 live lifecycle
Add cookie authentication, owned conversations, durable Live reservations, tool completion/replay fencing, revocation, and startup reconciliation. Introduce forward lifecycle/owner-chain migrations and the temporary Gemini adapter while preserving the existing OpenAI Realtime adapter. Include the executable audio client, regression coverage, configuration, API/database documentation, and recorded acceptance evidence. Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript syntax, and whitespace checks passed. Full PostgreSQL/provider-free results are recorded in the repair report; real-provider/browser acceptance is unrun. Follow-up work remains for configurable OpenAI/Gemini selection, transport admission, authority diagnostics, playback message bounds, and client replay identity after ambiguous creation responses.
This commit is contained in:
+110
-36
@@ -1,43 +1,117 @@
|
||||
"""Main FastAPI Application Entrypoint.
|
||||
|
||||
Initializes the FastAPI application, sets up CORS middleware, registers API routes,
|
||||
and provides system health check endpoints.
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI
|
||||
"""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 import dependencies
|
||||
from app.infrastructure.blocking import blocking, shutdown_pool
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.modules.voice.registry import shutdown
|
||||
|
||||
from app.api.v1.chat import router as chat_router
|
||||
from app.core.config import settings
|
||||
@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(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
|
||||
|
||||
# Initialize FastAPI application instance
|
||||
app = FastAPI(
|
||||
title=settings.app_name,
|
||||
version=settings.app_version,
|
||||
description=settings.app_description,
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
)
|
||||
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'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID'])
|
||||
|
||||
# Configure Cross-Origin Resource Sharing (CORS) middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@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
|
||||
|
||||
# Register API v1 routers
|
||||
app.include_router(chat_router, prefix="/api/v1")
|
||||
def envelope(request, code, status):
|
||||
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)}})
|
||||
|
||||
@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)
|
||||
|
||||
@app.get(
|
||||
"/api/v1/health",
|
||||
tags=["Health"],
|
||||
summary="Health Check",
|
||||
description="Check the operational health and readiness of the service.",
|
||||
)
|
||||
async def health_check() -> dict[str, str]:
|
||||
"""Return the service health status."""
|
||||
return {"status": "healthy"}
|
||||
@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):
|
||||
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'})
|
||||
|
||||
Reference in New Issue
Block a user