"""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 app import config 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.publisher.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 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: broker reachable, publishing") 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