"""lab3: Idempotency-Key у POST /chats/{id}/messages. Запуск при запущенном стенде: make idempotency (или вместе со всеми: make student-test). Все запросы идут через балансировщик, поэтому повторы попадают на разные реплики. - повтор того же запроса (в том числе через другую реплику) -> тот же 201 и то же сообщение; - 20 одновременных запросов с одним ключом через обе реплики -> ровно одно сообщение; - одновременные разные тела с одним ключом -> одно сообщение, остальным 409; - форматирование JSON не важно; другое тело с тем же ключом -> 409; - область ключа: пользователь + чат (тот же ключ у другого пользователя или в другом чате независим); - нет ключа или он неверный -> 400; ошибка 400 ключ не «занимает»; - повтор заново проверяет сессию (401 после logout) и доступ к чату (404 постороннему). """ import threading import unittest import uuid from collections import Counter from concurrent.futures import ThreadPoolExecutor from helpers import Client, idempotency, login, read_history PARALLEL = 20 class IdempotencyTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = Client() cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap() def path(self, chat=None): return f"/api/v1/chats/{(chat or self.chat)['id']}/messages" def post(self, actor, text, key, expected=201, chat=None, api=None): return (api or self.api).call("POST", self.path(chat), expected, actor=actor, body={"text": text}, headers=idempotency(key), schema="Message" if expected == 201 else None) def count_text(self, text, chat=None): history, _ = read_history(self.api, self.alice, (chat or self.chat)["id"]) return sum(1 for message in history if message["text"] == text) def test_replay_through_another_replica_returns_same_message(self): key, text = uuid.uuid4().hex, "повтор " + uuid.uuid4().hex first = self.post(self.alice, text, key) replies = [self.post(self.alice, text, key) for _ in range(4)] self.assertTrue(all(reply["json"] == first["json"] for reply in replies), "replay differs") instances = {first["headers"]["X-Instance-Id"]} | {r["headers"]["X-Instance-Id"] for r in replies} self.assertGreaterEqual(len(instances), 2, "replays did not switch replica") self.assertEqual(self.count_text(text), 1) print(f"\n 1 запрос + 4 повтора через реплики {sorted(instances)}: 201 и то же сообщение, в истории 1") def test_parallel_same_key_through_replicas_creates_one_message(self): key, text = uuid.uuid4().hex, "параллельно " + uuid.uuid4().hex start = threading.Barrier(PARALLEL) def send(_): client = Client() # у каждого «клиента» свои соединения start.wait() return self.post(self.alice, text, key, api=client) with ThreadPoolExecutor(max_workers=PARALLEL) as pool: replies = list(pool.map(send, range(PARALLEL))) ids = {reply["json"]["id"] for reply in replies} instances = Counter(reply["headers"]["X-Instance-Id"] for reply in replies) self.assertEqual(len(ids), 1, "different messages for one key") self.assertGreaterEqual(len(instances), 2, "parallel requests did not reach both replicas") self.assertEqual(self.count_text(text), 1, "duplicate message created") print(f"\n {PARALLEL} одновременных POST с одним ключом через реплики {dict(instances)}: " f"все 201 с одним id, в истории 1 сообщение") def test_parallel_different_bodies_same_key(self): key = uuid.uuid4().hex texts = [f"тело {n} {key}" for n in range(10)] start = threading.Barrier(len(texts)) def send(text): client = Client() start.wait() reply = client.call("POST", self.path(), [201, 409], actor=self.alice, body={"text": text}, headers=idempotency(key)) return text, reply["status"], reply["json"] with ThreadPoolExecutor(max_workers=len(texts)) as pool: results = list(pool.map(send, texts)) created = [text for text, status, _ in results if status == 201] self.assertEqual(len(created), 1, f"expected exactly one 201, got {len(created)}") self.assertEqual(sum(1 for _, status, _ in results if status == 409), len(texts) - 1) self.assertEqual(sum(self.count_text(text) for text in texts), 1) print(f"\n {len(texts)} одновременных разных тел с одним ключом: 201 x1, 409 x{len(texts) - 1}, " f"в истории 1 сообщение") def test_json_formatting_does_not_matter(self): key, text = uuid.uuid4().hex, "формат " + uuid.uuid4().hex first = self.post(self.alice, text, key)["json"] for raw in (('{ "text" : "%s" }' % text).encode("utf-8"), ('{\n "text": "%s"\n}' % text).encode("utf-8")): again = self.api.call("POST", self.path(), 201, actor=self.alice, raw=raw, schema="Message", headers={"Content-Type": "application/json", **idempotency(key)})["json"] self.assertEqual(again, first) print("\n тот же JSON с другими пробелами и переносами -> тот же 201 и то же сообщение") def test_same_key_other_body_is_409(self): key, text = uuid.uuid4().hex, "оригинал " + uuid.uuid4().hex self.post(self.alice, text, key) error = self.post(self.alice, text + " (изменено)", key, expected=409)["json"]["error"] self.assertEqual(error["code"], "conflict") self.assertEqual(self.count_text(text), 1) self.assertEqual(self.count_text(text + " (изменено)"), 0) print("\n другой текст с тем же ключом -> 409 conflict, второе сообщение не создано") def test_key_scope_is_user_and_chat(self): key, text = uuid.uuid4().hex, "область " + uuid.uuid4().hex other_chat = self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat", body={"title": "второй чат", "member_ids": [self.alice["id"], self.bob["id"]]})["json"] by_alice = self.post(self.alice, text, key)["json"] by_bob = self.post(self.bob, text, key)["json"] in_other_chat = self.post(self.alice, text, key, chat=other_chat)["json"] self.assertEqual(len({by_alice["id"], by_bob["id"], in_other_chat["id"]}), 3) print("\n тот же ключ у другого пользователя и в другом чате -> независимые сообщения") def test_key_is_required_and_validated(self): text = "без ключа " + uuid.uuid4().hex self.api.call("POST", self.path(), 400, actor=self.alice, body={"text": text}) for bad in ("", "a" * 129, "пробел есть", "a b", "slash/no", "ключ"): # Не-ASCII отправляем как есть, байтами UTF-8 (так их пришлёт реальный клиент). header = bad.encode("utf-8").decode("latin-1") self.api.call("POST", self.path(), 400, actor=self.alice, body={"text": text}, headers={"Idempotency-Key": header}) self.post(self.alice, text + " 128", "k" * 128) self.post(self.alice, text + " punct", "Az09._:-" + uuid.uuid4().hex) self.assertEqual(self.count_text(text), 0) print("\n нет ключа, пустой, 129 символов, пробел, '/', кириллица -> 400; 128 символов и ._:- -> 201") def test_failed_request_does_not_burn_key(self): key, text = uuid.uuid4().hex, "после ошибки " + uuid.uuid4().hex self.post(self.alice, " ", key, expected=400) # пустой текст: 400, ничего не сохранено created = self.post(self.alice, text, key)["json"] self.assertEqual(created["text"], text) print("\n с тем же ключом: сначала 400 (пустой текст), потом 201 — ошибка ключ не заняла") def test_replay_rechecks_session_and_access(self): key, text = uuid.uuid4().hex, "проверка доступа " + uuid.uuid4().hex frank = self.api.user("frank") chat = self.api.call("POST", "/api/v1/chats", 201, actor=frank, schema="Chat", body={"title": "frank", "member_ids": [frank["id"], self.bob["id"]]})["json"] first = self.post(frank, text, key, chat=chat)["json"] self.post(self.eve, text, key, expected=404, chat=chat) # посторонний: 404, а не сохранённый ответ token = frank["token"] self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=frank) self.post(frank, text, key, expected=401, chat=chat) # отозванный токен: 401 session = login(self.api, frank["registration"]["username"], frank["registration"]["password"]) frank_again = dict(frank, token=session["token"]) # новый вход, новый токен self.assertNotEqual(frank_again["token"], token) again = self.post(frank_again, text, key, chat=chat)["json"] self.assertEqual(again, first) print("\n повтор: посторонний -> 404, после logout -> 401, после нового входа -> то же сообщение") if __name__ == "__main__": unittest.main()