add logic from lab2

This commit is contained in:
Матвей
2026-10-14 14:38:00 +03:00
parent 0ab3a341aa
commit 27cbf91b73
30 changed files with 2185 additions and 6 deletions
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Проверяет fallback и восстановление Redis-кэша без restart API."""
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from pathlib import Path
import subprocess
import sys
import threading
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
def main() -> None:
client = Client()
alice, _bob, _eve, chat = client.bootstrap()
message = client.message(alice, chat, "survives Redis restart")["json"]
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
before = client.call("GET", path, actor=alice, schema="MessagePage")["json"]
check(before["items"] == [message], "initial cache fill failed")
subprocess.run(["docker", "compose", "stop", "redis"], cwd=ROOT, check=True)
fallback = client.call("GET", path, actor=alice, schema="MessagePage")["json"]
check(fallback["items"] == [message], "PostgreSQL fallback returned a different history")
subprocess.run(["docker", "compose", "start", "redis"], cwd=ROOT, check=True)
time.sleep(1.1) # Интервал повторного подключения к Redis в приложении.
after = client.call("GET", path, actor=alice, schema="MessagePage")["json"]
check(after["items"] == [message], "history changed after Redis restart")
keys = subprocess.check_output(
[
"docker", "compose", "exec", "-T", "redis", "redis-cli", "--scan",
"--pattern", "history:first:" + chat["id"] + ":*",
],
cwd=ROOT,
text=True,
)
check("history:first:" + chat["id"] in keys, "cache was not restored after Redis restart")
second = client.message(alice, chat, "cold page after Redis recovery")["json"]
started_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
workers = 20
barrier = threading.Barrier(workers)
def read_cold_page(_worker: int) -> None:
barrier.wait()
response = Client().call("GET", path, actor=alice, schema="MessagePage")["json"]
check(response["items"] == [message, second], "concurrent history differs")
with ThreadPoolExecutor(max_workers=workers) as pool:
list(pool.map(read_cold_page, range(workers)))
logs = subprocess.check_output(
["docker", "compose", "logs", "--since", started_at, "api-a", "api-b"],
cwd=ROOT,
text=True,
)
marker = "history_sql_page_load chat_id=" + chat["id"] + " version=2 limit=100"
check(logs.count(marker) == 1, "Redis lock was not restored after Redis restart")
print("PASS: Redis cache and stampede lock recover without API restart")
if __name__ == "__main__":
run(main)
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Одновременное чтение холодной первой страницы истории."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import json
import sys
import threading
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
def main() -> None:
concurrency = 20
client = Client()
alice, _bob, _eve, chat = client.bootstrap()
created = client.message(alice, chat, "cold-cache message")["json"]
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=1"
barrier = threading.Barrier(concurrency)
def read_page(_worker: int) -> float:
local = Client()
barrier.wait()
started = time.monotonic()
response = local.call("GET", path, actor=alice, schema="MessagePage")["json"]
check(response["items"] == [created], "cold-page response differs")
return time.monotonic() - started
with ThreadPoolExecutor(max_workers=concurrency) as pool:
latencies = list(pool.map(read_page, range(concurrency)))
ordered = sorted(latencies)
print(
json.dumps(
{
"chat_id": chat["id"],
"concurrency": concurrency,
"successful_reads": len(latencies),
"latency_ms": {
"p50": round(1000 * ordered[(concurrency - 1) // 2], 3),
"p95": round(1000 * ordered[18], 3),
"max": round(1000 * ordered[-1], 3),
},
},
ensure_ascii=False,
)
)
if __name__ == "__main__":
run(main)
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Один ключ одновременно через LB создаёт ровно одно сообщение."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
def main() -> None:
client = Client()
alice, _bob, _eve, chat = client.bootstrap()
key = uuid.uuid4().hex
text = "concurrent idempotency " + key
def send(_number: int):
return Client().message(alice, chat, text, key=key)["json"]
with ThreadPoolExecutor(max_workers=16) as pool:
replies = list(pool.map(send, range(16)))
check(all(reply == replies[0] for reply in replies), "replays returned different messages")
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
history = client.call("GET", path, actor=alice, schema="MessagePage")["json"]["items"]
check(sum(message["id"] == replies[0]["id"] for message in history) == 1, "concurrent retries created duplicates")
print("PASS: concurrent idempotency through load balancer")
if __name__ == "__main__":
run(main)
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Проверки гонки регистрации и rollback создания чата."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
def main() -> None:
client = Client()
alice, bob, _eve, chat = client.bootstrap()
username = "race_" + uuid.uuid4().hex[:12]
body = {
"username": username,
"display_name": "Гонка регистрации",
"password": "Race-password-" + uuid.uuid4().hex,
}
def register_once() -> int:
local = Client()
return local.call("POST", "/api/v1/users", expected=[201, 409], body=body)["status"]
with ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(lambda _unused: register_once(), range(8)))
check(statuses.count(201) == 1 and statuses.count(409) == 7, "username race was not serialized")
title = "rollback-" + uuid.uuid4().hex
client.call(
"POST",
"/api/v1/chats",
400,
actor=alice,
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]},
)
chats = client.call(
"GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage"
)["json"]["items"]
check(all(chat["title"] != title for chat in chats), "failed chat creation left a chat")
first = client.message(alice, chat, "before cached read")["json"]
client.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=alice,
schema="MessagePage",
)
second = client.message(bob, chat, "after cached read")["json"]
history = client.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=alice,
schema="MessagePage",
)["json"]["items"]
check(
{message["id"] for message in history} == {first["id"], second["id"]},
"history cache returned stale data after write",
)
first_page_path = "/api/v1/chats/" + chat["id"] + "/messages?limit=1"
first_page = client.call(
"GET", first_page_path, actor=alice, schema="MessagePage"
)["json"]
cached_page = client.call(
"GET", first_page_path, actor=alice, schema="MessagePage"
)["json"]
check(first_page == cached_page, "cached page differs from the first response")
check(first_page["next_cursor"], "first page has no continuation cursor")
client.call(
"GET",
first_page_path + "&cursor=" + first_page["next_cursor"],
actor=alice,
schema="MessagePage",
)
print("PASS: registration race, chat rollback and cache read-after-write")
if __name__ == "__main__":
run(main)
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Проверка 503 readiness при остановленном PostgreSQL."""
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, run # noqa: E402
def main() -> None:
Client().call("GET", "/health/ready", 503)
print("PASS: readiness rejects unavailable PostgreSQL")
if __name__ == "__main__":
run(main)
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Проверка expiry; запускается при SESSION_TTL_SECONDS=2."""
from pathlib import Path
import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
def main() -> None:
client = Client()
actor = client.user("expiry")
time.sleep(3)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: expired Bearer session was rejected")
if __name__ == "__main__":
run(main)