Declare the classic dead-letter topology, reject terminal worker outcomes without requeue, and add coverage for malformed messages and retry jitter.
139 lines
4.9 KiB
Python
139 lines
4.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Verify terminal worker failures and rejected messages reach the durable DLQ."""
|
|
|
|
import hashlib
|
|
import os
|
|
import time
|
|
from io import BytesIO
|
|
from pathlib import Path
|
|
from uuid import uuid4
|
|
|
|
import pika
|
|
|
|
from src.worker import _delay, settle_delivery
|
|
from src.attachments import BUCKET, storage
|
|
from src.db import pool
|
|
from src.pipeline_jobs import queue_attachment, reserve_upload
|
|
|
|
|
|
QUEUE = os.environ.get("BROKER_QUEUE", "attachments.process")
|
|
DLQ = os.environ.get("BROKER_DLQ", "attachments.dlq")
|
|
PROBE_ID = f"lab5-dlq-{uuid4()}"
|
|
|
|
|
|
class RecordingChannel:
|
|
def __init__(self):
|
|
self.calls = []
|
|
|
|
def basic_reject(self, delivery_tag, requeue):
|
|
self.calls.append(("reject", delivery_tag, requeue))
|
|
|
|
def basic_ack(self, delivery_tag):
|
|
self.calls.append(("ack", delivery_tag))
|
|
|
|
|
|
def check_terminal_settlement():
|
|
channel = RecordingChannel()
|
|
settle_delivery(channel, 1, "failed")
|
|
settle_delivery(channel, 2, "queued")
|
|
assert channel.calls == [("reject", 1, False), ("ack", 2)]
|
|
|
|
|
|
def check_retry_jitter():
|
|
for attempt, base in ((1, 1), (5, 16), (6, 30)):
|
|
delay = _delay(attempt)
|
|
assert base <= delay <= base * 1.5, (attempt, delay)
|
|
|
|
|
|
def create_invalid_image_job():
|
|
user_id, chat_id, attachment_id = uuid4(), uuid4(), uuid4()
|
|
staging_key = f"staging/{attachment_id}"
|
|
source = b"synthetic invalid image"
|
|
digest = hashlib.sha256(source).hexdigest()
|
|
with pool().connection() as conn:
|
|
with conn.transaction():
|
|
conn.execute(
|
|
"INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)",
|
|
(user_id, f"dlq_{user_id.hex[:20]}", "DLQ test fixture", "synthetic"),
|
|
)
|
|
conn.execute("INSERT INTO chats (id,title) VALUES (%s,%s)", (chat_id, "DLQ test fixture"))
|
|
conn.execute(
|
|
"INSERT INTO memberships (chat_id,user_id,position) VALUES (%s,%s,0)",
|
|
(chat_id, user_id),
|
|
)
|
|
reserve_upload(conn, attachment_id, staging_key)
|
|
storage().put_object(
|
|
BUCKET, staging_key, BytesIO(source), len(source), content_type="image/png",
|
|
)
|
|
with pool().connection() as conn:
|
|
_, job_id = queue_attachment(
|
|
conn,
|
|
attachment_id=attachment_id,
|
|
chat_id=chat_id,
|
|
owner_id=user_id,
|
|
filename="invalid.png",
|
|
staging_key=staging_key,
|
|
object_key=f"originals/{attachment_id}",
|
|
content_type="image/png",
|
|
size_bytes=len(source),
|
|
sha256=digest,
|
|
)
|
|
return job_id
|
|
|
|
|
|
def wait_for_dead_letter(connection, channel, expected_id):
|
|
deadline = time.monotonic() + 20
|
|
while time.monotonic() < deadline:
|
|
method, properties, _body = channel.basic_get(queue=DLQ, auto_ack=False)
|
|
if method is None:
|
|
connection.process_data_events(time_limit=0.2)
|
|
continue
|
|
if properties.message_id != expected_id:
|
|
channel.basic_nack(method.delivery_tag, requeue=True)
|
|
raise AssertionError("unexpected message appeared in an initially empty DLQ")
|
|
deaths = (properties.headers or {}).get("x-death", [])
|
|
assert any(death.get("queue") == QUEUE and death.get("reason") == "rejected"
|
|
for death in deaths), deaths
|
|
channel.basic_ack(method.delivery_tag)
|
|
return
|
|
raise AssertionError(f"message {expected_id} did not reach the DLQ")
|
|
|
|
|
|
def main():
|
|
check_terminal_settlement()
|
|
check_retry_jitter()
|
|
url = Path(os.environ["BROKER_URL_FILE"]).read_text(encoding="utf-8").strip()
|
|
connection = pika.BlockingConnection(pika.URLParameters(url))
|
|
try:
|
|
channel = connection.channel()
|
|
channel.confirm_delivery()
|
|
depth = channel.queue_declare(queue=DLQ, passive=True).method.message_count
|
|
if depth:
|
|
raise SystemExit(f"{DLQ} already contains {depth} message(s); inspect it before this demo")
|
|
|
|
channel.basic_publish(
|
|
exchange="",
|
|
routing_key=QUEUE,
|
|
body=b"{invalid-json",
|
|
mandatory=True,
|
|
properties=pika.BasicProperties(
|
|
content_type="application/json", delivery_mode=2, message_id=PROBE_ID,
|
|
),
|
|
)
|
|
wait_for_dead_letter(connection, channel, PROBE_ID)
|
|
|
|
job_id = create_invalid_image_job()
|
|
wait_for_dead_letter(connection, channel, str(job_id))
|
|
with pool().connection() as conn:
|
|
job = conn.execute(
|
|
"SELECT status,error_code FROM attachment_jobs WHERE id=%s", (job_id,),
|
|
).fetchone()
|
|
assert job["status"] == "failed" and job["error_code"] == "invalid_image", job
|
|
print("PASS: malformed message and permanently invalid image reached DLQ; failed job was recorded in PostgreSQL; retry jitter bounds passed")
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|