from .faults import inject from .broker import publish from opentelemetry.trace import SpanKind from .telemetry import PROPAGATOR, current_carrier, event, span class OutboxDispatcher: def __init__(self, repository, broker): self.repository = repository self.broker = broker def run(self): self.recover_expired() with self.repository.connection() as db: rows = db.execute( """SELECT j.*,o.payload,o.published_at AS previous_publish FROM processing_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version JOIN processing_outbox o ON o.job_id=j.job_id WHERE j.status='QUEUED' AND j.next_at<=now() AND j.next_publish_at<=now() ORDER BY j.created_at LIMIT 20 FOR UPDATE OF o SKIP LOCKED""" ).fetchall() for job in rows: self.publish(db, job) def publish(self, db, job): inject(self.repository, job, "before_publish") payload = dict(job["payload"], attempt=job["attempt"] + 1) with span( "attachments publish", SpanKind.PRODUCER, PROPAGATOR.extract(payload), {"messaging.destination.name": "attachments", "job.attempt": payload["attempt"]}, ): current_carrier(payload) created = publish(self.broker, self.repository.settings, payload) event("outbox.published", attempt=payload["attempt"], publication_created=created) inject(self.repository, job, "after_publish") db.execute( "UPDATE processing_jobs SET next_publish_at=now()+interval '10 seconds' WHERE job_id=%s", (job["job_id"],), ) db.execute( "UPDATE processing_outbox SET published_at=now(),publish_count=publish_count+1 WHERE job_id=%s", (job["job_id"],), ) if created or job["previous_publish"] is None: self.repository.event(db, dict(job, attempt=payload["attempt"]), "published") def recover_expired(self): with self.repository.connection() as db: rows = db.execute( """SELECT j.* FROM processing_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version WHERE j.status='PROCESSING' AND j.lease_until= job["attempt_limit"] code = "retry_exhausted" if terminal else "lease_expired" self.repository.set_failure(db, job, "FAILED" if terminal else "QUEUED", code, 1) self.repository.event(db, job, "lease_expired")