#!/usr/bin/env python3 """ Общая идемпотентность POST сообщения через LB (lab3). python student-tests/idempotency.py --base-url http://localhost:8080 Проверяет: параллельные запросы с ОДНИМ ключом через разные реплики дают одно сообщение; другой body с тем же ключом → 409; ключ без/неверного формата → 400; порядок/пробелы в JSON не важны; область ключа — пользователь + чат. """ import argparse import json import uuid from concurrent.futures import ThreadPoolExecutor from common import Api, Report def main(): ap = argparse.ArgumentParser() ap.add_argument("--base-url", default="http://localhost:8080") ap.add_argument("--parallel", type=int, default=20) api, r = Api(ap.parse_args().base_url), Report() args = ap.parse_args() alice, bob = api.new_user("idem_a"), api.new_user("idem_b") st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "idem", "member_ids": [alice["id"], bob["id"]]}, token=alice["token"]) st, chat2, _ = api.call("POST", "/api/v1/chats", {"title": "idem2", "member_ids": [alice["id"]]}, token=alice["token"]) path, path2 = f"/api/v1/chats/{chat['id']}/messages", f"/api/v1/chats/{chat2['id']}/messages" def history(p, token): st, page, _ = api.call("GET", p + "?limit=100", token=token) return page["items"] print(f"== {args.parallel} параллельных запросов с одним ключом ==") key, text = uuid.uuid4().hex, "одно сообщение " + uuid.uuid4().hex[:6] def send(_): return api.call("POST", path, {"text": text}, token=alice["token"], headers={"Idempotency-Key": key}) with ThreadPoolExecutor(max_workers=args.parallel) as pool: res = list(pool.map(send, range(args.parallel))) codes = [x[0] for x in res] ids = {x[1]["id"] for x in res if x[0] == 201} instances = {x[2].get("X-Instance-Id") for x in res} r.check(codes.count(201) == args.parallel, f"all parallel repeats -> 201 (got {sorted(set(codes))})") r.check(len(ids) == 1, f"all responses carry the same message id ({len(ids)} distinct)") r.check(len(instances) >= 2, f"requests were served by >=2 replicas ({len(instances)})") r.check(sum(m["text"] == text for m in history(path, alice["token"])) == 1, "exactly one message in history") first = res[0][1] r.check(all(x[1] == first for x in res), "every replay returns the identical Message") print("== семантика ключа ==") st, _, _ = api.call("POST", path, {"text": "другой текст"}, token=alice["token"], headers={"Idempotency-Key": key}) r.check(st == 409, f"same key, different body -> 409 (got {st})") raw = ('{ "text" : ' + json.dumps(text, ensure_ascii=False) + ' }').encode() st, body, _ = api.raw("POST", path, raw, {"Content-Type": "application/json", "Idempotency-Key": key, "Authorization": "Bearer " + alice["token"]}) r.check(st == 201 and json.loads(body)["id"] == first["id"], f"other JSON formatting = same request (got {st})") st, other, _ = api.call("POST", path2, {"text": text}, token=alice["token"], headers={"Idempotency-Key": key}) r.check(st == 201 and other["id"] != first["id"], "same key in another chat is independent") st, bobs, _ = api.call("POST", path, {"text": text}, token=bob["token"], headers={"Idempotency-Key": key}) r.check(st == 201 and bobs["id"] != first["id"] and bobs["sender_id"] == bob["id"], "same key from another user is independent") st, _, _ = api.raw("POST", path, json.dumps({"text": "без ключа"}).encode(), {"Content-Type": "application/json", "Authorization": "Bearer " + alice["token"]}) r.check(st == 400, f"missing Idempotency-Key -> 400 (got {st})") for bad in ("has space", "x" * 129, "slash/key"): st, _, _ = api.call("POST", path, {"text": "bad key"}, token=alice["token"], headers={"Idempotency-Key": bad}) r.check(st == 400, f"invalid key {bad[:12]!r}... -> 400 (got {st})") st, _, _ = api.call("POST", path, {"text": text}, headers={"Idempotency-Key": key}) r.check(st == 401, f"replay without session -> 401, access re-checked (got {st})") print("== неопределённый результат: клиент повторяет с тем же ключом ==") key2 = uuid.uuid4().hex try: api.call("POST", path, {"text": "таймаут?"}, token=alice["token"], headers={"Idempotency-Key": key2}, timeout=0.001) except OSError: pass # ответ не дождались: записано или нет — неизвестно st, again, _ = api.call("POST", path, {"text": "таймаут?"}, token=alice["token"], headers={"Idempotency-Key": key2}) r.check(st == 201, "retry after uncertain result -> 201") r.check(sum(m["text"] == "таймаут?" for m in history(path, alice["token"])) == 1, "still exactly one message") r.finish() if __name__ == "__main__": main()