Check the token before the declared size and pace the request deadline

The pipeline now runs the guard first, so an anonymous upload with a too
large Content-Length gets 401 with WWW-Authenticate, as the contract
asks; the guard does not read the body, so 413 still comes before the
first body byte for an authenticated client.

The single request deadline cut slow but steady uploads and downloads:
a client slower than about 1.3 MB/s could not move 10 MiB in 8 s. Each
body chunk the application receives or sends now moves the deadline to
min(now, start + moved / MIN_TRANSFER_RATE_BYTES) + REQUEST_TIMEOUT,
128 KiB/s by default, like mod_reqtimeout with a ceiling: a steady
transfer lives as long as it moves, a stalled or crawling body is cut
after the request timeout as before, and the work after the last body
byte still gets at most the request timeout. The pipeline's own error
responses bypass the pacing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-30 08:53:39 +03:00
co-authored by Claude Opus 5.5
parent 96e934ed8f
commit 54099e1da3
6 changed files with 115 additions and 12 deletions
+1
View File
@@ -137,6 +137,7 @@ def create_app(
guard=guard,
instance=platform.instance_id,
limits=((UPLOAD_PATH, attachments.max_upload_bytes),),
min_rate=transport.min_transfer_rate_bytes,
)
errors.install(app, logger, ERROR_CODES, challenge_for, platform.instance_id)
app.include_router(health.router)
@@ -7,3 +7,4 @@ class TransportSettings(Settings):
docs: bool = False
max_body_bytes: int = Field(default=1_048_576, ge=4_096)
request_timeout_seconds: float = Field(default=8.0, gt=0, le=300)
min_transfer_rate_bytes: int = Field(default=131_072, ge=1_024)
+44 -7
View File
@@ -58,8 +58,44 @@ async def send_error(
await send({"type": "http.response.body", "body": body})
class Pace:
__slots__ = ("_deadline", "_moved", "_opened", "_rate", "_timeout")
def __init__(self, deadline: asyncio.Timeout, timeout: float, rate: float) -> None:
self._deadline = deadline
self._timeout = timeout
self._rate = rate
self._opened = asyncio.get_running_loop().time()
self._moved = 0
def around(self, receive: Receive, send: Send) -> tuple[Receive, Send]:
async def paced_receive() -> Message:
return self._count(await receive())
async def paced_send(message: Message) -> None:
await send(self._count(message))
return paced_receive, paced_send
def _count(self, message: Message) -> Message:
if size := len(message.get("body", b"")):
self._moved += size
moved = min(asyncio.get_running_loop().time(), self._opened + self._moved / self._rate)
self._deadline.reschedule(moved + self._timeout)
return message
class RequestPipeline:
__slots__ = ("_app", "_guard", "_instance", "_limits", "_logger", "_max_bytes", "_timeout")
__slots__ = (
"_app",
"_guard",
"_instance",
"_limits",
"_logger",
"_max_bytes",
"_min_rate",
"_timeout",
)
def __init__(
self,
@@ -70,12 +106,14 @@ class RequestPipeline:
guard: Guard,
instance: str,
limits: BodyLimits = (),
min_rate: float = 131_072,
) -> None:
self._app = app
self._logger = logger
self._max_bytes = max_bytes
self._limits = limits
self._timeout = timeout
self._min_rate = min_rate
self._guard = guard
self._instance = instance.encode()
@@ -86,9 +124,7 @@ class RequestPipeline:
incoming = header(scope, HEADER_BYTES)
request_id = incoming[:MAX_REQUEST_ID] if incoming else uuid4().hex
state = scope.setdefault("state", {})
state["request_id"] = request_id
state["actor"] = None
scope.setdefault("state", {}).update(request_id=request_id, actor=None)
started = time.perf_counter()
status_holder = [500]
answered = [False]
@@ -119,10 +155,11 @@ class RequestPipeline:
rejection: Rejection | None = None
try:
async with asyncio.timeout(self._timeout):
rejection = self._oversized(scope, limit) or await self._guard(scope)
async with asyncio.timeout(self._timeout) as deadline:
rejection = await self._guard(scope) or self._oversized(scope, limit)
if rejection is None:
await self._app(scope, limited_receive, wrapped_send)
pace = Pace(deadline, self._timeout, self._min_rate)
await self._app(scope, *pace.around(limited_receive, wrapped_send))
except Unavailable as error:
self._logger.warning(
"dependency.unavailable",