70 lines
2.8 KiB
Python
70 lines
2.8 KiB
Python
#!/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"],
|
|
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)
|