Files
mtusi2026lab4/tests/s3_outage.py
T

155 lines
3.6 KiB
Python

from __future__ import annotations
import base64
import json
from pathlib import Path
import runpy
import subprocess
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parent.parent
COMPOSE = [
"docker", "compose",
"-f", "compose.yaml",
"-f", "compose.s3.yaml",
"--env-file", ".env",
]
def compose(*args):
return subprocess.run(
COMPOSE + list(args),
cwd=ROOT,
check=True,
)
state = runpy.run_path(str(ROOT / "tests/attachments_negative.py"))
containers = subprocess.check_output(
COMPOSE + ["ps", "-q", "api"],
cwd=ROOT,
text=True,
).split()
if not containers:
raise SystemExit("No running API container")
payload = {
"token": state["token"],
"chat_id": state["chat_ids"][0],
"attachment_id": state["attachment"]["id"],
"image": base64.b64encode(state["image"]).decode(),
}
probe = r'''
import base64
import json
import sys
import urllib.error
import urllib.request
state = json.load(sys.stdin)
base = "http://127.0.0.1:8080/api/v1"
attachment = state["attachment_id"]
cases = [
(
"metadata remains readable",
"GET",
f"/attachments/{attachment}",
None,
200,
),
(
"download fails safely",
"GET",
f"/attachments/{attachment}/content",
None,
503,
),
(
"upload fails safely",
"POST",
f"/chats/{state['chat_id']}/attachments?filename=outage.png",
base64.b64decode(state["image"]),
503,
),
]
for label, method, path, data, expected in cases:
headers = {"Authorization": "Bearer " + state["token"]}
if data is not None:
headers["Content-Type"] = "image/png"
request = urllib.request.Request(
base + path, method=method, headers=headers, data=data
)
try:
response = urllib.request.urlopen(request, timeout=40)
except urllib.error.HTTPError as error:
response = error
with response:
status = response.code
headers = response.headers
body = json.loads(response.read())
assert status == expected, (label, status, body)
assert headers.get("X-Request-Id")
assert headers.get("X-Instance-Id")
if expected == 503:
assert body["error"]["code"] == "unavailable"
assert (
body["error"]["request_id"]
== headers["X-Request-Id"]
)
else:
assert body["id"] == attachment
print(f"OK {status}: {label}", flush=True)
'''
try:
compose("stop", "--timeout", "10", "s3")
subprocess.run(
["docker", "exec", "-i", containers[0], "python", "-c", probe],
input=json.dumps(payload),
text=True,
check=True,
timeout=150,
)
finally:
compose("start", "s3")
deadline = time.monotonic() + 90
while True:
try:
with urllib.request.urlopen(
"http://127.0.0.1:18082/health/ready",
timeout=5,
) as response:
assert response.status == 200
break
except (urllib.error.URLError, TimeoutError, ConnectionError):
if time.monotonic() >= deadline:
raise SystemExit("Readiness did not recover")
time.sleep(2)
request = urllib.request.Request(
state["BASE"]
+ f"/attachments/{state['attachment']['id']}/content",
headers={"Authorization": "Bearer " + state["token"]},
)
with urllib.request.urlopen(request, timeout=15) as response:
downloaded = response.read()
assert downloaded == state["image"]
print("OK: original remains intact after S3 restart")
print("PASS: S3 outage operations and recovery")