Files
mtusi2026lab5/student-tests/grade3.py
T

445 lines
20 KiB
Python

"""Reproduce Lab 5 acceptance scenarios using only local Compose services."""
import hashlib
import json
import os
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from io import BytesIO
from pathlib import Path
import re
import subprocess
import sys
import time
from uuid import UUID, uuid4
from jsonschema import Draft202012Validator, FormatChecker
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
PROJECT = os.getenv("LAB5_PROJECT", "")
SERVICES = {"api1", "api2", "broker", "worker", "postgres", "s3", "lb"}
JOB_SCHEMA = json.loads((ROOT / "contracts/jobs.schema.json").read_text(encoding="utf-8"))
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
def docker(*args):
completed = subprocess.run(["docker", *args], capture_output=True, text=True, timeout=45)
check(completed.returncode == 0, f"docker {args[0]} returned {completed.returncode}")
return (completed.stdout + (completed.stderr if args[0] == "logs" else "")).strip()
def container(service):
check(service in SERVICES, "unexpected service")
ids = docker("ps", "-aq", "--filter", f"label=com.docker.compose.project={PROJECT}",
"--filter", f"label=com.docker.compose.service={service}",
"--filter", "label=com.docker.compose.oneoff=False").splitlines()
check(len(ids) == 1, f"expected one container for {service}")
return ids[0]
def action(verb, *services):
ids = [container(service) for service in services]
print(f"docker {verb} {' '.join(services)} containers={','.join(ids)}")
extra = ("--time", "2") if verb in {"stop", "restart"} else ()
docker(verb, *extra, *ids)
def inspect(service, fmt):
return docker("inspect", "--format", fmt, container(service))
def inside(service, *args):
return docker("exec", container(service), *args)
def psql_args():
return ("psql", "-XAt", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger")
def sql(statement):
return inside("postgres", *psql_args(), "-c", statement)
@contextmanager
def block_variant_insert():
# Compatible with metadata SELECT, blocks the worker's final INSERT only.
args = ["docker", "exec", "-i", container("postgres"), *psql_args()]
proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True)
try:
proc.stdin.write("BEGIN; LOCK attachment_variants IN SHARE MODE; SELECT 'locked';\n")
proc.stdin.flush()
for _ in range(3):
if proc.stdout.readline().strip() == "locked":
break
else:
raise Failure("could not lock variants")
yield
finally:
try:
proc.communicate("COMMIT;\n", timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
raise Failure("could not release variants lock") from None
check(proc.returncode == 0, "variant lock session failed")
def eventually(description, fn, seconds=45, interval=0.2):
start = time.monotonic()
last = ""
while time.monotonic() - start < seconds:
try:
value = fn()
if value:
print(f"{description} after {time.monotonic()-start:.3f}s")
return value
except Failure as exc:
last = str(exc)
time.sleep(interval)
raise Failure(f"timeout waiting for {description}: {last}")
def ready(client):
eventually("LB ready", lambda: client.call("GET", "/health/ready", schema="Health"))
def metadata(client, actor, attachment):
path = f"/api/v1/attachments/{attachment['id']}"
return client.call("GET", path, actor=actor, schema="Attachment")["json"]
def expect_unavailable(client, actor, attachment):
path = f"/api/v1/attachments/{attachment['id']}/content"
for variant in ("original", "thumbnail"):
client.call("GET", f"{path}?variant={variant}", 409, actor=actor)
def upload(client, actor, chat, data=SAMPLE, mime="image/png", expected=202, filename="fixture"):
response = client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={filename}",
expected, actor=actor, raw=data, headers={"Content-Type": mime},
schema="Attachment" if expected == 202 else None)
if expected == 202:
row = response["json"]
check(row["status"] == "queued" and row["variants"] == [] and row["error_code"] is None,
"expected queued snapshot")
check((row["size_bytes"], row["sha256"], row["content_type"]) ==
(len(data), hashlib.sha256(data).hexdigest(), mime), "staging metadata mismatch")
return response
def assert_ready(client, actor, attachment, data, dimensions, mime="image/png"):
start = time.monotonic()
row = client.wait_ready(actor, attachment)
check(row["error_code"] is None and len(row["variants"]) == 1, "invalid ready result")
check((row["content_type"], row["size_bytes"], row["sha256"]) ==
(mime, len(data), hashlib.sha256(data).hexdigest()), "original metadata changed")
content_path = f"/api/v1/attachments/{attachment['id']}/content"
original = client.call("GET", content_path, actor=actor)
check(original["bytes"] == data and original["headers"].get_content_type() == mime,
"original content changed")
thumb = client.call("GET", content_path + "?variant=thumbnail", actor=actor)
check(thumb["headers"].get_content_type() == "image/jpeg", "thumbnail HTTP MIME")
variant = row["variants"][0]
check(variant["name"] == "thumbnail" and variant["content_type"] == "image/jpeg"
and (variant["width"], variant["height"]) == dimensions, "thumbnail metadata")
check((variant["sha256"], variant["size_bytes"]) ==
(hashlib.sha256(thumb["bytes"]).hexdigest(), len(thumb["bytes"])), "thumbnail checksum")
with Image.open(BytesIO(thumb["bytes"])) as im:
im.load()
check(im.format == "JPEG" and im.size == dimensions and not im.getexif(),
"invalid thumbnail format, dimensions or EXIF")
pixel = im.getpixel((0, 0))
print(f"ready id={row['id']} wait={time.monotonic()-start:.3f}s original_sha256={row['sha256']} "
f"jpeg={dimensions[0]}x{dimensions[1]} thumb_sha256={variant['sha256']} "
f"read={original['headers']['X-Instance-Id']}/{thumb['headers']['X-Instance-Id']}")
return row, pixel
def job_state(attachment):
aid = UUID(attachment["id"])
return sql(f"""SELECT a.status,j.attempt,COALESCE(j.last_error,''),j.max_attempts
FROM attachments a JOIN attachment_jobs j ON a.id=j.attachment_id
WHERE a.id='{aid}'""")
def private(service, key):
status = inside(service, "python", "-c", """
import sys
from urllib.error import HTTPError
from urllib.request import urlopen
from src import s3
try:
urlopen(f"http://s3:9000/{s3.BUCKET}/{sys.argv[1]}", timeout=3).close()
except HTTPError as error:
print(error.code)
else:
print(200)
""", key)
check(status == "403", "unsigned S3 request was not rejected")
print("private RustFS object unsigned GET HTTP 403")
def queued_carrier():
# Observe the real persistent AMQP message and put it back without ack.
raw = inside("api1", "python", "-c", """
import json
from src import jobs
with jobs.broker() as channel:
method, props, body = channel.basic_get(jobs.QUEUE, auto_ack=False)
if method:
channel.basic_nack(method.delivery_tag, requeue=True)
print(json.dumps({"delivery_mode":props.delivery_mode, "job":json.loads(body)}))
""")
check(bool(raw), "no queued job in RabbitMQ")
observed = json.loads(raw)
check(observed["delivery_mode"] == 2, "AMQP message is not persistent")
carrier = observed["job"]
Draft202012Validator(JOB_SCHEMA, format_checker=FormatChecker()).validate(carrier)
print(f"RabbitMQ persistent carrier schema valid job={carrier['job_id']} "
f"attempt={carrier['attempt']} fields={','.join(sorted(carrier))}")
return carrier
def queue_stats():
text = inside("broker", "rabbitmqctl", "-q", "list_queues",
"name", "durable", "messages_ready", "messages_unacknowledged")
for line in text.splitlines():
fields = line.split()
if fields and fields[0] == "attachment.process.v1":
check(fields[1] == "true", "queue durability is off")
print(f"broker queue={fields[0]} durable={fields[1]} ready={fields[2]} unacked={fields[3]}")
return tuple(map(int, fields[2:]))
raise Failure("RabbitMQ queue absent")
def duplicate(client, actor, attachment, carrier, ready_snapshot):
inside("api1", "python", "-c", """
import sys
from src import jobs
job = jobs.parse(sys.argv[1])
with jobs.broker() as channel:
jobs.publish(channel, job)
jobs.publish(channel, job)
""", json.dumps(carrier))
worker = container("worker")
job_id = carrier["job_id"]
eventually("worker acknowledged two ready duplicates", lambda:
docker("logs", worker).count(f"job={job_id} attempt=1 outcome=duplicate_ready") >= 2)
check(metadata(client, actor, attachment) == ready_snapshot, "duplicate changed ready metadata")
aid = UUID(attachment["id"])
check(sql(f"SELECT count(*) FROM attachment_variants WHERE attachment_id='{aid}'") == "1",
"duplicate created another variant row")
count = inside("api1", "python", "-c", """
import sys
from src import s3
result = s3.client.list_objects_v2(Bucket=s3.BUCKET, Prefix=f"variants/{sys.argv[1]}/")
print(result["KeyCount"])
""", str(aid))
check(count == "1", "duplicate created another variant object")
print("PASS duplicate delivery: ready snapshot unchanged, one SQL row and one S3 variant")
def restart_scenarios(c, alice, bob, eve, chat):
action("stop", "worker")
try:
a = upload(c, alice, chat)["json"]
carrier = queued_carrier()
check(carrier["attachment_id"] == a["id"] and carrier["attempt"] == 1,
"RabbitMQ job identity differs from upload")
b = upload(c, bob, chat)["json"]
check(a["id"] != b["id"], "distinct uploads reused ID")
key = uuid4().hex
with ThreadPoolExecutor(max_workers=8) as pool:
calls = list(pool.map(lambda _: c.message(bob, chat, "", key, [a["id"]]), range(8)))
check(len({x["json"]["id"] for x in calls}) == 1, "idempotency race produced duplicates")
observed = {x["headers"]["X-Instance-Id"] for x in calls}
check(observed == {"api1", "api2"}, "idempotency requests did not use both replicas")
check(calls[0]["json"]["attachment_ids"] == [a["id"]], "queued attachment link lost")
c.message(alice, chat, "ordinary text with worker stopped")
check(metadata(c, bob, a) == a, "queued metadata changed with worker stopped")
expect_unavailable(c, bob, a)
private("api1", f"staging/{a['id']}")
print(f"PASS stopped worker: uploads=202 ids={a['id']},{b['id']}; queued content=409; "
"linked and ordinary POST=201; concurrent same-key response identical via api1/api2")
starts = {s: inspect(s, "{{.State.StartedAt}}") for s in ("api1", "api2")}
action("restart", "api1", "api2")
ready(c)
for service, old in starts.items():
new = inspect(service, "{{.State.StartedAt}}")
check(new != old, f"{service} did not actually restart")
print(f"{service} started before={old} after={new}")
check(metadata(c, bob, a) == a and job_state(a).startswith("queued|1|"),
"accepted job lost after API restart")
volume_format = "{{range .Mounts}}{{if eq .Destination \"/var/lib/rabbitmq\"}}{{.Name}}{{end}}{{end}}"
volume = inspect("broker", volume_format)
check(volume == f"{PROJECT}_broker_data", "unexpected RabbitMQ volume")
check(queue_stats() == (2, 0), "expected two pending jobs before broker restart")
broker_start = inspect("broker", "{{.State.StartedAt}}")
action("restart", "broker")
eventually("broker healthy", lambda: inspect("broker", "{{.State.Health.Status}}") == "healthy")
broker_after = inspect("broker", "{{.State.StartedAt}}")
check(broker_start != broker_after and inspect("broker", volume_format) == volume,
"broker restart or volume identity mismatch")
print(f"broker started before={broker_start} after={broker_after} volume={volume}")
check(queue_stats() == (2, 0), "broker restart lost accepted jobs")
check(metadata(c, bob, b) == b, "second job metadata lost")
print("PASS both APIs + RabbitMQ restarted with queued work and unchanged RabbitMQ volume")
path = f"/api/v1/attachments/{a['id']}"
c.call("GET", path, 401)
c.call("GET", path + "/content?variant=thumbnail", 404, actor=eve)
with block_variant_insert():
action("start", "worker")
processing = eventually(
"HTTP processing state",
lambda: next((row for row in (a, b) if metadata(c, bob, row)["status"] == "processing"), None),
6, interval=0.05,
)
expect_unavailable(c, bob, processing)
c.message(bob, chat, "linked during processing", attachments=[processing["id"]])
print("PASS processing metadata visible, content=409, linking=201 before final SQL commit")
a_ready, _ = assert_ready(c, bob, a, SAMPLE, (256, 160))
assert_ready(c, alice, b, SAMPLE, (256, 160))
duplicate(c, bob, a, carrier, a_ready)
private("api1", f"originals/{a['id']}")
c.call("GET", path + "/content?variant=unknown", 404, actor=bob)
finally:
action("start", "worker")
def image_bytes(image, fmt, **kwargs):
data = BytesIO()
image.save(data, fmt, **kwargs)
return data.getvalue()
def input_and_image_cases(c, alice, eve, chat):
for data, mime, status, actor, filename in (
(SAMPLE, "image/jpeg", 415, alice, "wrong-mime"),
(SAMPLE[:-8], "image/png", 415, alice, "corrupt"),
(b"x" * (10 * 1024 * 1024 + 1), "image/png", 413, alice, "oversize"),
(SAMPLE, "image/png", 404, eve, "private"),
(SAMPLE, "image/png", 401, None, "anonymous"),
(SAMPLE, "image/png", 400, alice, "invalid%2Fname.png"),
):
upload(c, actor, chat, data, mime, status, filename)
print(f"negative upload {filename} HTTP {status}")
huge = image_bytes(Image.new("1", (8001, 5000)), "PNG")
upload(c, alice, chat, huge, expected=413)
print("negative upload 40,005,000 decoded pixels HTTP 413")
exif = Image.Exif()
exif[274] = 6
original = image_bytes(Image.new("RGB", (319, 101), "navy"), "JPEG", exif=exif)
broken = original[:100]
upload(c, alice, chat, broken, mime="image/jpeg", expected=415)
print("negative truncated JPEG HTTP 415")
oriented = upload(c, alice, chat, original, "image/jpeg")["json"]
assert_ready(c, alice, oriented, original, (81, 256), "image/jpeg")
original = image_bytes(Image.new("RGBA", (37, 19), (255, 0, 0, 0)), "PNG")
alpha = upload(c, alice, chat, original)["json"]
_, pixel = assert_ready(c, alice, alpha, original, (37, 19))
check(min(pixel) >= 250, "transparent pixel was not composited on white")
print(f"PASS true JPEG, EXIF orientation, floor rounding, no upscale, alpha pixel={pixel}")
def failure_cases(c, alice, bob, chat):
action("stop", "worker")
try:
a = upload(c, alice, chat)["json"]
action("stop", "s3")
action("start", "worker")
state = eventually("persistent retry after real S3 stop", lambda:
(s := job_state(a)) and "storage_unavailable" in s and s)
print(f"storage outage SQL status|attempt|reason|max={state}")
finally:
action("start", "s3", "worker")
ready(c)
assert_ready(c, bob, a, SAMPLE, (256, 160))
check(int(job_state(a).split("|")[1]) >= 2, "no durable retries recorded")
print("PASS temporary S3 outage recovered the same attachment")
action("stop", "worker")
try:
missing = upload(c, alice, chat)["json"]
corrupt = upload(c, alice, chat)["json"]
inside("api1", "python", "-c", """
from io import BytesIO
import sys
from src import s3
s3.delete(f"staging/{sys.argv[1]}")
damaged = BytesIO(b"X" * int(sys.argv[3]))
s3.put(f"staging/{sys.argv[2]}", damaged, damaged.getbuffer().nbytes, "image/png")
""", missing["id"], corrupt["id"], str(corrupt["size_bytes"]))
finally:
action("start", "worker")
for row, error in ((corrupt, "invalid_image"), (missing, "retry_exhausted")):
failed = eventually(f"failed {row['id']}", lambda:
(meta := metadata(c, bob, row))["status"] == "failed" and meta)
check(failed["error_code"] == error and failed["variants"] == [], "unsafe failed result")
state = job_state(row)
status, current, _, maximum = state.split("|")
check(status == "failed" and int(current) == (1 if error == "invalid_image" else int(maximum)),
"unexpected number of attempts")
expect_unavailable(c, bob, row)
c.call("POST", f"/api/v1/chats/{chat['id']}/messages", 409, actor=bob,
body={"text": "", "attachment_ids": [row["id"]]},
headers={"Idempotency-Key": uuid4().hex})
print(f"PASS safe failure code={error}; status|attempt|reason|max={state}; content/link HTTP 409")
action("stop", "broker")
try:
response = upload(c, alice, chat, expected=503)
check(response["json"]["error"]["code"] == "unavailable", "unexpected queue-down response")
c.message(alice, chat, "normal API works when broker is stopped")
print("PASS unavailable broker upload=503 (no false 202), ordinary message=201")
finally:
action("start", "broker")
eventually("broker healthy after failure case", lambda:
inspect("broker", "{{.State.Health.Status}}") == "healthy")
def replica_cases(c, alice, bob, chat):
for stopped, survivor in (("api1", "api2"), ("api2", "api1")):
action("stop", stopped)
try:
eventually(f"{survivor} handles existing Bearer with {stopped} stopped", lambda:
c.call("GET", "/api/v1/users/me", actor=bob, schema="User")["headers"]
["X-Instance-Id"] == survivor)
response = upload(c, alice, chat)
check(response["headers"]["X-Instance-Id"] == survivor, "wrong upload replica")
assert_ready(c, bob, response["json"], SAMPLE, (256, 160))
finally:
action("start", stopped)
eventually(f"{stopped} container healthy", lambda:
inspect(stopped, "{{.State.Health.Status}}") == "healthy")
print("PASS authorized new uploads and thumbnail reads with either replica stopped")
def main():
check(re.fullmatch(r"mtusi-lab5-grade3(?:-[a-z0-9-]+)?", PROJECT), "unsafe project name")
c = Client("http://lb:8080")
ready(c)
alice, bob, eve, chat = c.bootstrap()
alice_id = UUID(alice["id"])
check(sql(f"SELECT password_hash LIKE '$argon2id$%' FROM users WHERE id='{alice_id}'") == "t",
"stored verifier is not Argon2id")
print("PASS Argon2id verifier confirmed without reading hash")
restart_scenarios(c, alice, bob, eve, chat)
input_and_image_cases(c, alice, eve, chat)
failure_cases(c, alice, bob, chat)
replica_cases(c, alice, bob, chat)
check(queue_stats() == (0, 0), "queue did not drain")
print("PASS Lab 5 grade 3 Docker scenarios")
if __name__ == "__main__":
run(main)