forked from mtusi2026/mtusi2026lab3
Общие PostgreSQL, Valkey и идемпотентность сообщений нужны, чтобы чтение и запись переживали остановку одной реплики.
65 lines
2.6 KiB
Python
65 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Проверки уровня 4, которые не входят в публичный smoke: разнос реплик и гонка ключа."""
|
|
import threading
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
from client import Client, arguments, check, run
|
|
|
|
|
|
def instances_of(c, actor, n=24):
|
|
seen = []
|
|
for _ in range(n):
|
|
seen.append(c.call("GET", "/api/v1/users/me", actor=actor, schema="User")["headers"]["X-Instance-Id"])
|
|
return seen
|
|
|
|
|
|
def main():
|
|
args = arguments("Lab3 level-4: two instances and concurrent idempotency")
|
|
c = Client(args.base_url, args.ca_file)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
seen = instances_of(c, alice)
|
|
uniq = sorted(set(seen))
|
|
check(len(uniq) >= 2, "LB did not spread one session across two API replicas: %s" % uniq)
|
|
|
|
key = "same-" + uuid.uuid4().hex
|
|
text = "общий ключ " + key
|
|
workers = 8
|
|
barrier = threading.Barrier(workers)
|
|
|
|
def once(_n):
|
|
local = Client(args.base_url, args.ca_file, timeout=10)
|
|
barrier.wait()
|
|
return local.message(alice, chat, text, key=key)
|
|
|
|
with ThreadPoolExecutor(max_workers=workers) as pool:
|
|
results = list(pool.map(once, range(workers)))
|
|
ids = {item["json"]["id"] for item in results}
|
|
bodies = {item["json"]["text"] for item in results}
|
|
served = sorted({item["headers"]["X-Instance-Id"] for item in results})
|
|
check(len(ids) == 1, "concurrent idempotency created more than one message")
|
|
check(bodies == {text}, "concurrent replay changed text")
|
|
check(len(served) >= 2, "concurrent posts did not hit two replicas: %s" % served)
|
|
replay = c.message(alice, chat, text, key=key)["json"]
|
|
check(replay == results[0]["json"], "sequential replay differs")
|
|
c.call(
|
|
"POST",
|
|
"/api/v1/chats/" + chat["id"] + "/messages",
|
|
409,
|
|
actor=alice,
|
|
body={"text": "другой текст " + key},
|
|
headers={"Idempotency-Key": key},
|
|
)
|
|
shared = "shared-" + uuid.uuid4().hex
|
|
left = c.message(alice, chat, "алиса " + shared, key=shared)["json"]
|
|
right = c.message(bob, chat, "боб " + shared, key=shared)["json"]
|
|
check(left["id"] != right["id"], "same key must be independent per user")
|
|
page = c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=bob, schema="MessagePage")["json"]
|
|
copies = [item for item in page["items"] if item["text"] == text]
|
|
check(len(copies) == 1, "history contains duplicate of the idempotent message")
|
|
print("PASS: level4 spread=%s parallel_instances=%s" % (",".join(uniq), ",".join(served)))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|