Files
mtusi2026lab2/student-tests/api/test_concurrency.py
T
ArtyomandClaude Opus 5.5 e927afdb09 Carry over the lab 3 fixes made after 61c0c28
Bring the system changes of lab 3 from 61c0c28..72a1e57 onto the lab 4
code, resolving each conflict by meaning and keeping everything lab 4
added:

- a message is posted with one SQL statement under the chat row lock,
  and the attachment links go into the same statement; a foreign key
  violation on the attachment link still answers 404 and leaves nothing
  behind. Text and the attachment list are checked before the write, an
  outsider gets 404 for both, as before the carry over;
- the request pipeline counts the body bytes actually received against
  the limit of the route, so a chunked body over 1 MiB gets 413 and the
  upload route keeps its MAX_UPLOAD_BYTES limit;
- a request cancelled at shutdown gets 503 unavailable in the contract
  format, the worker waits a second less than the rest of the shutdown
  budget, SHUTDOWN_TIMEOUT_SECONDS becomes 6 s and the stop hooks 7 s;
- readiness sits behind a Readiness port with the draining flag in
  shared infrastructure, and the drain window is logged through Logger;
- logout revokes through SessionRevocations and withdraws the mark when
  PostgreSQL rejects the delete; an empty cursor is 400;
- EventBus.project is gone, the sweep test subscribes and waits on a
  queue; domain tests check attachment_list instead of Chat.post;
- make up waits for every replica in the balancer, BASE_URL follows the
  lb port, the image is tagged by the compose project, retry-check and
  faults-evidence are added, detection runs three times, failover-each
  and rolling-update record the stand usage, CI checks numeric uids.
  down also takes the tools and reconcile profiles of lab 4.

Track 1 tooling of lab 3 (scaling.py, its samplers, tools/ and the CPU
pinning of api, lb, valkey and k6) stays out; stand-usage.sh queries the
database size itself instead of the track 1 sampler.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:25:23 +03:00

108 lines
4.2 KiB
Python

import asyncio
from datetime import UTC, datetime, timedelta
from urllib.parse import quote
from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, keyed, make_chat, register
from messenger.shared.infrastructure.clock import MonotonicUtcClock
CLIENTS = 10
PER_CLIENT = 10
TOTAL = CLIENTS * PER_CLIENT
async def drain(client: AsyncClient, chat: dict, reader: dict) -> list[dict]:
collected: list[dict] = []
cursor: str | None = None
while True:
query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
page = (
await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader))
).json()
collected.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return collected
async def flood(client: AsyncClient, chat: dict, sender: dict) -> list[int]:
async def writer(worker: int) -> list[int]:
codes = []
for index in range(PER_CLIENT):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"нагрузка-{worker}-{index}"},
headers=keyed(sender),
)
codes.append(response.status_code)
return codes
batches = await asyncio.gather(*(writer(worker) for worker in range(CLIENTS)))
return [code for batch in batches for code in batch]
async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
codes = await flood(client, chat, alice)
assert codes.count(201) == TOTAL, f"неуспешные ответы: {set(codes) - {201}}"
history = await drain(client, chat, bob)
assert len(history) == TOTAL
assert len({item["id"] for item in history}) == TOTAL
assert len({item["text"] for item in history}) == TOTAL
keys = [(item["created_at"], item["id"]) for item in history]
assert keys == sorted(keys), "история не упорядочена по (created_at, id)"
stamps = [item["created_at"] for item in history]
assert len(set(stamps)) == TOTAL, "created_at внутри чата обязан строго возрастать"
async def test_history_follows_the_clock_but_never_moves_back(
monkeypatch: pytest.MonkeyPatch, client: AsyncClient
) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
base = datetime.now(UTC) + timedelta(minutes=10)
stamps = []
for moment in (base, base - timedelta(minutes=5), base + timedelta(seconds=5)):
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self, moment=moment: moment)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "часы"}, headers=keyed(alice)
)
stamps.append(datetime.fromisoformat(response.json()["created_at"]))
assert stamps == [base, base + timedelta(microseconds=1), base + timedelta(seconds=5)]
async def test_parallel_registration_keeps_username_unique(client: AsyncClient) -> None:
body = {"username": f"race_{uuid4().hex[:12]}", "display_name": "Гонка", "password": PASSWORD}
responses = await asyncio.gather(*(client.post("/api/v1/users", json=body) for _ in range(20)))
codes = [response.status_code for response in responses]
assert codes.count(201) == 1
assert codes.count(409) == len(codes) - 1
async def test_parallel_chat_creation_is_atomic(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
responses = await asyncio.gather(
*(
client.post(
"/api/v1/chats",
json={"title": f"Чат {index}", "member_ids": [alice["id"], bob["id"]]},
headers=actor(alice),
)
for index in range(20)
)
)
assert all(response.status_code == 201 for response in responses)
listed = (await client.get("/api/v1/chats?limit=100", headers=actor(bob))).json()
assert len(listed["items"]) == 20
keys = [(item["created_at"], item["id"]) for item in listed["items"]]
assert keys == sorted(keys)