"""Проверка гонок (уровень 4). Запуск: make race 1. 10 клиентов одновременно отправляют по 10 сообщений в один чат: в истории ровно 100 сообщений, все id уникальны, ни один текст не потерян. 2. 20 клиентов одновременно регистрируют ОДИН И ТОТ ЖЕ username: ровно один получает 201, остальные 409; в базе один такой пользователь. Защита — уникальный индекс users.username в PostgreSQL, а не проверка в коде. """ import threading import time import uuid from concurrent.futures import ThreadPoolExecutor from helpers import Client, check, read_history, run CLIENTS = 10 PER_CLIENT = 10 REGISTRATIONS = 20 def concurrent_messages(api): users = [api.user(f"race{i}") for i in range(CLIENTS)] chat = api.call("POST", "/api/v1/chats", 201, actor=users[0], schema="Chat", body={"title": "race", "member_ids": [u["id"] for u in users]})["json"] path = f"/api/v1/chats/{chat['id']}/messages" start_together = threading.Barrier(CLIENTS) # все потоки стартуют одновременно def send_all(index): client = Client() # у каждого «клиента» свои HTTP-соединения start_together.wait() for n in range(PER_CLIENT): client.call("POST", path, 201, actor=users[index], body={"text": f"client-{index}-msg-{n}"}) started = time.monotonic() with ThreadPoolExecutor(max_workers=CLIENTS) as pool: list(pool.map(send_all, range(CLIENTS))) # list() пробрасывает ошибки из потоков elapsed = time.monotonic() - started history, pages = read_history(api, users[0], chat["id"], limit=25) expected = {f"client-{i}-msg-{n}" for i in range(CLIENTS) for n in range(PER_CLIENT)} print(f"messages: sent {CLIENTS * PER_CLIENT} from {CLIENTS} parallel clients in {elapsed:.2f}s") print(f"messages: read {len(history)} in {pages} pages, unique ids: {len({m['id'] for m in history})}") check(len(history) == CLIENTS * PER_CLIENT, "wrong number of messages") check(len({m["id"] for m in history}) == len(history), "duplicate message ids") check({m["text"] for m in history} == expected, "lost or corrupted message texts") print("PASS: 100 concurrent messages stored without loss or duplicates") def concurrent_registration(): username = "race_" + uuid.uuid4().hex[:12] start_together = threading.Barrier(REGISTRATIONS) def register(index): client = Client() body = {"username": username, "display_name": f"Участник {index}", "password": f"Race-password-{index:03d}"} start_together.wait() return client.call("POST", "/api/v1/users", [201, 409], body=body)["status"] with ThreadPoolExecutor(max_workers=REGISTRATIONS) as pool: statuses = list(pool.map(register, range(REGISTRATIONS))) created, conflicts = statuses.count(201), statuses.count(409) print(f"registration: {REGISTRATIONS} parallel requests for one username -> 201 x{created}, 409 x{conflicts}") check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win") print("PASS: concurrent registration of the same username created exactly one user") def main(): api = Client() concurrent_messages(api) concurrent_registration() if __name__ == "__main__": run(main)