"""Bounded HTTP adapter; authentication remains on the registered routes.""" import json from fastapi import HTTPException from starlette.concurrency import run_in_threadpool import psycopg from app.discovery.repository import DiscoveryRepository MAX_BODY = 1024 * 1024 async def dispatch(method, request=None, **kwargs): if request is not None: chunks = [] size = 0 async for chunk in request.stream(): size += len(chunk) if size > MAX_BODY: raise HTTPException(413, "discovery_payload_too_large") chunks.append(chunk) try: def invalid_constant(_): raise ValueError("Non-finite JSON number") kwargs["body"] = json.loads( b"".join(chunks), parse_constant=invalid_constant ) except (ValueError, UnicodeDecodeError, RecursionError): raise HTTPException(422, "discovery_invalid_json") try: return await run_in_threadpool(getattr(DiscoveryRepository(), method), **kwargs) except ( psycopg.errors.LockNotAvailable, psycopg.errors.QueryCanceled, psycopg.errors.DeadlockDetected, ): raise HTTPException(409, "discovery_concurrent_change_retry") except psycopg.DataError: raise HTTPException(422, "discovery_invalid_value") except psycopg.IntegrityError: raise HTTPException(409, "discovery_identity_conflict")