Реализовать лабораторную 4 на оценку 5
Добавить приватное S3-хранилище, вложения, presigned upload, reconciler и доказательства.
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Concurrent shared-key replay across replicas plus scope/conflict checks."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import HttpClient
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--workers", type=int, default=20)
|
||||
args = parser.parse_args()
|
||||
client = HttpClient(args.base_url)
|
||||
|
||||
alice, alice_registration = client.register()
|
||||
bob, bob_registration = client.register()
|
||||
alice_token = client.login(alice_registration)["token"]
|
||||
bob_token = client.login(bob_registration)["token"]
|
||||
|
||||
status, _headers, chat, _ = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
body={"title": "Idempotency race", "member_ids": [alice["id"], bob["id"]]},
|
||||
token=alice_token,
|
||||
)
|
||||
if status != 201:
|
||||
raise AssertionError(f"chat creation failed: HTTP {status}")
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
text = "concurrent replay " + key
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
def send_same_body(_index: int):
|
||||
return client.call(
|
||||
"POST", path, body={"text": text}, token=alice_token,
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.workers) as pool:
|
||||
results = list(pool.map(send_same_body, range(args.workers)))
|
||||
|
||||
statuses = Counter(status for status, _h, _p, _r in results)
|
||||
statuses.pop(200, None)
|
||||
if set(statuses) != {201}:
|
||||
raise AssertionError(f"concurrent replay statuses are not all 201: {dict(statuses)}")
|
||||
ids = {payload["id"] for _s, _h, payload, _r in results}
|
||||
if len(ids) != 1:
|
||||
raise AssertionError(f"concurrent replay created {len(ids)} messages instead of 1")
|
||||
instances = {
|
||||
headers.get("X-Instance-Id", "")
|
||||
for _s, headers, _p, _r in results
|
||||
if headers.get("X-Instance-Id")
|
||||
}
|
||||
if len(instances) < 2:
|
||||
raise AssertionError("concurrent replay did not reach at least two replicas")
|
||||
|
||||
message_id = next(iter(ids))
|
||||
status, _headers, page, _ = client.call(
|
||||
"GET", path + "?limit=100", token=bob_token
|
||||
)
|
||||
if status != 200:
|
||||
raise AssertionError(f"history read failed: HTTP {status}")
|
||||
matching = [m for m in page["items"] if m["id"] == message_id]
|
||||
if len(matching) != 1:
|
||||
raise AssertionError("history contains a duplicate or a missing replayed message")
|
||||
|
||||
# Same key, different canonical body -> 409.
|
||||
status, _headers, payload, _ = client.call(
|
||||
"POST", path, body={"text": text + " different"}, token=alice_token,
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
if status != 409 or payload.get("error", {}).get("code") != "conflict":
|
||||
raise AssertionError(f"different body with the same key returned HTTP {status}, expected 409")
|
||||
|
||||
# Missing / malformed key -> 400.
|
||||
for headers in ({}, {"Idempotency-Key": "bad key with spaces"}):
|
||||
status, _headers, payload, _ = client.call(
|
||||
"POST", path, body={"text": "no valid key"}, token=alice_token, headers=headers
|
||||
)
|
||||
if status != 400 or payload.get("error", {}).get("code") != "invalid_request":
|
||||
raise AssertionError(f"invalid Idempotency-Key returned HTTP {status}, expected 400")
|
||||
|
||||
# Scope includes the user: the same key by another user is independent.
|
||||
status, _headers, bob_message, _ = client.call(
|
||||
"POST", path, body={"text": "bob independent"}, token=bob_token,
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
if status != 201 or bob_message["sender_id"] != bob["id"]:
|
||||
raise AssertionError(f"another user's identical key was not independent: HTTP {status}")
|
||||
|
||||
# Scope includes the path: the same key in another chat is independent.
|
||||
status, _headers, other_chat, _ = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
body={"title": "Second chat", "member_ids": [alice["id"], bob["id"]]},
|
||||
token=alice_token,
|
||||
)
|
||||
if status != 201:
|
||||
raise AssertionError(f"second chat creation failed: HTTP {status}")
|
||||
status, _headers, other_message, _ = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + other_chat["id"] + "/messages",
|
||||
body={"text": "same key another chat"},
|
||||
token=alice_token,
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
if status != 201 or other_message["id"] == message_id:
|
||||
raise AssertionError(f"same key in another chat was not independent: HTTP {status}")
|
||||
|
||||
print("concurrent_workers:", args.workers)
|
||||
print("statuses:", dict(statuses))
|
||||
print("instances:", ", ".join(sorted(instances)))
|
||||
print("PASS: shared idempotency creates exactly one message and respects all scopes")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user