forked from mtusi2026/mtusi2026lab5
140 lines
7.3 KiB
Python
140 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Functional suite for the asynchronous pipeline (levels 3-4): variants, EXIF orientation, alpha, limits,
|
|
permanent failures. Black box through the LB, plus the operator CLI for attempt counters."""
|
|
import hashlib
|
|
import time
|
|
import uuid
|
|
from urllib.parse import quote
|
|
|
|
from stack import (SAMPLE_PNG, corrupt_png, fixture, has_exif, inspect, jpeg_size, pixel, png_header_only,
|
|
webp_size)
|
|
from client import Client, arguments, check, run
|
|
|
|
LIMIT = 10 * 1024 * 1024
|
|
|
|
|
|
def main():
|
|
args = arguments("Async attachment pipeline: variants and failures")
|
|
c = Client(args.base_url, timeout=30)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
results = []
|
|
|
|
def case(name, fn):
|
|
started = time.monotonic()
|
|
fn()
|
|
results.append(name)
|
|
print("PASS %-70s %.1fs" % (name, time.monotonic() - started))
|
|
|
|
def upload(data, ctype="image/png", filename="f.png", expected=202):
|
|
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename, safe="")
|
|
r = c.call("POST", path, expected, actor=alice, raw=data, headers={"Content-Type": ctype},
|
|
schema="Attachment" if expected == 202 else None)
|
|
return r["json"]
|
|
|
|
def wait_final(att, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
att = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
|
|
if att["status"] in ("ready", "failed"):
|
|
return att
|
|
time.sleep(0.2)
|
|
raise AssertionError("attachment did not reach a final state")
|
|
|
|
def content(att, variant=None, expected=200, actor=bob):
|
|
q = "" if variant is None else "?variant=" + variant
|
|
return c.call("GET", "/api/v1/attachments/" + att["id"] + "/content" + q, expected, actor=actor)
|
|
|
|
def variants(att):
|
|
return {v["name"]: v for v in att["variants"]}
|
|
|
|
def verify_variant(att, name, ctype, size):
|
|
v = variants(att)[name]
|
|
d = content(att, name)
|
|
check(d["headers"].get_content_type() == ctype == v["content_type"], name + " content type")
|
|
check(len(d["bytes"]) == v["size_bytes"] and hashlib.sha256(d["bytes"]).hexdigest() == v["sha256"], name + " checksum")
|
|
real = jpeg_size(d["bytes"]) if ctype == "image/jpeg" else webp_size(d["bytes"])
|
|
check(real == size == (v["width"], v["height"]), "%s: expected %s, metadata %sx%s, real %s" % (
|
|
name, size, v["width"], v["height"], real))
|
|
check(not has_exif(d["bytes"]), name + " must not carry EXIF")
|
|
return d["bytes"]
|
|
|
|
def sample():
|
|
a = upload(SAMPLE_PNG, filename="sample.png")
|
|
check(a["status"] == "queued" and a["variants"] == [] and a["error_code"] is None, "202 snapshot")
|
|
r = wait_final(a)
|
|
check(r["status"] == "ready" and r["error_code"] is None, "sample ready")
|
|
check([v["name"] for v in r["variants"]] == ["thumbnail", "crop", "optimized"], "exactly three variants")
|
|
verify_variant(r, "thumbnail", "image/jpeg", (256, 160))
|
|
verify_variant(r, "crop", "image/jpeg", (128, 128))
|
|
verify_variant(r, "optimized", "image/webp", (320, 200)) # no upscaling beyond the source
|
|
orig = content(r)
|
|
check(orig["bytes"] == SAMPLE_PNG and orig["headers"].get_content_type() == "image/png", "original unchanged")
|
|
check(r["sha256"] == hashlib.sha256(SAMPLE_PNG).hexdigest() and r["size_bytes"] == len(SAMPLE_PNG), "original metadata")
|
|
info = inspect(r["id"])
|
|
check(info["jobs"][0]["attempt"] == 1 and info["s3_staging_keys"] == [], "one attempt, staging removed")
|
|
check(len(info["s3_final_keys"]) == 4, "original + 3 variants in final prefix")
|
|
case("sample.png 320x200 -> thumbnail 256x160, crop 128x128, webp 320x200; original byte-identical", sample)
|
|
|
|
def exif():
|
|
data = fixture("exif_rot6.jpg")
|
|
r = wait_final(upload(data, "image/jpeg", "rotated.jpg"))
|
|
check(r["status"] == "ready", "exif jpeg ready")
|
|
# stored 300x200 with Orientation=6 -> displayed 200x300; fit 256: 170x256 (floor of 200*256/300)
|
|
verify_variant(r, "thumbnail", "image/jpeg", (170, 256))
|
|
verify_variant(r, "optimized", "image/webp", (200, 300))
|
|
verify_variant(r, "crop", "image/jpeg", (128, 128))
|
|
check(content(r)["bytes"] == data and has_exif(data), "original keeps its own EXIF byte-for-byte")
|
|
case("EXIF orientation applied, EXIF stripped from variants (thumbnail 170x256)", exif)
|
|
|
|
def alpha():
|
|
r = wait_final(upload(fixture("alpha.png"), filename="alpha.png"))
|
|
thumb = verify_variant(r, "thumbnail", "image/jpeg", (64, 40)) # small source is not upscaled
|
|
crop = verify_variant(r, "crop", "image/jpeg", (128, 128)) # crop may upscale
|
|
check(min(pixel(thumb, 56, 20)) >= 245, "transparent area must become white")
|
|
g = pixel(thumb, 8, 20)
|
|
check(g[1] > 120 and g[0] < 60 and g[2] < 60, "opaque green stays green")
|
|
check(min(pixel(crop, 120, 64)) >= 245, "crop: alpha on white")
|
|
case("RGBA 64x40: no upscaling of thumbnail, alpha composited on white, crop upscaled", alpha)
|
|
|
|
def wide():
|
|
r = wait_final(upload(fixture("wide.png"), filename="wide.png"))
|
|
verify_variant(r, "thumbnail", "image/jpeg", (256, 64))
|
|
verify_variant(r, "optimized", "image/webp", (1280, 320))
|
|
case("2000x500 -> thumbnail 256x64, optimized fit 1280x320", wide)
|
|
|
|
def corrupt():
|
|
a = upload(corrupt_png(), filename="broken.png")
|
|
r = wait_final(a)
|
|
check(r["status"] == "failed" and r["error_code"] == "invalid_image" and r["variants"] == [], "invalid_image")
|
|
info = inspect(r["id"])
|
|
check(info["jobs"][0]["attempt"] == 1, "permanent error must not be retried")
|
|
check(not any(e["event"] == "retry_scheduled" for e in info["events"]), "no retry events")
|
|
content(r, None, 409)
|
|
content(r, "thumbnail", 409)
|
|
c.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 409, actor=alice,
|
|
body={"text": "", "attachment_ids": [r["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
|
|
failed = c.call("GET", "/api/v1/attachments/" + r["id"], actor=alice, schema="Attachment")["json"]
|
|
check(failed["error_code"] == "invalid_image", "error visible to members")
|
|
case("PNG with valid CRCs but broken IDAT -> failed/invalid_image after 1 attempt; attach 409, content 409", corrupt)
|
|
|
|
def limits():
|
|
upload(png_header_only(8000, 6000), filename="bomb.png", expected=413) # 48 MP, header only
|
|
upload(b"\x89PNG\r\n\x1a\n" + bytes(LIMIT), filename="big.png", expected=413)
|
|
upload(b"GIF89a" + bytes(100), "image/png", "x.png", expected=415)
|
|
upload(fixture("sample.jpg"), "image/png", "lie.png", expected=415)
|
|
upload(SAMPLE_PNG, "image/png", "a/b.png", expected=400)
|
|
case("synchronous limits before 202: pixels/bytes 413, type 415, filename 400", limits)
|
|
|
|
def access():
|
|
r = wait_final(upload(SAMPLE_PNG, filename="acl.png"))
|
|
for suffix in ("", "/content", "/content?variant=thumbnail"):
|
|
c.call("GET", "/api/v1/attachments/" + r["id"] + suffix, 404, actor=eve)
|
|
content(r, "bogus", 400)
|
|
case("outsider gets 404 for metadata/original/variant; unknown variant 400", access)
|
|
|
|
print("PASS: %d pipeline cases" % len(results))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|