"""Cookie-only identity and shared backend services, lazily constructed.""" from datetime import timedelta import json from typing import Annotated from fastapi import Depends, Header, HTTPException, Request from sqlalchemy.engine import Engine from app.infrastructure.database import create_database from app.modules.documents.settings import IngestionSettings from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, check_origin, verify_csrf_token from app.modules.voice.lifecycle import LiveLifecycleService from app.modules.voice.configuration import VoiceSettings from app.modules.knowledge.service import SearchService from app.modules.knowledge.langchain_tool import SearchToolRunner from app.modules.knowledge.calibration import load_cutoff _ENGINE = _AUTH_SERVICE = _LIFECYCLE_SERVICE = _TOOL_RUNNER = _SEARCH_SERVICE = None def get_voice_settings(): return VoiceSettings() def error(code): code = {'SESSION_NOT_FOUND':'NOT_FOUND','CONVERSATION_NOT_FOUND':'NOT_FOUND', 'SESSION_REVOKED':'AUTH_REQUIRED','SESSION_EXPIRED':'AUTH_REQUIRED','ACCOUNT_DISABLED':'AUTH_REQUIRED', 'CSRF_TOKEN_INVALID':'CSRF_INVALID','FORBIDDEN_ORIGIN':'FORBIDDEN','SERVICE_BUSY':'RATE_LIMITED', 'SERVICE_UNAVAILABLE':'DEPENDENCY_UNAVAILABLE'}.get(code,code) codes = { 'AUTH_REQUIRED': 401, 'INVALID_CREDENTIALS': 401, 'ACCOUNT_DISABLED': 401, 'SESSION_REVOKED': 401, 'SESSION_EXPIRED': 401, 'CSRF_TOKEN_INVALID': 403, 'FORBIDDEN_ORIGIN': 403, 'CONVERSATION_NOT_FOUND': 404, 'SESSION_NOT_FOUND': 404, 'CALIBRATION_REQUIRED': 503, 'LIVE_PROVIDER_UNAVAILABLE': 503, 'SERVICE_BUSY': 429, 'MODE_MISMATCH': 409, 'CONVERSATION_CLOSED': 409, 'CONVERSATION_STALE': 409, 'LIVE_SESSION_BUSY': 409, 'LIVE_SESSION_UNUSABLE': 409, 'IDEMPOTENCY_CONFLICT': 409, 'CONTEXT_REVOKED': 409, 'LIVE_SESSION_EXPIRED':409, 'NOT_FOUND':404,'CSRF_INVALID':403,'FORBIDDEN':403,'RATE_LIMITED':429,'DEPENDENCY_UNAVAILABLE':503, } if code not in codes: code = 'DEPENDENCY_UNAVAILABLE' return HTTPException(codes.get(code, 503), detail={'code': code, 'message': 'Request could not be completed.'}) def get_engine(): global _ENGINE if _ENGINE is None: _ENGINE = create_database(IngestionSettings().database_url.get_secret_value()) return _ENGINE def get_auth_service(engine: Annotated[Engine, Depends(get_engine)]): global _AUTH_SERVICE if _AUTH_SERVICE is None or _AUTH_SERVICE.engine is not engine: _AUTH_SERVICE = AuthService(engine, session_lifetime=timedelta(seconds=VoiceSettings().auth_session_seconds)) return _AUTH_SERVICE def get_lifecycle_service(engine: Annotated[Engine, Depends(get_engine)]): global _LIFECYCLE_SERVICE if _LIFECYCLE_SERVICE is None or _LIFECYCLE_SERVICE.engine is not engine: _LIFECYCLE_SERVICE = LiveLifecycleService(engine, session_ttl=timedelta(seconds=VoiceSettings().live_session_seconds)) return _LIFECYCLE_SERVICE def get_tool_runner(): global _TOOL_RUNNER if _TOOL_RUNNER is None: _TOOL_RUNNER = SearchToolRunner() return _TOOL_RUNNER def get_search_service(engine: Annotated[Engine, Depends(get_engine)]): global _SEARCH_SERVICE if _SEARCH_SERVICE is None or _SEARCH_SERVICE.engine is not engine: settings = IngestionSettings() path = VoiceSettings().search_calibration_report cutoff = None if path is not None: try: cutoff = load_cutoff(json.loads(path.read_text(encoding='utf-8'))) except (ValueError, OSError, KeyError, TypeError, AttributeError): raise error('CALIBRATION_REQUIRED') from None from app.worker import factories _, provider_factory = factories(settings) provider, counter = provider_factory(settings.processing_profile()) _SEARCH_SERVICE = SearchService(engine, settings, provider, counter, cutoff=cutoff) return _SEARCH_SERVICE def get_current_user(request: Request, auth_service: Annotated[AuthService, Depends(get_auth_service)]) -> UserContext: try: return auth_service.get_current_user(request.cookies.get(COOKIE_NAME)) except ValueError: raise error('AUTH_REQUIRED') from None def require_origin(request: Request, config: Annotated[VoiceSettings, Depends(get_voice_settings)]): if not check_origin(request.headers.get('origin'), request.headers.get('host'), config.trusted_origins, config.trusted_hosts, required=True): raise error('FORBIDDEN_ORIGIN') def require_csrf(request: Request, config: Annotated[VoiceSettings, Depends(get_voice_settings)], x_csrf_token: Annotated[str | None, Header()] = None): require_origin(request, config) if not verify_csrf_token(request.cookies.get(COOKIE_NAME), x_csrf_token): raise error('CSRF_TOKEN_INVALID')