forked from mtusi2026/mtusi2026lab3
125 lines
5.3 KiB
Python
125 lines
5.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Inherited lab 2 level 4 checks through the lab 3 load balancer."""
|
|
|
|
import base64
|
|
import concurrent.futures
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
|
|
|
|
|
|
def compose(*args, env=None):
|
|
return subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, env=env, check=True, capture_output=True, text=True).stdout
|
|
|
|
|
|
def psql(sql):
|
|
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-t", "-A", "-c", sql)
|
|
|
|
|
|
def call(method, path, data=None, auth=None):
|
|
headers = {"Accept": "application/json"}
|
|
if method == "POST" and path.endswith("/messages"):
|
|
headers["Idempotency-Key"] = uuid.uuid4().hex
|
|
if data is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
if auth:
|
|
headers["Authorization"] = auth
|
|
request = urllib.request.Request(BASE + path, method=method, headers=headers, data=json.dumps(data).encode() if data is not None else None)
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=10) as response:
|
|
return response.status, json.loads(response.read() or b"null")
|
|
except urllib.error.HTTPError as error:
|
|
return error.code, json.loads(error.read())
|
|
|
|
|
|
def register(name, password):
|
|
return call("POST", "/api/v1/users", {"username": name, "display_name": "Synthetic", "password": password})
|
|
|
|
|
|
def login(name, password):
|
|
basic = base64.b64encode((name + ":" + password).encode()).decode()
|
|
return call("POST", "/api/v1/auth/sessions", auth="Basic " + basic)
|
|
|
|
|
|
def main():
|
|
assert register("spaces_" + uuid.uuid4().hex[:12], " " * 12)[0] == 400
|
|
name = "race_" + uuid.uuid4().hex[:12]
|
|
password = "synthetic-" + uuid.uuid4().hex
|
|
gate = threading.Barrier(16)
|
|
def competing_register(_):
|
|
gate.wait()
|
|
return register(name, password)[0]
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as workers:
|
|
statuses = list(workers.map(competing_register, range(16)))
|
|
assert statuses.count(201) == 1 and statuses.count(409) == 15, statuses
|
|
status, session = login(name, password)
|
|
assert status == 201
|
|
basic = base64.b64encode((name + ":" + password).encode()).decode()
|
|
assert call("POST", "/api/v1/auth/sessions", {"unexpected": "body"}, "Basic " + basic)[0] == 400
|
|
token = "Bearer " + session["token"]
|
|
user_id = session["user"]["id"]
|
|
status, chat = call("POST", "/api/v1/chats", {"title": "Failure test", "member_ids": [user_id]}, token)
|
|
assert status == 201
|
|
probe = "rollback_" + uuid.uuid4().hex
|
|
psql("CREATE FUNCTION lab2_rollback_guard() RETURNS trigger LANGUAGE plpgsql AS $$ "
|
|
f"BEGIN IF EXISTS (SELECT 1 FROM chats WHERE id=NEW.chat_id AND title='{probe}') "
|
|
"THEN RAISE EXCEPTION 'rollback probe'; END IF; RETURN NEW; END $$;")
|
|
psql("CREATE TRIGGER lab2_rollback_guard BEFORE INSERT ON chat_members "
|
|
"FOR EACH ROW EXECUTE FUNCTION lab2_rollback_guard();")
|
|
try:
|
|
assert call("POST", "/api/v1/chats", {"title": probe, "member_ids": [user_id]}, token)[0] == 500
|
|
assert psql(f"SELECT count(*) FROM chats WHERE title='{probe}'").strip() == "0"
|
|
finally:
|
|
psql("DROP TRIGGER lab2_rollback_guard ON chat_members; DROP FUNCTION lab2_rollback_guard();")
|
|
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
|
assert call("POST", path, {"text": "before outage"}, token)[0] == 201
|
|
malformed = base64.urlsafe_b64encode(json.dumps([chat["id"], 17, user_id]).encode()).decode().rstrip("=")
|
|
assert call("GET", path + "?cursor=" + malformed, auth=token)[0] == 400
|
|
assert call("GET", path + "?limit=" + "9" * 100, auth=token)[0] == 400
|
|
missing_status, missing_body = call("GET", "/api/v1/missing", auth=token)
|
|
assert missing_status == 404 and missing_body["error"]["code"] == "not_found"
|
|
compose("stop", "redis")
|
|
try:
|
|
assert call("GET", path, auth=token)[0] == 200
|
|
assert call("POST", path, {"text": "during cache outage"}, token)[0] == 201
|
|
assert call("GET", path, auth=token)[1]["items"][-1]["text"] == "during cache outage"
|
|
assert call("GET", "/api/v1/users/me", auth="Bearer invalid")[0] == 401
|
|
finally:
|
|
compose("start", "redis")
|
|
compose("stop", "postgres")
|
|
try:
|
|
assert call("GET", "/health/ready")[0] == 503
|
|
assert call("GET", "/api/v1/users/me", auth=token)[0] == 503
|
|
finally:
|
|
compose("start", "postgres")
|
|
for _ in range(40):
|
|
if call("GET", "/health/ready")[0] == 200:
|
|
break
|
|
time.sleep(0.5)
|
|
else:
|
|
raise AssertionError("PostgreSQL did not recover")
|
|
# Expiry is checked against PostgreSQL time, without a Redis dependency.
|
|
env = dict(os.environ, SESSION_TTL_SECONDS="2")
|
|
compose("up", "-d", "--force-recreate", "--wait", "api", env=env)
|
|
try:
|
|
short = login(name, password)[1]["token"]
|
|
time.sleep(3)
|
|
assert call("GET", "/api/v1/users/me", auth="Bearer " + short)[0] == 401
|
|
finally:
|
|
compose("up", "-d", "--force-recreate", "--wait", "api")
|
|
print("PASS: username race, chat rollback, Redis fallback, PostgreSQL failure, session expiry")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|