Files
rag-technical-docs-assistant/app/api/v1/dependencies.py
11linear11 a73a496c54 feat(backend): deliver Phase 3 document and voice integration
Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
2026-10-09 17:43:52 -04:00

235 lines
10 KiB
Python

"""Cookie-only identity and shared backend services, lazily constructed."""
import asyncio
from datetime import timedelta
import json
import tempfile
from pathlib import Path
from app.infrastructure.json_processing import (JSON_SLOTS, INLINE_BYTES, owned_io, validate_json, validate_spool)
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, prepare_search_tools
from app.modules.knowledge.calibration import load_cutoff
_ENGINE = _AUTH_SERVICE = _LIFECYCLE_SERVICE = _TOOL_RUNNER = _SEARCH_SERVICE = None
# ReviewDecision: 10,000 group IDs + 16 checks, each <=500 characters,
# note <=2,000 characters. A Unicode scalar needs at most 12 JSON bytes
# (escaped surrogate pair), exceeding raw UTF-8 and other escape forms.
# Include quotes/commas, fixed fields and 1 KiB of formatting allowance.
MAX_DECISION_BYTES = (10000 + 16) * (500 * 12 + 3) + 2000 * 12 + 1024
MAX_SELECTION_BYTES = 1 * 1024 * 1024 # 1 MiB (up to 10,000 document UUIDs)
JSON_RECEIVE_SECONDS = 15
RETRY_RECEIVE_SECONDS = 5
def get_voice_settings():
return VoiceSettings()
def get_ingestion_settings():
return IngestionSettings()
def error(code):
code = {'SESSION_NOT_FOUND':'NOT_FOUND','CONVERSATION_NOT_FOUND':'NOT_FOUND',
'DOCUMENT_NOT_FOUND':'NOT_FOUND', 'ADMINISTRATOR_REQUIRED':'FORBIDDEN',
'INVALID_SELECTION':'VALIDATION_ERROR',
'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 = {
'FILE_TOO_LARGE':413, 'PAYLOAD_TOO_LARGE':413, 'UNSUPPORTED_FILE_TYPE':415, 'INVALID_FILE':422,
'VALIDATION_ERROR':422, 'REVISION_CONFLICT':409, 'DOCUMENT_NOT_READY':409,
'DOCUMENT_NOT_RETRYABLE':409, 'EXTRACTION_REVIEW_PENDING':409,
'REVIEW_STALE':409, 'REVIEW_ALREADY_DECIDED':409,
'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.'})
async def receive_json(request: Request, model_cls, max_bytes: int, timeout_seconds: float | None = None):
if timeout_seconds is None:
timeout_seconds = JSON_RECEIVE_SECONDS
content_type = request.headers.get('content-type', '')
if content_type:
media_type = content_type.split(';')[0].strip().lower()
if media_type != 'application/json':
raise error('VALIDATION_ERROR')
content_length_header = request.headers.get('content-length')
content_length = None
if content_length_header is not None:
try:
content_length = int(content_length_header)
if content_length < 0:
raise error('VALIDATION_ERROR')
if content_length > max_bytes:
raise error('PAYLOAD_TOO_LARGE')
except ValueError:
raise error('VALIDATION_ERROR')
if not JSON_SLOTS.acquire(blocking=False):
raise error('SERVICE_BUSY')
# One owner covers receive, spool, parsing and result reconstruction. A
# timed-out/cancelled caller cancels it but cannot prematurely free its slot.
task = asyncio.create_task(_receive_json(request, model_cls, max_bytes, content_length))
def completed(owner):
JSON_SLOTS.release()
if not owner.cancelled():
owner.exception() # retrieve orphaned errors after caller cancellation
task.add_done_callback(completed)
try:
return await asyncio.wait_for(asyncio.shield(task), timeout_seconds)
except TimeoutError:
task.cancel()
raise error('DEPENDENCY_UNAVAILABLE') from None
except asyncio.CancelledError:
task.cancel()
raise
except ValueError as exc:
raise error(str(exc)) from None
async def _receive_json(request, model_cls, max_bytes, content_length):
body, size, directory, spool = bytearray(), 0, None, None
try:
async for chunk in request.stream():
if len(chunk) > max_bytes - size:
raise error('PAYLOAD_TOO_LARGE')
size += len(chunk)
if spool is None and size > INLINE_BYTES:
directory = tempfile.TemporaryDirectory(prefix='rag-json-')
path = Path(directory.name) / 'payload'
spool = path.open('wb')
await owned_io(spool.write, body)
body.clear()
# Bound each copy/write, including a transport supplying one large
# message. Yield during cooperative streams that never suspend.
for offset in range(0, len(chunk), INLINE_BYTES):
piece = chunk[offset:offset + INLINE_BYTES]
if spool is None:
body.extend(piece)
else:
await owned_io(spool.write, piece)
await asyncio.sleep(0)
if not size or (content_length is not None and size != content_length):
raise error('VALIDATION_ERROR')
if spool is None:
return validate_json(body, model_cls)
await owned_io(spool.close)
spool = None
return await validate_spool(path, model_cls)
finally:
if spool is not None:
await owned_io(spool.close)
if directory is not None:
await owned_io(directory.cleanup)
async def receive_empty(request: Request, timeout_seconds: float | None = None):
if timeout_seconds is None:
timeout_seconds = RETRY_RECEIVE_SECONDS
content_length_header = request.headers.get('content-length')
if content_length_header is not None:
try:
if int(content_length_header) > 0:
raise error('VALIDATION_ERROR')
except ValueError:
raise error('VALIDATION_ERROR')
try:
async with asyncio.timeout(timeout_seconds):
async for chunk in request.stream():
if chunk:
raise error('VALIDATION_ERROR')
except TimeoutError:
raise error('DEPENDENCY_UNAVAILABLE') from None
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()
voice = VoiceSettings()
path = voice.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):
if not voice.voice_transport_testing:
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')
def require_admin(user: Annotated[UserContext, Depends(get_current_user)]):
if user.role != 'admin':
raise error('FORBIDDEN')
return user