Files
mtusi2026lab3/student-tests/persistence_checks.py
T

52 lines
2.4 KiB
Python

"""Restart storage and processes, then replay the original request with the original token."""
import argparse
import json
import subprocess
import time
from cluster import inspect
from compose_helpers import ROOT, compose, sql
from client import Client, check, run
import uuid
def state():
result = {}
for service in ("postgres", "redis", "api", "lb"):
result[service] = [{"container": row["Id"], "started_at": row["State"]["StartedAt"],
"volumes": [mount["Name"] for mount in row["Mounts"] if mount["Type"] == "volume"]}
for row in (inspect(container) for container in compose("ps", "-q", service).splitlines())]
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
args = parser.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
key = uuid.uuid4().hex
original = c.message(alice, chat, "Persistent request " + key, key=key)["json"]
before = state()
subprocess.run([str(ROOT / "scripts/restart.sh")], check=True, timeout=90, stdout=subprocess.DEVNULL)
after = state()
for service in before:
check({row["started_at"] for row in before[service]} != {row["started_at"] for row in after[service]},
service + " was not restarted")
check(before["postgres"][0]["volumes"] == after["postgres"][0]["volumes"], "database volume changed")
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
replay = c.message(alice, chat, original["text"], key=key)["json"]
check(replay == original, "original key/token did not replay after full restart")
check(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';") == "1", "restart replay duplicated message")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
c.call("GET", "/api/v1/users/me", 401, actor=alice)
report = {"verified_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"before": before, "after": after, "same_token": True, "same_message": True,
"replay_without_duplicates": True, "logout_status": 401}
(ROOT / "evidence/persistence.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
print("PASS: all services restarted, original token and key replayed, one message, logout 401")
if __name__ == "__main__":
run(main)