#!/usr/bin/env python3 """Конкурентная идемпотентность через разные реплики (lab3, уровни 3–4). Сценарий на каждый раунд: A) PARALLEL запросов одновременно отправляют ОДИН И ТОТ ЖЕ ключ и одинаковое тело. Ожидаем: все 201, у всех один и тот же Message.id, ответы пришли от >=2 реплик, в истории ровно одно сообщение с этим текстом. B) Тот же ключ, но половина запросов с другим телом. Ожидаем: побеждает ровно одно тело; запросы с ним — 201 и один id, запросы с другим телом — 409; дублей нет. Каждый запрос — отдельное TCP-соединение, поэтому HAProxy (roundrobin) раскладывает их по репликам. Токены только в памяти; синтетические пользователи создаются заново. python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16 """ import argparse import json import sys import threading import urllib.error import urllib.request import uuid from collections import Counter from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from client import Client # noqa: E402 (публичный клиент тестов: bootstrap пользователей/чата) def post(base, token, chat_id, key, text, barrier, out, idx): data = json.dumps({"text": text}).encode() req = urllib.request.Request( base + "/api/v1/chats/" + chat_id + "/messages", data=data, method="POST", headers={"Authorization": "Bearer " + token, "Content-Type": "application/json", "Idempotency-Key": key, "Connection": "close"}) barrier.wait() try: with urllib.request.urlopen(req, timeout=10) as r: out[idx] = (r.status, json.loads(r.read()), r.headers.get("X-Instance-Id"), text) except urllib.error.HTTPError as e: out[idx] = (e.code, None, e.headers.get("X-Instance-Id"), text) except Exception as e: # noqa: BLE001 — считаем любую сетевую ошибку out[idx] = (0, repr(e), None, text) def burst(base, token, chat_id, key, texts): barrier = threading.Barrier(len(texts)) out = [None] * len(texts) threads = [threading.Thread(target=post, args=(base, token, chat_id, key, t, barrier, out, i)) for i, t in enumerate(texts)] for t in threads: t.start() for t in threads: t.join() return out def history_texts(c, actor, chat): from urllib.parse import quote texts, path = [], "/api/v1/chats/" + chat["id"] + "/messages?limit=100" while True: page = c.call("GET", path, actor=actor, schema="MessagePage")["json"] texts += [m["text"] for m in page["items"]] if page["next_cursor"] is None: return texts path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="") def main(): p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) p.add_argument("--base-url", default="http://localhost:8080") p.add_argument("--rounds", type=int, default=20) p.add_argument("--parallel", type=int, default=16) p.add_argument("--output") a = p.parse_args() base = a.base_url.rstrip("/") c = Client(base) alice, _bob, _eve, chat = c.bootstrap() token = alice["token"] problems, instances = [], Counter() stats = {"same_body": Counter(), "conflicting_body": Counter()} for rnd in range(a.rounds): # A) одинаковое тело key, text = "same-" + uuid.uuid4().hex, "Конкурентный повтор " + uuid.uuid4().hex res = burst(base, token, chat["id"], key, [text] * a.parallel) stats["same_body"].update(str(r[0]) for r in res) ids = {r[1]["id"] for r in res if r[0] == 201} seen = {r[2] for r in res if r[2]} instances.update(r[2] for r in res if r[2]) if any(r[0] != 201 for r in res) or len(ids) != 1: problems.append("round %d same-body: statuses=%s ids=%d" % (rnd, Counter(r[0] for r in res), len(ids))) if len(seen) < 2: problems.append("round %d: only %d replica(s) answered" % (rnd, len(seen))) # B) тот же ключ, два разных тела вперемешку key = "mixed-" + uuid.uuid4().hex t1, t2 = "Тело A " + key, "Тело B " + key res = burst(base, token, chat["id"], key, [t1, t2] * (a.parallel // 2)) stats["conflicting_body"].update(str(r[0]) for r in res) winners = {r[3] for r in res if r[0] == 201} ids = {r[1]["id"] for r in res if r[0] == 201} bad = [r[0] for r in res if r[0] not in (201, 409)] losers_ok = all(r[0] == 409 for r in res if r[3] not in winners) if len(winners) != 1 or len(ids) != 1 or bad or not losers_ok: problems.append("round %d mixed-body: winners=%d ids=%d bad=%s" % (rnd, len(winners), len(ids), bad)) texts = history_texts(c, alice, chat) dupes = [t for t, n in Counter(texts).items() if n > 1] if dupes: problems.append("duplicated messages in history: %d" % len(dupes)) summary = { "rounds": a.rounds, "parallel_per_burst": a.parallel, "requests_total": a.rounds * a.parallel * 2, "status_counts": {k: dict(v) for k, v in stats.items()}, "replicas_answered": len(instances), "requests_per_replica": sorted(instances.values()), "messages_in_history": len(texts), "expected_messages": a.rounds * 2, "duplicates": len(dupes), "problems": problems, } if len(texts) != a.rounds * 2: problems.append("history has %d messages, expected %d" % (len(texts), a.rounds * 2)) print(json.dumps(summary, ensure_ascii=False, indent=2)) if a.output: Path(a.output).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print("PASS" if not problems else "FAIL") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())