"""Transactional outbox relay (runs inside every API replica; SKIP LOCKED keeps replicas from double work). Rows are locked while they are published; `published_at` is set in the same transaction only after the broker confirmed the message. A crash between confirm and COMMIT republishes the row: duplicates are expected and harmless (the worker's claim is idempotent). A crash between the upload COMMIT and publish leaves an unpublished row that any replica picks up within OUTBOX_POLL_SECONDS. """ import asyncio import logging from opentelemetry.trace import SpanKind from app import config, telemetry log = logging.getLogger("messenger.outbox") class Relay: def __init__(self, db, publisher) -> None: self.db = db self.publisher = publisher self.wake = asyncio.Event() self.broker_ok = False self.published = 0 def notify(self) -> None: self.wake.set() async def run_once(self) -> int: sent, failure = 0, None async with self.db.connection() as conn: async with conn.transaction(): cur = await conn.execute( "SELECT id, payload FROM outbox WHERE published_at IS NULL AND available_at <= clock_timestamp()" " ORDER BY available_at, id LIMIT %s FOR UPDATE SKIP LOCKED", (config.OUTBOX_BATCH,), ) for row in await cur.fetchall(): try: await self.publish(row["payload"]) except Exception as exc: # Keep what was already confirmed: commit those rows, record the error, stop the batch. await conn.execute( "UPDATE outbox SET publish_attempts = publish_attempts + 1, last_error = %s WHERE id = %s", (type(exc).__name__, row["id"]), ) failure = exc break await conn.execute( "UPDATE outbox SET published_at = clock_timestamp(), publish_attempts = publish_attempts + 1" " WHERE id = %s", (row["id"],), ) sent += 1 self.published += sent if failure is not None: raise failure return sent async def publish(self, payload: dict) -> None: """PRODUCER span, child of the context stored with the job (upload request or failed attempt); the message then carries the producer's own traceparent, so the consumer becomes its child.""" attrs = {"messaging.system": "rabbitmq", "messaging.operation.type": "publish", "messaging.destination.name": config.BROKER_EXCHANGE, "messaging.message.id": payload["job_id"], "messenger.job.attempt": payload["attempt"], "messenger.attachment_id": payload["attachment_id"]} with telemetry.span(config.BROKER_QUEUE + " publish", kind=SpanKind.PRODUCER, context=telemetry.extract(payload), attributes=attrs): body = {k: v for k, v in payload.items() if k not in ("traceparent", "tracestate")} body.update(telemetry.inject()) await self.publisher.publish(body) async def loop(self) -> None: delay = config.OUTBOX_POLL_SECONDS while True: try: await asyncio.wait_for(self.wake.wait(), delay) except asyncio.TimeoutError: pass self.wake.clear() try: while await self.run_once() == config.OUTBOX_BATCH: pass if not self.broker_ok: log.info("outbox_relay_resumed: broker reachable") self.broker_ok = True delay = config.OUTBOX_POLL_SECONDS except Exception as exc: if self.broker_ok: log.warning("outbox_relay_paused: %s; jobs stay in outbox", type(exc).__name__) self.broker_ok = False await self.publisher.close() delay = min(10.0, max(delay * 2, 1.0)) async def cleanup(self) -> int: async with self.db.connection() as conn: cur = await conn.execute( "DELETE FROM outbox WHERE published_at < clock_timestamp() - make_interval(secs => %s)", (config.OUTBOX_RETENTION_SECONDS,), ) return cur.rowcount