Files
mtusi2026lab6/student-tests/publish_gap_inner.py
T

66 lines
2.6 KiB
Python

"""Run in a one-shot publisher container to inject publish-before-confirm gap."""
import json
import os
import time
from pathlib import Path
from uuid import UUID, uuid4
import pika
from src.db import pool
from src.publisher import QUEUE, job_payload, publish_batch
attachment_id = UUID(os.environ["FAULT_ATTACHMENT_ID"])
url = Path(os.environ["BROKER_URL_FILE"]).read_text(encoding="utf-8").strip()
broker = pika.BlockingConnection(pika.URLParameters(url))
try:
channel = broker.channel()
channel.queue_declare(queue=QUEUE, passive=True)
channel.confirm_delivery()
token = uuid4()
with pool().connection() as conn:
row = conn.execute(
"SELECT o.id,o.job_id,o.attempt,j.attachment_id,j.pipeline_version,j.created_at "
"FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id "
"WHERE j.attachment_id=%s AND j.pipeline_version=1 AND o.attempt=1",
(attachment_id,),
).fetchone()
assert row is not None
claimed = conn.execute(
"UPDATE attachment_outbox SET claim_token=%s,"
"claim_expires_at=clock_timestamp()+interval '30 seconds' "
"WHERE id=%s AND claim_token IS NULL AND published_at IS NULL RETURNING id",
(token, row["id"]),
).fetchone()
assert claimed is not None
body = json.dumps(job_payload(row), separators=(",", ":")).encode()
channel.basic_publish(
exchange="", routing_key=QUEUE, mandatory=True, body=body,
properties=pika.BasicProperties(content_type="application/json", delivery_mode=2),
)
# Simulate process death after broker confirm, before PostgreSQL confirm.
with pool().connection() as conn:
conn.execute(
"UPDATE attachment_outbox SET claim_expires_at=clock_timestamp()-interval '1 second' "
"WHERE id=%s AND claim_token=%s AND published_at IS NULL",
(row["id"], token),
)
published = publish_batch(channel)
with pool().connection() as conn:
outbox = conn.execute(
"SELECT published_at IS NOT NULL AS confirmed FROM attachment_outbox "
"WHERE id=%s", (row["id"],),
).fetchone()
deadline = time.monotonic() + 3
while True:
count = channel.queue_declare(queue=QUEUE, passive=True).method.message_count
if count >= 2 or time.monotonic() >= deadline:
break
time.sleep(0.05)
assert published >= 1 and outbox["confirmed"] and count >= 2
print(json.dumps({"confirmed_after_republish": True, "queued_copies_before_worker": count}))
finally:
broker.close()