Files
mtusi2026lab5-Leskovskiy/src/jobs.py
T

119 lines
3.7 KiB
Python

"""Broker access: durable job publication and the transactional-outbox pump.
The broker message carries only identifiers and metadata (never bytes or
credentials). The job row in PostgreSQL is the source of truth; `published_at`
turns the row into a small transactional outbox so a crash between COMMIT and
publish is repaired by the background pump.
"""
import json
import logging
import threading
import time
import uuid
from datetime import datetime, timezone, timedelta
import pika
from sqlalchemy import select
from . import config
from .db import SessionLocal
from .models import AttachmentJob
log = logging.getLogger("jobs")
TYPE_V1 = "attachment.process.v1"
def build_payload(job: AttachmentJob, attempt: int) -> dict:
return {
"schema_version": 1,
"job_id": str(job.id),
"type": TYPE_V1,
"attachment_id": str(job.attachment_id),
"pipeline_version": job.pipeline_version,
"attempt": attempt,
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
}
def publish(payload: dict) -> None:
params = pika.URLParameters(config.BROKER_URL)
params.heartbeat = 30
params.blocked_connection_timeout = 30
connection = pika.BlockingConnection(params)
try:
channel = connection.channel()
channel.queue_declare(queue=config.QUEUE_NAME, durable=True)
channel.confirm_delivery()
channel.basic_publish(
exchange="",
routing_key=config.QUEUE_NAME,
body=json.dumps(payload).encode("utf-8"),
properties=pika.BasicProperties(
delivery_mode=2, # persistent
content_type="application/json",
message_id=payload["job_id"],
),
mandatory=True,
)
finally:
connection.close()
def publish_job_row(job_id: uuid.UUID, attempt: int) -> None:
with SessionLocal() as db:
job = db.get(AttachmentJob, job_id)
if not job or job.state in ("done", "failed"):
return
payload = build_payload(job, attempt)
publish(payload)
with SessionLocal() as db:
job = db.get(AttachmentJob, job_id)
if job:
job.published_at = datetime.now(timezone.utc)
db.commit()
def pump_once(limit: int = 50) -> int:
"""Publish queued rows whose outbox timestamp is still empty."""
now = datetime.now(timezone.utc)
cutoff = now - timedelta(seconds=config.OUTBOX_GRACE_SECONDS)
published = 0
with SessionLocal() as db:
rows = (
db.execute(
select(AttachmentJob)
.where(AttachmentJob.published_at.is_(None))
.where(AttachmentJob.state == "queued")
.where(AttachmentJob.created_at <= cutoff)
.order_by(AttachmentJob.created_at)
.limit(limit)
)
.scalars()
.all()
)
pending = [(job.id, job.attempt + 1) for job in rows]
for job_id, attempt in pending:
try:
publish_job_row(job_id, attempt)
published += 1
except Exception as exc: # broker may still be starting
log.warning("outbox publish failed for %s: %s", job_id, exc)
return published
def start_outbox_thread() -> threading.Thread:
def loop():
while True:
try:
count = pump_once()
if count:
log.info("outbox published %d job(s)", count)
except Exception as exc:
log.warning("outbox pump error: %s", exc)
time.sleep(config.OUTBOX_INTERVAL_SECONDS)
thread = threading.Thread(target=loop, name="outbox", daemon=True)
thread.start()
return thread