feat: Carry runnable lab5 business stack into lab6 (U1)
Import committed lab5 baseline 03899d7 via git archive: API replicas, PostgreSQL, private S3, RabbitMQ, publisher, worker, migrations, and hooks. Preserve lab6 contracts and the separate telemetry stack. Static checks pass; Docker runtime integration remains pending.
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
"""Small checks for the worker's deterministic image and payload boundary."""
|
||||
|
||||
import json
|
||||
import unittest
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from src.image_variants import InvalidImage, render
|
||||
from src.worker import parse_message
|
||||
|
||||
|
||||
def encoded(image, format="PNG", **options):
|
||||
stream = BytesIO()
|
||||
image.save(stream, format=format, **options)
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
class ImagePipelineTest(unittest.TestCase):
|
||||
def test_contract_sizes_original_and_content_types(self):
|
||||
original = encoded(Image.new("RGB", (320, 200), "red"))
|
||||
result = render(original, "image/png")
|
||||
self.assertEqual(result["original"]["data"], original)
|
||||
self.assertEqual((result["thumbnail"]["width"], result["thumbnail"]["height"]), (256, 160))
|
||||
self.assertEqual((result["crop"]["width"], result["crop"]["height"]), (128, 128))
|
||||
self.assertEqual((result["optimized"]["width"], result["optimized"]["height"]), (320, 200))
|
||||
self.assertEqual([result[name]["content_type"] for name in ("thumbnail", "crop", "optimized")],
|
||||
["image/jpeg", "image/jpeg", "image/webp"])
|
||||
|
||||
def test_alpha_is_white_and_small_image_is_not_upscaled(self):
|
||||
original = encoded(Image.new("RGBA", (24, 12), (255, 0, 0, 0)))
|
||||
result = render(original, "image/png")
|
||||
self.assertEqual((result["thumbnail"]["width"], result["thumbnail"]["height"]), (24, 12))
|
||||
with Image.open(BytesIO(result["thumbnail"]["data"])) as thumb:
|
||||
self.assertTrue(all(channel >= 245 for channel in thumb.getpixel((0, 0))))
|
||||
|
||||
def test_exif_orientation_and_center_crop(self):
|
||||
image = Image.new("RGB", (30, 10), "green")
|
||||
image.paste("red", (0, 0, 10, 10))
|
||||
image.paste("blue", (20, 0, 30, 10))
|
||||
exif = Image.Exif()
|
||||
exif[274] = 6
|
||||
original = encoded(image, "JPEG", exif=exif)
|
||||
result = render(original, "image/jpeg")
|
||||
self.assertEqual((result["thumbnail"]["width"], result["thumbnail"]["height"]), (10, 30))
|
||||
with Image.open(BytesIO(result["crop"]["data"])) as crop:
|
||||
red, green, blue = crop.getpixel((64, 64))
|
||||
self.assertGreater(green, red)
|
||||
self.assertGreater(green, blue)
|
||||
|
||||
def test_rejects_wrong_type_and_corrupt_file(self):
|
||||
original = encoded(Image.new("RGB", (2, 2), "black"))
|
||||
with self.assertRaises(InvalidImage):
|
||||
render(original, "image/jpeg")
|
||||
with self.assertRaises(InvalidImage):
|
||||
render(b"broken", "image/png")
|
||||
|
||||
def test_payload_contains_only_versioned_job_identifiers(self):
|
||||
body = {
|
||||
"schema_version": 1,
|
||||
"job_id": "11111111-1111-4111-8111-111111111111",
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": "22222222-2222-4222-8222-222222222222",
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": "2026-09-01T12:00:00Z",
|
||||
}
|
||||
self.assertEqual(parse_message(json.dumps(body).encode()), body)
|
||||
with self.assertRaises(ValueError):
|
||||
parse_message(json.dumps({**body, "staging_key": "private"}).encode())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Keep broker messages within the public job schema and free of file data."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import validate # noqa: E402
|
||||
from src.pipeline_jobs import job_payload # noqa: E402
|
||||
|
||||
|
||||
class OutboxPayloadTest(unittest.TestCase):
|
||||
def test_job_message_has_only_contract_fields(self):
|
||||
schema = json.loads((ROOT / "contracts/jobs.schema.json").read_text(encoding="utf-8"))
|
||||
row = {
|
||||
"job_id": uuid4(), "attachment_id": uuid4(), "pipeline_version": 2,
|
||||
"attempt": 3, "created_at": datetime.now(timezone.utc),
|
||||
"object_key": "staging/must-not-leak", "bytes": b"must-not-leak",
|
||||
}
|
||||
message = job_payload(row)
|
||||
validate(message, schema)
|
||||
self.assertEqual(set(message), set(schema["required"]))
|
||||
self.assertNotIn("staging", json.dumps(message))
|
||||
self.assertNotIn("bytes", json.dumps(message))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Run inside the cleanup image against an isolated pair of staging keys."""
|
||||
|
||||
import time
|
||||
import sys
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.db import pool
|
||||
from src.pipeline_jobs import reserve_upload
|
||||
from src.staging_cleanup import BUCKET, clean_once, storage
|
||||
|
||||
|
||||
client = storage()
|
||||
orphan_id, active_id = uuid4(), uuid4()
|
||||
orphan_key, active_key = f"staging/{orphan_id}", f"staging/{active_id}"
|
||||
|
||||
|
||||
def exists(key):
|
||||
return any(obj.object_name == key for obj in client.list_objects(BUCKET, prefix=key))
|
||||
|
||||
|
||||
try:
|
||||
for key in (orphan_key, active_key):
|
||||
client.put_object(BUCKET, key, BytesIO(b"test"), 4, content_type="image/png")
|
||||
with pool().connection() as conn:
|
||||
reserve_upload(conn, active_id, active_key, lease_seconds=60)
|
||||
time.sleep(2)
|
||||
clean_once(client, grace_seconds=1)
|
||||
assert not exists(orphan_key), "old orphan was not removed"
|
||||
assert exists(active_key), "active upload was removed"
|
||||
|
||||
with pool().connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE attachment_uploads SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=%s",
|
||||
(active_id,),
|
||||
)
|
||||
clean_once(client, grace_seconds=1)
|
||||
assert not exists(active_key), "expired orphan was not removed"
|
||||
print("PASS: cleanup removes old orphans and preserves active uploads")
|
||||
finally:
|
||||
for key in (orphan_key, active_key):
|
||||
client.remove_object(BUCKET, key)
|
||||
with pool().connection() as conn:
|
||||
conn.execute("DELETE FROM attachment_uploads WHERE id=%s", (active_id,))
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise 202 handoff while RabbitMQ and worker are unavailable."""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT, check=True, stdout=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def ready_after_restart(client):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure("API did not recover after restart")
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab5 durable upload handoff with stopped broker and worker")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
compose("stop", "worker", "publisher", "broker")
|
||||
try:
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", 409, actor=bob)
|
||||
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
check(message["attachment_ids"] == [attachment["id"]], "queued attachment cannot be linked")
|
||||
|
||||
compose("up", "-d", "broker")
|
||||
compose("restart", "api")
|
||||
ready_after_restart(client)
|
||||
check(
|
||||
client.call("GET", f"/api/v1/attachments/{attachment['id']}", actor=bob, schema="Attachment")["json"]["status"] == "queued",
|
||||
"accepted job disappeared before publisher restart",
|
||||
)
|
||||
compose("up", "-d", "publisher", "worker")
|
||||
client.wait_ready(bob, attachment)
|
||||
result = client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)
|
||||
check(result["bytes"] == original, "accepted original changed after recovery")
|
||||
finally:
|
||||
compose("up", "-d", "broker", "publisher", "worker")
|
||||
print("PASS: accepted upload survived broker/API outage and reached ready")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Public U2 check while publisher and worker are stopped."""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab5 durable queued upload")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
attachment, _content = client.attachment(alice, chat)
|
||||
check(attachment["status"] == "queued", "upload did not enter queued state")
|
||||
client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", 409, actor=bob)
|
||||
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
check(message["attachment_ids"] == [attachment["id"]], "queued attachment cannot be linked")
|
||||
print("PASS: 202 queued upload is readable and linkable; content is pending")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check every public variant against committed metadata and original bytes."""
|
||||
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab5 ready variants")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
ready = client.wait_ready(bob, attachment)
|
||||
variants = {item["name"]: item for item in ready["variants"]}
|
||||
check(set(variants) == {"thumbnail", "crop", "optimized"}, "incomplete variant set")
|
||||
expected = {
|
||||
"thumbnail": ("image/jpeg", 256, 160),
|
||||
"crop": ("image/jpeg", 128, 128),
|
||||
"optimized": ("image/webp", 320, 200),
|
||||
}
|
||||
for name, (content_type, width, height) in expected.items():
|
||||
variant = variants[name]
|
||||
check((variant["content_type"], variant["width"], variant["height"]) ==
|
||||
(content_type, width, height), f"wrong {name} metadata")
|
||||
response = client.call(
|
||||
"GET", f"/api/v1/attachments/{attachment['id']}/content?variant={name}", actor=bob
|
||||
)
|
||||
check(response["headers"].get_content_type() == content_type, f"wrong {name} MIME")
|
||||
check(len(response["bytes"]) == variant["size_bytes"] and
|
||||
hashlib.sha256(response["bytes"]).hexdigest() == variant["sha256"],
|
||||
f"wrong {name} bytes")
|
||||
client.call(
|
||||
"GET", f"/api/v1/attachments/{attachment['id']}/content?variant={name}",
|
||||
404, actor=eve,
|
||||
)
|
||||
downloaded = client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)
|
||||
check(downloaded["bytes"] == original, "original bytes changed")
|
||||
print("PASS: all three variants match metadata; original preserved; outsider denied")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user