Files
mtusi2026lab4/scripts/check-s3-outage.py
T

116 lines
4.4 KiB
Python

#!/usr/bin/env python3
"""S3 outage probe (grade 4): losing object storage must degrade, not crash.
* stopping S3 -> /health/ready = 503 and upload/download = 503 (bounded);
* PostgreSQL data (users/chats/messages/metadata) stays intact;
* after S3 returns the API serves uploads again.
Run from the repository root where ``docker compose`` is available.
"""
from __future__ import annotations
import base64
import json
import os
import struct
import subprocess
import time
import urllib.error
import urllib.request
import uuid
import zlib
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
def _png_chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def make_png(width=64, height=64):
pixels = os.urandom(width * height * 3)
raw = bytearray()
for row in range(height):
raw.append(0)
raw += pixels[row * width * 3 : (row + 1) * width * 3]
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + _png_chunk(b"IHDR", ihdr) + _png_chunk(b"IDAT", zlib.compress(bytes(raw), 0)) + _png_chunk(b"IEND", b"")
def call(method, path, token=None, body=None, raw=None, content_type=None):
headers = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if content_type:
headers["Content-Type"] = content_type
if token:
headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=15) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
except (urllib.error.URLError, TimeoutError, OSError):
return 0, b""
def compose(*args):
subprocess.run(["docker", "compose", *args], check=True, stdout=subprocess.DEVNULL)
def wait_ready(expected, timeout=180.0):
deadline = time.time() + timeout
while time.time() < deadline:
if call("GET", "/health/ready")[0] == expected:
return
time.sleep(2)
raise SystemExit(f"readiness did not reach {expected}")
def main() -> None:
wait_ready(200)
username = "s3out_" + uuid.uuid4().hex[:8]
password = "T3st-" + uuid.uuid4().hex
assert call("POST", "/api/v1/users", body={"username": username, "display_name": "S3", "password": password})[0] == 201
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
request = urllib.request.Request(
BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=15) as response:
token = json.loads(response.read())["token"]
user_id = json.loads(call("GET", "/api/v1/users/me", token=token)[1])["id"]
chat = json.loads(call("POST", "/api/v1/chats", token=token, body={"title": "s3", "member_ids": [user_id]})[1])
assert call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", token=token,
raw=make_png(), content_type="image/png")[0] == 201
print("baseline: upload = 201")
print("stopping s3 ...")
compose("stop", "s3")
time.sleep(3)
ready = call("GET", "/health/ready")[0]
upload = call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=b.png", token=token,
raw=make_png(), content_type="image/png")[0]
assert ready == 503, f"readiness must be 503 without S3, got {ready}"
assert upload == 503, f"upload must be a bounded 503 without S3, got {upload}"
print("s3 down: /health/ready = 503, upload = 503 (bounded)")
# PostgreSQL-backed endpoints still work.
assert call("GET", "/api/v1/users/me", token=token)[0] == 200
print("s3 down: /users/me = 200 (metadata unaffected)")
compose("start", "s3")
wait_ready(200, timeout=240)
again = call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=c.png", token=token,
raw=make_png(), content_type="image/png")[0]
assert again == 201, f"upload must recover, got {again}"
print("s3 restored: upload = 201")
print("PASS: S3 outage degrades to bounded 503 and recovers")
if __name__ == "__main__":
main()