Files
rag-technical-docs-assistant/app/main.py
T
11linear11 996435d2ae 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.
2026-10-09 07:59:02 -04:00

118 lines
4.8 KiB
Python

"""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
@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
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'])
@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):
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.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'})