forked from mtusi2026/mtusi2026lab5
196 lines
8.0 KiB
Python
196 lines
8.0 KiB
Python
import hashlib
|
|
import io
|
|
import json
|
|
import unittest
|
|
from contextlib import contextmanager
|
|
from datetime import datetime, timezone
|
|
from unittest.mock import patch
|
|
|
|
from PIL import Image
|
|
|
|
from src.pipeline import CURRENT_PIPELINE_VERSION, pipeline_qualities
|
|
from src.worker import PermanentJobError, TransientJobError, process, record_failure
|
|
|
|
|
|
class InjectedCrash(BaseException):
|
|
pass
|
|
|
|
|
|
class FakeDatabase:
|
|
def __init__(self, attachment_id, job_id, image_bytes, pipeline_version=2):
|
|
self.attachment_id = attachment_id
|
|
self.job_id = job_id
|
|
self.image_bytes = image_bytes
|
|
self.staging_key = f"staging/{attachment_id}/original"
|
|
self.content_type = "image/png"
|
|
self.sha256 = hashlib.sha256(image_bytes).hexdigest()
|
|
self.attachment_status = "queued"
|
|
self.job_status = "queued"
|
|
self.attempt = 0
|
|
self.pipeline_version = pipeline_version
|
|
self.created_at = datetime.now(timezone.utc)
|
|
self.outbox = []
|
|
self.attempts = []
|
|
self.variants = []
|
|
|
|
@contextmanager
|
|
def transaction(self):
|
|
yield self
|
|
|
|
def execute(self, query, params=()):
|
|
statement = " ".join(query.split())
|
|
if statement.startswith("SELECT a.staging_key"):
|
|
if str(params[0]) != self.attachment_id or str(params[1]) != self.job_id:
|
|
self.result = None
|
|
else:
|
|
self.result = {
|
|
"staging_key": self.staging_key,
|
|
"status": self.attachment_status,
|
|
"content_type": self.content_type,
|
|
"size_bytes": len(self.image_bytes),
|
|
"sha256": self.sha256,
|
|
"job_status": self.job_status,
|
|
"lease_until": None,
|
|
"attempt": self.attempt,
|
|
"pipeline_version": self.pipeline_version,
|
|
}
|
|
elif statement.startswith("UPDATE attachments SET status='processing'"):
|
|
self.attachment_status = "processing"
|
|
elif statement.startswith("UPDATE jobs SET attempt=attempt+1"):
|
|
self.attempt += 1
|
|
self.job_status = "processing"
|
|
elif statement.startswith("UPDATE attachments SET status='ready'"):
|
|
self.attachment_status = "ready"
|
|
self.variants = json.loads(params[1])
|
|
elif statement.startswith("UPDATE jobs SET status='ready'"):
|
|
self.job_status = "ready"
|
|
elif statement.startswith("SELECT j.id,j.attachment_id,j.attempt"):
|
|
self.result = {
|
|
"id": self.job_id,
|
|
"attachment_id": self.attachment_id,
|
|
"attempt": self.attempt,
|
|
"pipeline_version": self.pipeline_version,
|
|
"created_at": self.created_at,
|
|
"status": self.attachment_status,
|
|
}
|
|
elif statement.startswith("INSERT INTO job_attempts"):
|
|
self.attempts.append(params)
|
|
elif statement.startswith("UPDATE jobs SET status='queued'"):
|
|
self.job_status = "queued"
|
|
elif statement.startswith("UPDATE attachments SET status='queued'"):
|
|
self.attachment_status = "queued"
|
|
elif statement.startswith("INSERT INTO outbox"):
|
|
payload = params[2]
|
|
self.outbox.append(json.loads(payload) if isinstance(payload, str) else payload)
|
|
else:
|
|
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
|
|
return self
|
|
|
|
def fetchone(self):
|
|
return self.result
|
|
|
|
|
|
class FakeStorage:
|
|
def __init__(self, image_bytes):
|
|
self.image_bytes = image_bytes
|
|
|
|
def get_object(self, **kwargs):
|
|
return {"Body": io.BytesIO(self.image_bytes)}
|
|
|
|
|
|
def png_fixture():
|
|
buffer = io.BytesIO()
|
|
Image.new("RGB", (320, 200), "navy").save(buffer, format="PNG")
|
|
return buffer.getvalue()
|
|
|
|
|
|
class PipelineFaultTests(unittest.TestCase):
|
|
def test_pipeline_versions_are_explicit_and_quality_is_versioned(self):
|
|
self.assertEqual(CURRENT_PIPELINE_VERSION, 2)
|
|
self.assertEqual(pipeline_qualities(1), (88, 82))
|
|
self.assertEqual(pipeline_qualities(2), (86, 80))
|
|
|
|
def make_job(self, db, attempt=1, pipeline_version=2):
|
|
return {
|
|
"job_id": db.job_id,
|
|
"attachment_id": db.attachment_id,
|
|
"attempt": attempt,
|
|
"pipeline_version": pipeline_version,
|
|
}
|
|
|
|
def run_process(self, db, objects, job):
|
|
def put_object(_bucket, key, data, _content_type):
|
|
objects[key] = data
|
|
|
|
with patch("src.worker.transaction", db.transaction), \
|
|
patch("src.worker.s3_client", return_value=FakeStorage(db.image_bytes)), \
|
|
patch("src.worker.put_object", side_effect=put_object), \
|
|
patch.dict("os.environ", {"S3_BUCKET": "test-bucket"}):
|
|
process(job)
|
|
|
|
def test_crash_before_and_after_object_write_retries_idempotently(self):
|
|
for stage in ("before_original_put", "after_original_put"):
|
|
with self.subTest(stage=stage):
|
|
image_bytes = png_fixture()
|
|
attachment_id = "9c554d5e-2d59-4c10-ae40-7f6f7aef6350"
|
|
job_id = "8f4b65d8-091d-423f-9565-d6ab08c8814c"
|
|
db = FakeDatabase(attachment_id, job_id, image_bytes)
|
|
objects = {}
|
|
first_job = self.make_job(db)
|
|
injection = f"{attachment_id}:1:{stage}"
|
|
|
|
with patch("src.worker.transaction", db.transaction), \
|
|
patch("src.worker.s3_client", return_value=FakeStorage(image_bytes)), \
|
|
patch("src.worker.put_object", side_effect=lambda _b, key, data, _c: objects.__setitem__(key, data)), \
|
|
patch.dict("os.environ", {"S3_BUCKET": "test-bucket", "WORKER_FAULT_INJECTION": injection}), \
|
|
patch("src.worker.os._exit", side_effect=InjectedCrash):
|
|
with self.assertRaises(InjectedCrash):
|
|
process(first_job)
|
|
|
|
original_key = f"final/{attachment_id}/original"
|
|
self.assertEqual(original_key in objects, stage == "after_original_put")
|
|
self.assertEqual(db.job_status, "processing")
|
|
|
|
with patch("src.worker.transaction", db.transaction):
|
|
record_failure(first_job, TransientJobError("worker_process_failed"))
|
|
self.assertEqual(db.outbox[0]["attempt"], 2)
|
|
|
|
# The redelivered first attempt is stale; the scheduled retry owns the next attempt.
|
|
self.run_process(db, objects, first_job)
|
|
self.assertEqual(db.job_status, "queued")
|
|
|
|
self.run_process(db, objects, db.outbox[0])
|
|
self.assertEqual(db.job_status, "ready")
|
|
self.assertEqual(db.attachment_status, "ready")
|
|
self.assertEqual(set(objects), {
|
|
original_key,
|
|
f"final/{attachment_id}/thumbnail",
|
|
f"final/{attachment_id}/crop",
|
|
f"final/{attachment_id}/optimized",
|
|
})
|
|
objects_before_duplicate = dict(objects)
|
|
self.run_process(db, objects, db.outbox[0])
|
|
self.assertEqual(objects, objects_before_duplicate)
|
|
|
|
def test_old_pipeline_message_cannot_overwrite_new_version(self):
|
|
image_bytes = png_fixture()
|
|
attachment_id = "9c554d5e-2d59-4c10-ae40-7f6f7aef6350"
|
|
job_id = "8f4b65d8-091d-423f-9565-d6ab08c8814c"
|
|
db = FakeDatabase(attachment_id, job_id, image_bytes, pipeline_version=2)
|
|
objects = {}
|
|
|
|
with self.assertRaises(PermanentJobError):
|
|
self.run_process(db, objects, self.make_job(db, pipeline_version=3))
|
|
|
|
self.run_process(db, objects, self.make_job(db, pipeline_version=1))
|
|
self.assertEqual(objects, {})
|
|
self.assertEqual(db.job_status, "queued")
|
|
|
|
self.run_process(db, objects, self.make_job(db, pipeline_version=2))
|
|
self.assertEqual(db.job_status, "ready")
|
|
self.assertTrue(objects)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|