import json import statistics import time from pathlib import Path from client import Client, check, run def main(): client = Client() alice, _, _, chat = client.bootstrap() path = f"/api/v1/chats/{chat['id']}/messages?limit=50" # Первое чтение — холодный кэш. started = time.perf_counter() client.call("GET", path, actor=alice, schema="MessagePage") cold_ms = (time.perf_counter() - started) * 1000 # Повторные чтения — прогретый кэш. warm = [] for _ in range(30): started = time.perf_counter() client.call("GET", path, actor=alice, schema="MessagePage") warm.append((time.perf_counter() - started) * 1000) # Проверка актуальности после записи. marker = "cache-read-after-write-check" client.message(alice, chat, marker) updated = client.call( "GET", path, actor=alice, schema="MessagePage" ) texts = [item["text"] for item in updated["json"]["items"]] check(marker in texts, "Read-after-write failed: new message is missing") result = { "experiment": "Redis message history cache", "cold_read_ms": round(cold_ms, 3), "warm_reads": len(warm), "warm_mean_ms": round(statistics.mean(warm), 3), "warm_median_ms": round(statistics.median(warm), 3), "warm_min_ms": round(min(warm), 3), "warm_max_ms": round(max(warm), 3), "read_after_write": "PASS", "limitations": ( "HTTP latency includes client, network, authentication " "and API overhead; it is not a direct SQL query count." ), } output = Path("evidence/cache-research.json") output.parent.mkdir(parents=True, exist_ok=True) output.write_text( json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) print(json.dumps(result, indent=2, ensure_ascii=False)) if __name__ == "__main__": run(main)