Files
mtusi2026lab5/student_tests/lab5_dlq_replay_lease.py
T
2026-11-19 07:57:14 +03:00

127 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""Exercise DLQ routing, guarded replay and expired processing leases."""
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
COMPOSE = ["docker", "compose", "--env-file", ".env.example"]
def command(*args, capture=False):
result = subprocess.run(
[*COMPOSE, *args], cwd=ROOT, check=True, text=True,
capture_output=capture)
return result.stdout.strip() if capture else ""
def database_scalar(sql):
return command(
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-At", "-c", sql, capture=True)
def env_value(name):
for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines():
if line.startswith(name + "="):
return line.split("=", 1)[1]
raise Failure("missing " + name + " in .env.example")
def queue_ready(queue):
listing = command(
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
"name", "messages_ready", capture=True)
for line in listing.splitlines():
columns = line.split("\t")
if len(columns) == 2 and columns[0] == queue:
return int(columns[1])
raise Failure("queue not found: " + queue)
def wait_ready(client, actor, attachment, seconds=120):
return client.wait_ready(actor, attachment, wait_seconds=seconds)
def replay(job_id):
subprocess.run(
["powershell", "-NoProfile", "-File", str(ROOT / "scripts" / "replay-failed.ps1"),
"-JobId", job_id, "-RequestedBy", "integration-test",
"-EnvFile", ".env.example"],
cwd=ROOT, check=True, text=True)
def main():
client = Client("http://localhost:8080")
alice, bob, _, chat = client.bootstrap()
# A permanently malformed delivery is rejected and dead-lettered.
before_dlq = queue_ready(env_value("ATTACHMENT_DLQ_QUEUE"))
command(
"exec", "-T", "rabbitmq", "rabbitmqadmin",
"-u", env_value("RABBITMQ_USER"), "-p", env_value("RABBITMQ_PASSWORD"),
"publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"),
"routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"),
"payload={}",
'properties={"delivery_mode":2,"content_type":"application/json"}')
deadline = time.monotonic() + 30
while time.monotonic() < deadline and queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) <= before_dlq:
time.sleep(0.5)
check(queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) == before_dlq + 1,
"malformed permanent failure was not dead-lettered exactly once")
# Replay is allowed only from failed and creates one audit record.
command("stop", "worker")
failed, _ = client.attachment(alice, chat)
job_id = database_scalar(
"SELECT id FROM attachment_jobs WHERE attachment_id = '" + failed["id"] + "';")
database_scalar(
"UPDATE attachment_jobs SET status='failed', published=true, "
"last_error_code='retry_exhausted', lease_token=NULL, lease_until=NULL "
"WHERE id='" + job_id + "'; "
"UPDATE attachments SET status='failed', error_code='retry_exhausted' "
"WHERE id='" + failed["id"] + "'; SELECT 1;")
replay(job_id)
replay(job_id)
audit_count = database_scalar(
"SELECT count(*) FROM attachment_job_replays WHERE job_id='" + job_id + "';")
check(audit_count == "1", "replay was not guarded or was audited more than once")
command("start", "worker")
ready = wait_ready(client, bob, failed)
check(ready["status"] == "ready", "replayed failed job did not become ready")
replay(job_id)
check(database_scalar(
"SELECT count(*) FROM attachment_job_replays WHERE job_id='" + job_id + "';") == "1",
"replay changed an already successful job")
check(database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" + failed["id"] + "';") == "3",
"replay did not preserve exactly one variant set")
# The API reaper returns an expired processing lease to the durable outbox.
command("stop", "worker")
leased, _ = client.attachment(alice, chat)
lease_job = database_scalar(
"SELECT id FROM attachment_jobs WHERE attachment_id='" + leased["id"] + "';")
database_scalar(
"UPDATE attachment_jobs SET status='processing', attempt=1, published=true, "
"lease_token=gen_random_uuid(), lease_until=clock_timestamp()-interval '1 second' "
"WHERE id='" + lease_job + "'; "
"UPDATE attachments SET status='processing' WHERE id='" + leased["id"] + "'; SELECT 1;")
command("start", "worker")
lease_ready = wait_ready(client, bob, leased)
check(lease_ready["status"] == "ready", "expired processing lease was not recovered")
check(int(database_scalar(
"SELECT attempt FROM attachment_jobs WHERE id='" + lease_job + "';")) >= 2,
"expired lease did not consume a bounded retry attempt")
print("PASS: DLQ, guarded replay and expired lease recovery")
if __name__ == "__main__":
run(main)