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.
This commit is contained in:
+133
-3
@@ -1,6 +1,10 @@
|
||||
"""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
|
||||
@@ -10,22 +14,41 @@ from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, chec
|
||||
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.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,
|
||||
@@ -39,6 +62,105 @@ def error(code):
|
||||
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:
|
||||
@@ -71,13 +193,15 @@ 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
|
||||
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):
|
||||
raise error('CALIBRATION_REQUIRED') from None
|
||||
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())
|
||||
@@ -102,3 +226,9 @@ def require_csrf(request: Request, config: Annotated[VoiceSettings, Depends(get_
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user