"""@module numeric-inference/admission — cap in-flight recognize calls. Probes stay open.""" from __future__ import annotations import asyncio import os from fastapi.responses import JSONResponse RECOGNIZE_PATHS = frozenset({ "/v1/recognize/lines", "/v1/recognize/numeric", "/v1/recognize/numeric:batch", }) def recognize_semaphore() -> asyncio.Semaphore: raw = os.getenv("AXIS_HTTP_CONCURRENCY", "4").strip() try: count = max(1, int(raw)) except ValueError: count = 4 return asyncio.Semaphore(count) async def admit(request, call_next, slots: asyncio.Semaphore): if request.url.path not in RECOGNIZE_PATHS: return await call_next(request) try: await asyncio.wait_for(slots.acquire(), timeout=0.05) except TimeoutError: return JSONResponse( status_code=503, content={"detail": "inference_busy"}, headers={"retry-after": "1"}, ) try: return await call_next(request) finally: slots.release()