Files
amirhosein mazaheri 21a0ea076a chore(backend): save remaining API and deployment changes
Expose frozen factual review policy, update API descriptions and Swagger settings, and adjust local deployment and embedding connectivity.

Include the requested extraction candidates and review-policy regression coverage. Validation: 31 OCR policy tests passed; staged diff whitespace checks passed.
2026-10-10 17:43:17 +03:30

223 lines
10 KiB
Python

"""D01-D04, D06-D07: authenticated adapters around existing ingestion services."""
import asyncio
from threading import BoundedSemaphore
from typing import Annotated, Literal, NamedTuple
from uuid import UUID
from fastapi import APIRouter, Depends, Header, Query, Request, Response
from app.api.v1.dependencies import (
get_engine, get_ingestion_settings, require_admin, require_csrf, error,
MAX_DECISION_BYTES, JSON_RECEIVE_SECONDS, RETRY_RECEIVE_SECONDS,
receive_json, receive_empty,
)
from app.api.v1.uploads import receive_upload
from app.infrastructure.intake_repository import SqlIntakeRepository
from app.infrastructure.worker_repository import SqlWorkerRepository
from app.infrastructure.review_repository import SqlReviewRepository
from app.infrastructure.file_store import LocalFileStore
from app.infrastructure.extraction_candidates import LocalExtractionCandidates
from app.infrastructure.blocking import blocking
from app.infrastructure.document_queries import DocumentQueries
from app.modules.documents.intake import import_document
from app.modules.documents.errors import IntakeError
from app.modules.documents.review import AdministratorIdentity, ReviewDecision
router = APIRouter(prefix='/documents', tags=['Documents'])
_DECISION_SLOTS = BoundedSemaphore(2)
class DocumentServices(NamedTuple):
settings: object
store: object
candidates: object
intake: object
worker: object
review: object
queries: object
def get_document_services(engine=Depends(get_engine), settings=Depends(get_ingestion_settings)):
store = LocalFileStore(settings.original_directory)
candidates = LocalExtractionCandidates(settings.extraction_directory, original_directory=settings.original_directory)
return DocumentServices(settings, store, candidates, SqlIntakeRepository(engine), SqlWorkerRepository(engine, settings),
SqlReviewRepository(engine, settings, candidates, store), DocumentQueries(engine, settings, store, candidates))
Services = Annotated[DocumentServices, Depends(get_document_services)]
Admin = Annotated[object, Depends(require_admin)]
Csrf = Annotated[None, Depends(require_csrf)]
Key = Annotated[UUID, Header(alias='Idempotency-Key')]
def replay_header(response, result):
if result.get('replayed'):
response.headers['Idempotency-Replayed'] = 'true'
@router.post(
'',
status_code=202,
summary='Upload Document for Ingestion',
description='Upload an original document (.pdf, .md, .docx, or image) to initiate the background ingestion and chunking pipeline.',
openapi_extra={'requestBody': {
'required': True, 'content': {'multipart/form-data': {'schema': {
'type': 'object', 'additionalProperties': False, 'required': ['file'],
'properties': {'file': {'type': 'string', 'format': 'binary'},
'title': {'type': 'string', 'maxLength': 200}}
}}}
}}
)
async def upload(request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
settings, store, _, intake, *_ = services
previous = None
try:
_, previous = await blocking(intake.lookup, settings, user.id, key)
# Known replay is bounded by its accepted length, independent of newer
# deployment admission limits. Intake still compares the exact payload.
admission = (settings.model_copy(update={'max_original_bytes': previous['size_bytes']})
if previous is not None else settings)
async with receive_upload(request, admission) as (path, filename, title):
# Cancellation cannot delete the spool while intake still owns it.
task = asyncio.create_task(asyncio.to_thread(import_document, intake, store, settings,
path=path, filename=filename, title=title, administrator_id=user.id, request_id=key))
try:
result = await asyncio.shield(task)
except asyncio.CancelledError:
while not task.done():
try:
await asyncio.shield(task)
except asyncio.CancelledError:
continue
except Exception:
break
# Retrieve a possible intake exception while preserving cancellation.
if not task.cancelled():
task.exception()
raise
replay_header(response, result)
doc = result['document']
return dict(document_id=doc['id'], job_id=doc['job']['id'], status=doc['status'],
is_active=doc['is_active'], searchable=doc['searchable'])
except IntakeError as exc:
raise error('IDEMPOTENCY_CONFLICT' if previous is not None and exc.code == 'FILE_TOO_LARGE'
else exc.code) from None
except ValueError as exc:
raise error(str(exc)) from None
@router.get(
'',
summary='List Ingested Documents',
description='List uploaded documents with optional filtering by status (queued, processing, ready, failed) and active state.',
)
def documents(user: Admin, services: Services, limit: Annotated[int, Query(ge=1, le=100)] = 20,
cursor: Annotated[str | None, Query(max_length=256)] = None,
status: Literal['queued', 'processing', 'ready', 'failed'] | None = None,
is_active: bool | None = None):
try:
return services.queries.list(user.id, limit=limit, cursor=cursor, status=status, is_active=is_active)
except IntakeError as exc:
raise error(exc.code) from None
@router.get(
'/{document_id}',
summary='Get Document Details',
description='Retrieve metadata, processing status, and job information for a specific document.',
)
def detail(document_id: UUID, user: Admin, services: Services):
try:
return services.queries.detail(user.id, document_id)
except IntakeError as exc:
raise error(exc.code) from None
@router.post(
'/{document_id}/retry',
status_code=202,
summary='Retry Failed Document Ingestion',
description='Trigger a background retry for an eligible failed document ingestion job.',
)
async def retry(document_id: UUID, request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
await receive_empty(request)
try:
result = await asyncio.to_thread(services.worker.retry, administrator_id=user.id, document_id=document_id, request_id=key,
store=services.store, candidates=services.candidates)
replay_header(response, result)
return {k: v for k, v in result.items() if k != 'replayed'}
except IntakeError as exc:
raise error(exc.code) from None
@router.get(
'/{document_id}/extraction-review',
summary='Get OCR Extraction Review Items',
description='Retrieve pending OCR extraction review items, confidence checks, and evidence hashes for a document.',
)
def review(document_id: UUID, user: Admin, services: Services,
limit: Annotated[int, Query(ge=1, le=20)] = 10,
cursor: Annotated[str | None, Query(pattern='^[0-9a-f]{64}$')] = None):
try:
result = services.review.read(AdministratorIdentity(user.id, user.organization_id), document_id, limit=limit, after=cursor)
for item in result['items']:
item['preview_path'] = (f'/api/v1/documents/{document_id}/extraction-review/{item["evidence_sha256"]}/preview'
if item.pop('preview_available') else None)
return result
except IntakeError as exc:
raise error(exc.code) from None
@router.get(
'/{document_id}/extraction-review/{evidence_sha256}/preview',
summary='Preview Extraction Review Artifact',
description='Download the visual proof snippet or rendered page image for a specific evidence hash.',
)
def preview(document_id: UUID, evidence_sha256: str, user: Admin, services: Services):
import re
if not re.fullmatch('[0-9a-f]{64}', evidence_sha256):
raise error('VALIDATION_ERROR')
try:
content, mime = services.review.preview(AdministratorIdentity(user.id, user.organization_id), document_id, evidence_sha256)
return Response(content, media_type=mime, headers={'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'})
except IntakeError as exc:
raise error(exc.code) from None
@router.post(
'/{document_id}/extraction-review/decisions',
summary='Submit Extraction Review Decision',
description='Approve or reject flagged OCR extraction blocks before proceeding to embedding chunk publication.',
openapi_extra={
'requestBody': {
'required': True,
'content': {'application/json': {'schema': ReviewDecision.model_json_schema()}}
}
},
)
async def decide(document_id: UUID, request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
payload = await receive_json(request, ReviewDecision, max_bytes=MAX_DECISION_BYTES)
try:
if not _DECISION_SLOTS.acquire(blocking=False):
raise error('SERVICE_BUSY')
try:
pending = asyncio.get_running_loop().run_in_executor(None, _apply_decision,
services.review, AdministratorIdentity(user.id, user.organization_id), document_id, key, payload)
except BaseException:
_DECISION_SLOTS.release()
raise
# Cancellation stops the caller, not a possibly committed transaction.
# The worker owns the normalized DTO and releases admission in its finally.
pending.add_done_callback(lambda future: future.exception() if not future.cancelled() else None)
result = await asyncio.shield(pending)
replay_header(response, result)
return {k: v for k, v in result.items() if k != 'replayed'}
except IntakeError as exc:
raise error(exc.code) from None
def _apply_decision(review, identity, document_id, key, payload):
try:
return review.decide(identity, document_id, request_id=key, payload=payload.model_dump(mode='json'))
finally:
_DECISION_SLOTS.release()