86 lines
3.2 KiB
Python
86 lines
3.2 KiB
Python
"""Idempotency scopes and concurrent replay checks for laboratory 3."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import unittest
|
|
import uuid
|
|
|
|
import common
|
|
|
|
|
|
class IdempotencyScope(unittest.TestCase):
|
|
def test_same_key_is_independent_for_different_users_and_chats(self) -> None:
|
|
alice = common.actor("idemalice")
|
|
eve = common.actor("idemeve")
|
|
alice_chat = common.create_chat(alice.token, [alice.id], "Alice scope")
|
|
eve_chat = common.create_chat(eve.token, [eve.id], "Eve scope")
|
|
key = uuid.uuid4().hex
|
|
|
|
first = common.request(
|
|
"POST",
|
|
"/api/v1/chats/" + alice_chat["id"] + "/messages",
|
|
body={"text": "same body"},
|
|
token=alice.token,
|
|
headers={"Idempotency-Key": key},
|
|
)
|
|
second = common.request(
|
|
"POST",
|
|
"/api/v1/chats/" + eve_chat["id"] + "/messages",
|
|
body={"text": "same body"},
|
|
token=eve.token,
|
|
headers={"Idempotency-Key": key},
|
|
)
|
|
self.assertEqual(first.status, 201, first.json)
|
|
self.assertEqual(second.status, 201, second.json)
|
|
self.assertNotEqual(first.json["id"], second.json["id"])
|
|
self.assertEqual(second.json["chat_id"], eve_chat["id"])
|
|
self.assertEqual(second.json["sender_id"], eve.id)
|
|
|
|
# A different payload in another scope is also a new independent write.
|
|
other_scope = common.create_chat(eve.token, [eve.id], "Eve second scope")
|
|
third = common.request(
|
|
"POST",
|
|
"/api/v1/chats/" + other_scope["id"] + "/messages",
|
|
body={"text": "different body"},
|
|
token=eve.token,
|
|
headers={"Idempotency-Key": key},
|
|
)
|
|
self.assertEqual(third.status, 201, third.json)
|
|
self.assertEqual(third.json["chat_id"], other_scope["id"])
|
|
|
|
def test_concurrent_identical_replays_return_one_message_without_500(self) -> None:
|
|
alice = common.actor("idemrace")
|
|
chat = common.create_chat(alice.token, [alice.id], "Concurrent replay")
|
|
key = uuid.uuid4().hex
|
|
workers = 32
|
|
barrier = threading.Barrier(workers)
|
|
responses: list[common.Response] = []
|
|
lock = threading.Lock()
|
|
|
|
def post() -> None:
|
|
barrier.wait()
|
|
response = common.request(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
body={"text": "exactly once"},
|
|
token=alice.token,
|
|
headers={"Idempotency-Key": key},
|
|
timeout=30,
|
|
)
|
|
with lock:
|
|
responses.append(response)
|
|
|
|
threads = [threading.Thread(target=post) for _ in range(workers)]
|
|
for thread in threads:
|
|
thread.start()
|
|
for thread in threads:
|
|
thread.join(timeout=60)
|
|
|
|
self.assertEqual(len(responses), workers)
|
|
self.assertTrue(all(response.status == 201 for response in responses), responses)
|
|
message_ids = {response.json["id"] for response in responses}
|
|
self.assertEqual(len(message_ids), 1)
|
|
messages = common.history(alice.token, chat["id"])
|
|
self.assertEqual([message["text"] for message in messages], ["exactly once"])
|