Реализовать стенд лабораторной 3: две API-реплики и балансировка

FastAPI + PostgreSQL как единый источник истины: пользователи, Basic/Bearer-сессии, чаты, сообщения. Сессии и идемпотентные ключи хранятся в БД, поэтому реплики взаимозаменяемы. Общая идемпотентность POST сообщения по Idempotency-Key, включая конкурентный повтор через разные реплики. compose.yaml: postgres, one-shot migrate, api1, api2 и nginx как единственная публичная точка входа. Добавлены scripts/stop-one.sh и scripts/restart.sh, student-tests, evidence и заполненный REPORT.md.
This commit is contained in:
drunkdiente
2026-11-07 16:04:29 +03:00
parent 0ab3a341aa
commit 3aba500a0e
51 changed files with 1629 additions and 22 deletions
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Concurrent replay of one Idempotency-Key through the load balancer.
The public smoke checks sequential replay. This test fires many simultaneous
POSTs with the same key/body so requests land on both API replicas, then
verifies that exactly one message was stored and every response is identical.
"""
import json
import sys
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, LAB, check, run # noqa: E402
def main():
check(LAB >= 3, "concurrent idempotency requires lab3")
base = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
client = Client(base)
alice, bob, eve, chat = client.bootstrap()
key = "concurrent-" + uuid.uuid4().hex
text = "Одновременный повтор " + uuid.uuid4().hex
requests = 40
barrier = threading.Barrier(requests)
def worker(_):
local = Client(base)
barrier.wait()
try:
response = local.message(alice, chat, text, key=key)
return ("ok", response["json"], response["headers"]["X-Instance-Id"])
except Failure as exc:
return ("fail", str(exc), None)
with ThreadPoolExecutor(max_workers=requests) as pool:
results = list(pool.map(worker, range(requests)))
failures = [result for result in results if result[0] == "fail"]
if failures:
raise Failure("concurrent replay failed: " + failures[0][1])
bodies = {json.dumps(result[1], sort_keys=True) for result in results}
check(len(bodies) == 1, "concurrent replays returned different messages")
instances = {result[2] for result in results}
check(len(instances) >= 2, "requests did not reach both replicas: " + repr(instances))
history_path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
page = client.call("GET", history_path, actor=bob, schema="MessagePage")["json"]
copies = sum(1 for message in page["items"] if message["text"] == text)
check(copies == 1, "expected exactly one stored message, got %d" % copies)
client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
409,
actor=alice,
body={"text": text + " (different body)"},
headers={"Idempotency-Key": key},
)
print(
json.dumps(
{
"concurrent_requests": requests,
"instances": sorted(instances),
"stored_copies": copies,
},
ensure_ascii=False,
)
)
print("PASS: one Idempotency-Key, concurrent replicas, exactly one message")
if __name__ == "__main__":
run(main)