refactor code
This commit is contained in:
@@ -1,69 +0,0 @@
|
||||
#!/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)
|
||||
@@ -1,51 +0,0 @@
|
||||
#!/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)
|
||||
@@ -1,82 +0,0 @@
|
||||
#!/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)
|
||||
Reference in New Issue
Block a user