Реализовать стенд лабораторной 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)
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""One session, many requests, both replicas: proves shared session state."""
import json
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, LAB, check, run # noqa: E402
def main():
check(LAB >= 3, "shared sessions across replicas require lab3")
base = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
client = Client(base)
alice = client.user("replica")
# A just-restored replica can stay out of the nginx pool for up to
# fail_timeout=5s. Wait for normal two-replica operation before measuring.
deadline = time.monotonic() + 10
warm = set()
while time.monotonic() < deadline and len(warm) < 2:
warm.add(client.call("GET", "/health/live", schema="Health")["headers"]["X-Instance-Id"])
time.sleep(0.1)
check(len(warm) >= 2, "load balancer currently has only one healthy replica")
instances = []
for _ in range(12):
response = client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
instances.append(response["headers"]["X-Instance-Id"])
check(len(set(instances)) >= 2, "one session was served by a single replica only")
print(json.dumps({"requests": len(instances), "instances": instances}, ensure_ascii=False))
print("PASS: one bearer session served by both replicas without re-login")
if __name__ == "__main__":
run(main)