chore: carry over lab 1 solution into lab 2 skeleton
Copy the committed lab 1 sources as-is: src/, student-tests/, bench/, Dockerfile, docker-compose.yml, pyproject.toml, uv.lock, .python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/, openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays in the lab 1 repository. Merge the new skeleton files with own sections: Makefile (lab 2 targets plus own run, docker, bench and common targets), .gitignore, .dockerignore and .env.example. Rename the image to mtusi-messenger:lab2 and point AGENTS.md at lab 2. The application is still the in-memory lab 1 implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""Гонки: одновременные запросы по отдельным соединениям."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api_client import API, Api, order_key, unique_username
|
||||
from contract import assert_error, assert_ok
|
||||
|
||||
CLIENTS = 10
|
||||
MESSAGES_PER_CLIENT = 10
|
||||
HISTORY_PAGE = 30
|
||||
|
||||
|
||||
def run_together[T](work: Callable[[Api, int], T], base_url: str) -> list[T]:
|
||||
"""`CLIENTS` потоков со своим соединением стартуют за барьером."""
|
||||
barrier = threading.Barrier(CLIENTS)
|
||||
|
||||
def client(number: int) -> T:
|
||||
with Api(base_url) as own:
|
||||
# соединение открыто до барьера: после него сразу запросы
|
||||
own.request("GET", "/health/live")
|
||||
barrier.wait()
|
||||
return work(own, number)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
||||
return list(pool.map(client, range(CLIENTS)))
|
||||
|
||||
|
||||
def max_in_flight(spans: list[tuple[float, float]]) -> int:
|
||||
"""Сколько запросов максимум было в полёте одновременно."""
|
||||
# при равенстве времени конец считается раньше начала
|
||||
events = sorted(
|
||||
[(start, 1) for start, _ in spans] + [(end, -1) for _, end in spans],
|
||||
)
|
||||
current = peak = 0
|
||||
for _, delta in events:
|
||||
current += delta
|
||||
peak = max(peak, current)
|
||||
return peak
|
||||
|
||||
|
||||
@pytest.mark.spec("data-storage", "100 сообщений от 10 клиентов")
|
||||
def test_hundred_messages_from_ten_clients(api: Api, base_url: str) -> None:
|
||||
actors = [
|
||||
api.register(display_name=f"Racer {number}")
|
||||
for number in range(CLIENTS)
|
||||
]
|
||||
chat = api.create_chat(actors[0], *actors[1:], title="Race")
|
||||
path = f"{API}/chats/{chat['id']}/messages"
|
||||
|
||||
def send_all(
|
||||
own: Api,
|
||||
number: int,
|
||||
) -> list[tuple[str, httpx.Response, float, float]]:
|
||||
results = []
|
||||
for index in range(MESSAGES_PER_CLIENT):
|
||||
text = f"race-{number}-{index}"
|
||||
start = time.monotonic()
|
||||
resp = own.request(
|
||||
"POST",
|
||||
path,
|
||||
actor=actors[number],
|
||||
json={"text": text},
|
||||
)
|
||||
results.append((text, resp, start, time.monotonic()))
|
||||
return results
|
||||
|
||||
results = [
|
||||
row for rows in run_together(send_all, base_url) for row in rows
|
||||
]
|
||||
statuses = Counter(resp.status_code for _, resp, _, _ in results)
|
||||
peak = max_in_flight([(start, end) for _, _, start, end in results])
|
||||
|
||||
assert statuses == {201: CLIENTS * MESSAGES_PER_CLIENT}, statuses
|
||||
created = {}
|
||||
for text, resp, _, _ in results:
|
||||
message = assert_ok(resp, 201, "Message")
|
||||
assert message["text"] == text
|
||||
created[message["id"]] = message
|
||||
|
||||
pages = api.message_pages(actors[0], chat["id"], limits=(HISTORY_PAGE,))
|
||||
items = [item for page in pages for item in page["items"]]
|
||||
ids = [item["id"] for item in items]
|
||||
print(
|
||||
f"race: {CLIENTS} clients x {MESSAGES_PER_CLIENT} messages, "
|
||||
f"statuses {dict(statuses)}, max in flight {peak}; "
|
||||
f"history: {len(items)} messages, {len(set(ids))} unique ids, "
|
||||
f"{len(pages)} pages by {HISTORY_PAGE}",
|
||||
)
|
||||
|
||||
assert peak >= 2, "requests did not overlap: race is not proven"
|
||||
assert len(items) == CLIENTS * MESSAGES_PER_CLIENT
|
||||
assert len(set(ids)) == len(ids)
|
||||
assert set(ids) == created.keys()
|
||||
assert items == sorted(created.values(), key=order_key)
|
||||
senders = {actor.id for actor in actors}
|
||||
assert {item["sender_id"] for item in items} == senders
|
||||
|
||||
|
||||
@pytest.mark.spec("users", "Одновременная регистрация")
|
||||
@pytest.mark.spec("data-storage", "Гонка за username")
|
||||
def test_same_username_at_once(base_url: str) -> None:
|
||||
username = unique_username()
|
||||
|
||||
def register(own: Api, number: int) -> tuple[httpx.Response, float, float]:
|
||||
start = time.monotonic()
|
||||
resp = own.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={"username": username, "display_name": f"Racer {number}"},
|
||||
)
|
||||
return resp, start, time.monotonic()
|
||||
|
||||
results = run_together(register, base_url)
|
||||
statuses = Counter(resp.status_code for resp, _, _ in results)
|
||||
peak = max_in_flight([(start, end) for _, start, end in results])
|
||||
print(
|
||||
f"username race: {CLIENTS} clients, statuses {dict(statuses)}, "
|
||||
f"max in flight {peak}",
|
||||
)
|
||||
|
||||
assert peak >= 2, "requests did not overlap: race is not proven"
|
||||
assert statuses == {201: 1, 409: CLIENTS - 1}, statuses
|
||||
for resp, _, _ in results:
|
||||
if resp.status_code == 409:
|
||||
assert_error(resp, 409)
|
||||
else:
|
||||
assert assert_ok(resp, 201, "User")["username"] == username
|
||||
Reference in New Issue
Block a user