forked from mtusi2026/mtusi2026lab3
115 lines
3.7 KiB
Python
115 lines
3.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Same Idempotency-Key from several threads, then the same key in another chat."""
|
|
import base64
|
|
import json
|
|
import os
|
|
import threading
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
|
|
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
|
|
|
|
|
def call(method, path, expected, body=None, headers=None):
|
|
h = {"Accept": "application/json"}
|
|
raw = None
|
|
if body is not None:
|
|
raw = json.dumps(body, ensure_ascii=False).encode()
|
|
h["Content-Type"] = "application/json"
|
|
h.update(headers or {})
|
|
req = urllib.request.Request(BASE + path, data=raw, headers=h, method=method)
|
|
try:
|
|
resp = urllib.request.urlopen(req, timeout=10)
|
|
except urllib.error.HTTPError as exc:
|
|
resp = exc
|
|
with resp:
|
|
data = resp.read()
|
|
payload = json.loads(data) if data else None
|
|
if resp.code != expected:
|
|
raise SystemExit(
|
|
method + " " + path.split("?")[0] + ": expected "
|
|
+ str(expected) + ", got " + str(resp.code)
|
|
)
|
|
return payload, resp.headers.get("X-Instance-Id")
|
|
|
|
|
|
def main():
|
|
username = "u_par_" + uuid.uuid4().hex[:12]
|
|
password = "T3st-" + uuid.uuid4().hex
|
|
user, _ = call(
|
|
"POST", "/api/v1/users", 201,
|
|
{"username": username, "display_name": "Параллельный", "password": password},
|
|
)
|
|
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
|
session, _ = call(
|
|
"POST", "/api/v1/auth/sessions", 201,
|
|
headers={"Authorization": "Basic " + basic},
|
|
)
|
|
auth = {"Authorization": "Bearer " + session["token"]}
|
|
chat_a, _ = call(
|
|
"POST", "/api/v1/chats", 201,
|
|
{"title": "A", "member_ids": [user["id"]]},
|
|
auth,
|
|
)
|
|
chat_b, _ = call(
|
|
"POST", "/api/v1/chats", 201,
|
|
{"title": "B", "member_ids": [user["id"]]},
|
|
auth,
|
|
)
|
|
key = "same-" + uuid.uuid4().hex
|
|
text = "одно сообщение " + key
|
|
results = []
|
|
errors = []
|
|
lock = threading.Lock()
|
|
|
|
def post():
|
|
try:
|
|
payload, instance = call(
|
|
"POST", "/api/v1/chats/" + chat_a["id"] + "/messages", 201,
|
|
{"text": text},
|
|
{**auth, "Idempotency-Key": key},
|
|
)
|
|
with lock:
|
|
results.append((payload["id"], instance))
|
|
except SystemExit as exc:
|
|
with lock:
|
|
errors.append(str(exc))
|
|
|
|
threads = [threading.Thread(target=post) for _ in range(8)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join()
|
|
if errors:
|
|
raise SystemExit("parallel post failed: " + "; ".join(errors))
|
|
ids = {item[0] for item in results}
|
|
instances = {item[1] for item in results}
|
|
if len(ids) != 1:
|
|
raise SystemExit("parallel retry created " + str(len(ids)) + " messages")
|
|
other, _ = call(
|
|
"POST", "/api/v1/chats/" + chat_b["id"] + "/messages", 201,
|
|
{"text": text},
|
|
{**auth, "Idempotency-Key": key},
|
|
)
|
|
if other["id"] == next(iter(ids)):
|
|
raise SystemExit("same key in another chat reused the first message")
|
|
conflict, _ = call(
|
|
"POST", "/api/v1/chats/" + chat_a["id"] + "/messages", 409,
|
|
{"text": "другое тело"},
|
|
{**auth, "Idempotency-Key": key},
|
|
)
|
|
if conflict["error"]["code"] != "conflict":
|
|
raise SystemExit("conflict code mismatch")
|
|
print(json.dumps({
|
|
"parallel_responses": len(results),
|
|
"unique_message_ids": len(ids),
|
|
"instances_seen": len(instances),
|
|
"other_chat_independent": True,
|
|
"different_body": 409,
|
|
}, ensure_ascii=False))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|