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
+50 -1
View File
@@ -4,10 +4,13 @@ from contextlib import asynccontextmanager
from httpx import AsyncClient
from conftest import keyed, make_chat, register, resolve, running_app
from conftest import actor, keyed, make_chat, register, resolve, running_app, scalar
from fakes import MemoryObjectStorage
from messenger.attachments.application.ports import ObjectStorage
from messenger.messaging.application import handlers
from messenger.messaging.domain.events import MessagePosted
from messenger.shared.application.messagebus import EventBus
from pictures import SAMPLE, png
MARKER = "текст-который-не-должен-утечь-при-таймауте"
@@ -95,3 +98,49 @@ async def test_healthcheck_stays_fast(client: AsyncClient) -> None:
started = loop.time()
assert (await client.get("/health/live")).status_code == 200
assert loop.time() - started < 1.0
async def trickled(data: bytes, size: int, delay: float) -> AsyncIterator[bytes]:
for start in range(0, len(data), size):
await asyncio.sleep(delay)
yield data[start : start + size]
async def upload(client: AsyncClient, user: dict, chat: dict, body: AsyncIterator[bytes]):
return await client.post(
f"/api/v1/chats/{chat['id']}/attachments?filename=slow.png",
content=body,
headers={**actor(user), "Content-Type": "image/png"},
)
async def test_steady_slow_transfer_outlives_the_request_timeout() -> None:
picture = png(16, 16, size=1 << 20)
async with running_app(request_timeout_seconds=0.4, min_transfer_rate_bytes=16_384) as client:
alice, chat = await prepared(client)
loop = asyncio.get_running_loop()
started = loop.time()
uploaded = await upload(client, alice, chat, trickled(picture, 65_536, 0.1))
assert uploaded.status_code == 201, uploaded.text
assert loop.time() - started > 1.0
store = await resolve(client, ObjectStorage)
assert isinstance(store, MemoryObjectStorage)
store.delay = 0.1
started = loop.time()
content = await client.get(
f"/api/v1/attachments/{uploaded.json()['id']}/content", headers=actor(alice)
)
assert (content.status_code, content.content) == (200, picture)
assert loop.time() - started > 1.0
async def test_body_slower_than_the_minimal_rate_is_cut() -> None:
async with running_app(request_timeout_seconds=0.3, min_transfer_rate_bytes=1 << 20) as client:
alice, chat = await prepared(client)
before = await scalar("SELECT count(*) FROM attachments")
loop = asyncio.get_running_loop()
started = loop.time()
response = await upload(client, alice, chat, trickled(SAMPLE, 4_096, 0.1))
assert (response.status_code, response.json()["error"]["code"]) == (503, "unavailable")
assert loop.time() - started < 1.0
assert await scalar("SELECT count(*) FROM attachments") == before