"""Transactional outbox publisher (runs inside the API process). The API writes an attachment AND its job row in one transaction. This tiny background thread moves pending rows to RabbitMQ with publisher confirms and only then marks ``published_at``. That closes the COMMIT -> publish gap: a crash between the two leaves the row unpublished and it is retried after restart. Transient processing errors are also scheduled here: the worker sets the row back to ``pending`` with a future ``available_at`` (backoff + jitter) and the publisher republishes it when due. """ from __future__ import annotations import logging import threading from typing import Optional from . import broker from . import repositories as repo from .config import settings from .db import pool logger = logging.getLogger("messenger.outbox") _stop = threading.Event() _thread: Optional[threading.Thread] = None def _publish_once() -> int: with pool().connection() as conn: jobs = repo.list_outbox_jobs(conn, 100) published = 0 for job in jobs: try: broker.publish(repo.job_message(job)) except Exception as exc: # noqa: BLE001 - broker may be down; retry later logger.warning("broker publish failed (%s); will retry", type(exc).__name__) break with pool().connection() as conn: repo.mark_job_published(conn, str(job["job_id"])) published += 1 if published: logger.info("outbox published %d job(s)", published) return published def _loop() -> None: while not _stop.is_set(): try: _publish_once() except Exception as exc: # noqa: BLE001 - never kill the publisher logger.warning("outbox drain failed: %s", type(exc).__name__) _stop.wait(settings.outbox_interval_seconds) def publish_now() -> None: """Best-effort immediate publish (called right after a 202 for latency).""" try: _publish_once() except Exception as exc: # noqa: BLE001 logger.warning("immediate outbox publish failed: %s", type(exc).__name__) def start_worker() -> None: global _thread if _thread is not None and _thread.is_alive(): return _stop.clear() _thread = threading.Thread(target=_loop, name="outbox-publisher", daemon=True) _thread.start() logger.info("outbox publisher started (interval=%.2fs)", settings.outbox_interval_seconds) def stop_worker() -> None: global _thread _stop.set() if _thread is not None: _thread.join(timeout=2) _thread = None