"""Decide whether a request body is too large to read. Nothing else caps request size: uvicorn has no default, and the handlers read the whole body before looking at it. """ from collections.abc import Mapping MAX_BYTES = 512 * 1024 # far more than a 10-message history or 5 000-char TTS text MAX_FRAME_BYTES = 256 * 1024 # a single websocket frame; mic frames are a few KB _BODY_METHODS = frozenset({"POST", "PUT", "PATCH"}) def is_too_large(method: str, headers: Mapping[str, str]) -> bool: """True when the request should be refused before its body is read. A declared length over the cap is refused, and so is a body with no declared length at all — that is a chunked upload, which would otherwise stream past the check unmeasured. No browser sends chunked JSON here. A request with neither header carries no body (a bodyless POST) and is fine: rejecting those broke /api/benchmark the first time round. """ if method.upper() not in _BODY_METHODS: return False declared = headers.get("content-length") if declared is None: return bool(headers.get("transfer-encoding")) if not declared.isdigit(): return True return int(declared) > MAX_BYTES