Lab 2: PostgreSQL storage and Redis sessions
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
"""Explicit local Docker checks: expiry, then Redis/PostgreSQL outages."""
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check
|
||||
|
||||
|
||||
def docker(*args):
|
||||
subprocess.run(["docker", *args], cwd=ROOT, check=True, timeout=90,
|
||||
stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(c):
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
try:
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def check_expiry(base_url):
|
||||
c = Client(base_url, timeout=8)
|
||||
wait_ready(c)
|
||||
actor = c.user("expiry")
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
time.sleep(2.2)
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS: SESSION_TTL_SECONDS=2; active token becomes 401 after expiry")
|
||||
|
||||
|
||||
def check_outage(c, service, stop, start):
|
||||
wait_ready(c)
|
||||
actor = c.user("outage")
|
||||
try:
|
||||
stop()
|
||||
for path in ("/health/ready", "/api/v1/users/me"):
|
||||
response = c.call("GET", path, 503,
|
||||
actor=actor if path.startswith("/api/") else None)
|
||||
check(response["elapsed"] < 8, service + " failure took too long")
|
||||
check(response["json"]["error"]["code"] == "unavailable", "wrong outage error")
|
||||
c.call("GET", "/health/live", schema="Health")
|
||||
c.call("GET", "/api/v1/users/me", 401)
|
||||
finally:
|
||||
start()
|
||||
wait_ready(c)
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
print("PASS: " + service + " outage -> bounded 503; live=200; anonymous=401; old token recovers")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--expiry-port", type=int, default=8081)
|
||||
args = parser.parse_args()
|
||||
check(1 <= args.expiry_port <= 65535, "invalid expiry port")
|
||||
name = "lab2-expiry-" + uuid4().hex[:12]
|
||||
started = False
|
||||
try:
|
||||
docker("compose", "run", "-d", "--rm", "--no-deps", "--name", name,
|
||||
"-e", "SESSION_TTL_SECONDS=2", "-p", "127.0.0.1:" + str(args.expiry_port) + ":8080", "api")
|
||||
started = True
|
||||
check_expiry("http://127.0.0.1:" + str(args.expiry_port))
|
||||
finally:
|
||||
if started:
|
||||
docker("stop", name)
|
||||
c = Client(args.base_url, timeout=8)
|
||||
for service in ("redis", "postgres"):
|
||||
check_outage(c, service,
|
||||
lambda s=service: docker("compose", "stop", s),
|
||||
lambda s=service: docker("compose", "up", "-d", "--wait", s))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""EXPLAIN on 10,000 synthetic messages; transaction rolls fixtures back."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.db import connection_kwargs
|
||||
from src.main import HISTORY_AFTER_SQL, HISTORY_FIRST_SQL
|
||||
|
||||
|
||||
def explain(conn, query, params):
|
||||
plan = conn.execute("EXPLAIN (ANALYZE, BUFFERS) " + query, params).fetchall()
|
||||
text = "\n".join(row["QUERY PLAN"] for row in plan)
|
||||
print(text)
|
||||
if "messages_history_idx" not in text or "Seq Scan on messages" in text:
|
||||
raise AssertionError("Expected history index without full messages scan")
|
||||
|
||||
|
||||
def main():
|
||||
user_id, chat_id = uuid4(), uuid4()
|
||||
with psycopg.connect(**connection_kwargs()) as conn:
|
||||
print(conn.execute("SELECT version() AS version").fetchone()["version"])
|
||||
with conn.transaction(force_rollback=True):
|
||||
conn.execute(
|
||||
"INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)",
|
||||
(user_id, "plan_" + uuid4().hex[:20], "EXPLAIN fixture",
|
||||
PasswordHasher().hash("Synthetic-password-123")),
|
||||
)
|
||||
conn.execute("INSERT INTO chats (id,title) VALUES (%s,%s)", (chat_id, "EXPLAIN fixture"))
|
||||
conn.execute("INSERT INTO chat_members (chat_id,user_id) VALUES (%s,%s)", (chat_id, user_id))
|
||||
conn.execute("""
|
||||
INSERT INTO messages (id,chat_id,sender_id,text,created_at)
|
||||
SELECT gen_random_uuid(), %s, %s, 'EXPLAIN fixture ' || n,
|
||||
TIMESTAMPTZ '2026-01-01T00:00:00Z' + n * INTERVAL '1 microsecond'
|
||||
FROM generate_series(1,10000) AS n
|
||||
""", (chat_id, user_id))
|
||||
conn.execute("ANALYZE messages")
|
||||
count = conn.execute("SELECT count(*) AS n FROM messages WHERE chat_id=%s",
|
||||
(chat_id,)).fetchone()["n"]
|
||||
assert count >= 10000
|
||||
print("Fixture messages:", count)
|
||||
print("FIRST PAGE: LIMIT 51 (50 items + lookahead)")
|
||||
explain(conn, HISTORY_FIRST_SQL, (chat_id, 51))
|
||||
# OFFSET only selects a reproducible fixture boundary, outside the page query.
|
||||
boundary = conn.execute(
|
||||
"SELECT created_at,id FROM messages WHERE chat_id=%s "
|
||||
"ORDER BY created_at,id OFFSET 8999 LIMIT 1", (chat_id,),
|
||||
).fetchone()
|
||||
print("LATER PAGE: after message 9000, LIMIT 51")
|
||||
explain(conn, HISTORY_AFTER_SQL,
|
||||
(chat_id, boundary["created_at"], boundary["id"], 51))
|
||||
conn.execute("ANALYZE messages")
|
||||
print("PASS: 10000 messages; first/later pages use messages_history_idx; fixtures rolled back")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts\restart.py
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Restart the complete lab stack; keep volumes and record actual start times."""
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SERVICES = ["api", "postgres", "redis"]
|
||||
|
||||
|
||||
def snapshot(filename):
|
||||
ids = subprocess.check_output(
|
||||
["docker", "compose", "ps", "--all", "-q", *SERVICES], cwd=ROOT, text=True
|
||||
).split()
|
||||
if len(ids) != 3:
|
||||
raise RuntimeError("Expected one api, postgres and redis container")
|
||||
template = ('{{index .Config.Labels "com.docker.compose.service"}} '
|
||||
'{{.Id}} {{.State.StartedAt}} {{.State.Status}}')
|
||||
lines = subprocess.check_output(
|
||||
["docker", "inspect", "--format", template, *ids], cwd=ROOT, text=True
|
||||
)
|
||||
(ROOT / "evidence").mkdir(exist_ok=True)
|
||||
(ROOT / "evidence" / filename).write_text(lines, encoding="utf-8")
|
||||
|
||||
|
||||
def main():
|
||||
snapshot("restart-before.txt")
|
||||
subprocess.run(["docker", "compose", "stop", *SERVICES], cwd=ROOT, check=True, timeout=45)
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--wait", "api"],
|
||||
cwd=ROOT, check=True, timeout=40)
|
||||
snapshot("restart-after.txt")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/restart.py
|
||||
Reference in New Issue
Block a user