"""Job rows are the transactional outbox. The broker never stores file bytes.""" from __future__ import annotations import asyncio import hashlib import logging import os import random from datetime import datetime, timezone from uuid import UUID, uuid4 from app import broker, config, db, pipeline, s3 from app.errors import AppError from app.pipeline import PermanentJobError, TransientJobError from app.store import format_ts logger = logging.getLogger("messenger.jobs") _outbox_task: asyncio.Task | None = None _publish_lock = asyncio.Lock() def message_of(row) -> dict: return { "schema_version": 1, "job_id": str(row["job_id"]), "type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]), "pipeline_version": int(row["pipeline_version"]), "attempt": int(row["attempt"]), "created_at": format_ts(row["created_at"]), } def backoff_seconds(attempt: int) -> float: base = min(config.JOB_BACKOFF_CAP_SECONDS, config.JOB_BACKOFF_BASE_SECONDS * (2 ** max(0, attempt - 1))) return base * random.uniform(0.5, 1.5) async def insert_job(conn, attachment_id: UUID, created: datetime) -> UUID: job_id = uuid4() await conn.execute( """ INSERT INTO attachment_jobs ( job_id, attachment_id, pipeline_version, attempt, status, next_attempt_at, created_at, updated_at ) VALUES ($1, $2, 1, 1, 'queued', $3, $3, $3) """, job_id, attachment_id, created, ) await conn.execute( """ INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail) VALUES ($1, $2, 'queued', 'upload committed') """, job_id, attachment_id, ) return job_id def kick_publish() -> None: try: asyncio.get_running_loop().create_task(publish_pending()) except RuntimeError: return async def publish_pending(limit: int = 20) -> int: if not config.BROKER_URL: return 0 async with _publish_lock: try: async with db.require().acquire() as conn: async with conn.transaction(): rows = await conn.fetch( """ SELECT job_id, attachment_id, pipeline_version, attempt, created_at FROM attachment_jobs WHERE published_at IS NULL AND status = 'queued' AND (next_attempt_at IS NULL OR next_attempt_at <= now()) ORDER BY created_at LIMIT $1 FOR UPDATE SKIP LOCKED """, limit, ) for row in rows: await broker.publish_job(message_of(row)) await conn.execute( "UPDATE attachment_jobs SET published_at = now() WHERE job_id = $1", row["job_id"], ) return len(rows) except Exception: logger.warning("outbox publish failed; the job row stays unpublished") return 0 async def _outbox_loop() -> None: while True: try: await publish_pending() except asyncio.CancelledError: raise except Exception: logger.warning("outbox loop failed") await asyncio.sleep(0.25) def start_outbox() -> None: global _outbox_task if _outbox_task is None or _outbox_task.done(): _outbox_task = asyncio.create_task(_outbox_loop()) async def stop_outbox() -> None: global _outbox_task task = _outbox_task _outbox_task = None if task is None: return task.cancel() try: await task except asyncio.CancelledError: pass await broker.close() def _aware(value: datetime | None) -> datetime | None: if value is None: return None if value.tzinfo is None: return value.replace(tzinfo=timezone.utc) return value async def claim(job_id: UUID, pipeline_version: int): token = uuid4() async with db.require().acquire() as conn: async with conn.transaction(): row = await conn.fetchrow( "SELECT * FROM attachment_jobs WHERE job_id = $1 FOR UPDATE", job_id, ) if row is None: return "missing", None if int(row["pipeline_version"]) != pipeline_version: return "stale", row if row["status"] == "ready": return "ready", row attachment = await conn.fetchrow( "SELECT status FROM attachments WHERE id = $1", row["attachment_id"], ) if attachment is not None and attachment["status"] == "ready": await conn.execute( """ UPDATE attachment_jobs SET status = 'ready', error_code = NULL, lease_token = NULL, lease_until = NULL, updated_at = now() WHERE job_id = $1 AND status <> 'ready' """, job_id, ) return "ready", row if row["status"] == "failed": return "failed", row lease = _aware(row["lease_until"]) if row["status"] == "processing" and lease is not None and lease > datetime.now(timezone.utc): return "busy", row if int(row["attempt"]) > config.JOB_MAX_ATTEMPTS: await _fail(conn, row, "retry_exhausted") return "failed", row await conn.execute( """ UPDATE attachment_jobs SET status = 'processing', lease_token = $2, lease_until = now() + ($3::int * interval '1 second'), error_code = NULL, updated_at = now() WHERE job_id = $1 """, job_id, token, config.JOB_LEASE_SECONDS, ) await conn.execute( """ UPDATE attachments SET status = 'processing', error_code = NULL, updated_at = now() WHERE id = $1 AND status <> 'ready' """, row["attachment_id"], ) claimed = dict(row) claimed["lease_token"] = token claimed["status"] = "processing" return "claimed", claimed async def _fail(conn, row, code: str) -> None: await conn.execute( """ UPDATE attachment_jobs SET status = 'failed', error_code = $2, lease_token = NULL, lease_until = NULL, updated_at = now() WHERE job_id = $1 AND status <> 'ready' """, row["job_id"], code, ) await conn.execute( """ UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now() WHERE id = $1 AND status <> 'ready' """, row["attachment_id"], code, ) await conn.execute( """ INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail) VALUES ($1, $2, 'failed', $3) """, row["job_id"], row["attachment_id"], code, ) async def fail_job(job_id: UUID, lease_token: UUID, code: str) -> bool: async with db.require().acquire() as conn: async with conn.transaction(): row = await conn.fetchrow( """ SELECT * FROM attachment_jobs WHERE job_id = $1 AND lease_token = $2 AND status = 'processing' FOR UPDATE """, job_id, lease_token, ) if row is None: return False await _fail(conn, row, code) failed = dict(row) try: await broker.publish_dlq(message_of(failed)) except Exception: logger.warning("failed job is stored; DLQ publish will be retried by an operator replay") return True async def schedule_retry(job_id: UUID, lease_token: UUID, code: str) -> str: async with db.require().acquire() as conn: async with conn.transaction(): row = await conn.fetchrow( """ SELECT * FROM attachment_jobs WHERE job_id = $1 AND lease_token = $2 AND status = 'processing' FOR UPDATE """, job_id, lease_token, ) if row is None: return "lost" nxt = int(row["attempt"]) + 1 if nxt > config.JOB_MAX_ATTEMPTS: await _fail(conn, row, "retry_exhausted") failed = True else: delay = backoff_seconds(int(row["attempt"])) await conn.execute( """ UPDATE attachment_jobs SET status = 'queued', attempt = $2, error_code = $3, lease_token = NULL, lease_until = NULL, published_at = NULL, next_attempt_at = now() + ($4::double precision * interval '1 second'), updated_at = now() WHERE job_id = $1 """, job_id, nxt, code, delay, ) await conn.execute( """ UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1 AND status <> 'ready' """, row["attachment_id"], ) await conn.execute( """ INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail) VALUES ($1, $2, 'retry', $3) """, job_id, row["attachment_id"], code, ) failed = False failed_row = None if failed: failed_row = row if failed: try: await broker.publish_dlq(message_of(failed_row)) except Exception: logger.warning("retry exhausted; DLQ publish failed") return "failed" return "retry" async def _intent(key: str) -> None: async with db.require().acquire() as conn: await conn.execute( """ INSERT INTO blob_writes (object_key, committed) VALUES ($1, FALSE) ON CONFLICT (object_key) DO NOTHING """, key, ) async def complete_job(job_id: UUID, lease_token: UUID, attachment_id: UUID, final_key: str, variants: list) -> bool: async with db.require().acquire() as conn: async with conn.transaction(): owned = await conn.fetchval( """ UPDATE attachment_jobs SET status = 'ready', error_code = NULL, lease_token = NULL, lease_until = NULL, updated_at = now() WHERE job_id = $1 AND lease_token = $2 AND status = 'processing' RETURNING job_id """, job_id, lease_token, ) if owned is None: return False current = await conn.fetchrow( "SELECT status FROM attachments WHERE id = $1 FOR UPDATE", attachment_id, ) if current is None: raise PermanentJobError("invalid_image") if current["status"] != "ready": await conn.execute( """ UPDATE attachments SET status = 'ready', object_key = $2, error_code = NULL, updated_at = now() WHERE id = $1 AND status <> 'ready' """, attachment_id, final_key, ) for variant in variants: await conn.execute( """ INSERT INTO attachment_variants ( attachment_id, pipeline_version, name, content_type, size_bytes, width, height, sha256, object_key ) VALUES ($1, 1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING """, attachment_id, variant["name"], variant["content_type"], variant["size_bytes"], variant["width"], variant["height"], variant["sha256"], variant["object_key"], ) await conn.execute( "UPDATE blob_writes SET committed = TRUE WHERE object_key = $1", variant["object_key"], ) await conn.execute( "UPDATE blob_writes SET committed = TRUE WHERE object_key = $1", final_key, ) await conn.execute( """ INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail) VALUES ($1, $2, 'ready', 'variants committed') """, job_id, attachment_id, ) return True async def load_attachment(attachment_id: UUID): async with db.require().acquire() as conn: return await conn.fetchrow( """ SELECT id, filename, content_type, size_bytes, sha256, object_key, status FROM attachments WHERE id = $1 """, attachment_id, ) async def process(job_id: UUID, pipeline_version: int) -> str: state, row = await claim(job_id, pipeline_version) if state != "claimed": return state assert row is not None lease = row["lease_token"] try: await asyncio.wait_for(_effect(row, lease), config.JOB_TIMEOUT_SECONDS) except PermanentJobError as exc: await fail_job(job_id, lease, exc.code) return "failed" except (TransientJobError, asyncio.TimeoutError, AppError): return await schedule_retry(job_id, lease, "processing_failed") except Exception: logger.warning("job processing failed job_id=%s", job_id) return await schedule_retry(job_id, lease, "processing_failed") return "ready" async def _effect(row, lease: UUID) -> None: attachment = await load_attachment(row["attachment_id"]) if attachment is None: raise PermanentJobError("invalid_image") if attachment["status"] == "ready": committed = await complete_job(row["job_id"], lease, attachment["id"], attachment["object_key"], []) if not committed: raise TransientJobError("processing_failed") return data = await s3.get_bytes(attachment["object_key"]) if len(data) != attachment["size_bytes"] or hashlib.sha256(data).hexdigest() != attachment["sha256"]: raise PermanentJobError("invalid_image") final_key = f"originals/{attachment['id']}" if attachment["object_key"] != final_key: await _intent(final_key) await s3.put_bytes(final_key, data, attachment["content_type"]) rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"]) stored = [] for name, (payload, content_type, width, height) in rendered.items(): suffix = "webp" if content_type == "image/webp" else "jpg" key = f"variants/{attachment['id']}/{name}.{suffix}" await _intent(key) await s3.put_bytes(key, payload, content_type) stored.append( { "name": name, "content_type": content_type, "size_bytes": len(payload), "width": width, "height": height, "sha256": hashlib.sha256(payload).hexdigest(), "object_key": key, } ) if config.WORKER_CRASH_POINT == "after_s3": logger.warning("injected crash after object write before result commit job_id=%s", row["job_id"]) os._exit(1) committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored) if not committed: raise TransientJobError("processing_failed") if attachment["object_key"] != final_key: try: await s3.delete_key(attachment["object_key"]) async with db.require().acquire() as conn: await conn.execute("DELETE FROM blob_writes WHERE object_key = $1", attachment["object_key"]) except Exception: logger.warning("staging object left for retention attachment_id=%s", attachment["id"]) async def replay_attachment(attachment_id: str) -> dict: async with db.require().acquire() as conn: job_id = await conn.fetchval( """ SELECT job_id FROM attachment_jobs WHERE attachment_id = $1 AND pipeline_version = 1 """, UUID(attachment_id), ) if job_id is None: return {"result": "missing"} return await replay(job_id) async def replay(job_id: UUID) -> dict: async with db.require().acquire() as conn: async with conn.transaction(): row = await conn.fetchrow( "SELECT * FROM attachment_jobs WHERE job_id = $1 FOR UPDATE", job_id, ) if row is None: return {"result": "missing"} if row["status"] == "ready": await conn.execute( """ INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail) VALUES ($1, $2, 'replay', 'noop ready') """, row["job_id"], row["attachment_id"], ) return {"result": "noop", "job_id": str(row["job_id"])} lease = _aware(row["lease_until"]) if row["status"] == "processing" and lease is not None and lease > datetime.now(timezone.utc): return {"result": "busy", "job_id": str(row["job_id"])} await conn.execute( """ UPDATE attachment_jobs SET status = 'queued', attempt = 1, error_code = NULL, lease_token = NULL, lease_until = NULL, published_at = NULL, next_attempt_at = now(), updated_at = now() WHERE job_id = $1 AND status <> 'ready' """, job_id, ) await conn.execute( """ UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1 AND status <> 'ready' """, row["attachment_id"], ) await conn.execute( """ INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail) VALUES ($1, $2, 'replay', 'operator replay') """, row["job_id"], row["attachment_id"], ) await publish_pending() return {"result": "queued", "job_id": str(job_id)} async def reap_expired() -> int: async with db.require().acquire() as conn: async with conn.transaction(): rows = await conn.fetch( """ SELECT job_id, attachment_id, attempt FROM attachment_jobs WHERE status = 'processing' AND lease_until < now() FOR UPDATE SKIP LOCKED """ ) changed = 0 for row in rows: nxt = int(row["attempt"]) + 1 if nxt > config.JOB_MAX_ATTEMPTS: await conn.execute( """ UPDATE attachment_jobs SET status = 'failed', error_code = 'retry_exhausted', lease_token = NULL, lease_until = NULL, updated_at = now() WHERE job_id = $1 AND status = 'processing' """, row["job_id"], ) await conn.execute( """ UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted', updated_at = now() WHERE id = $1 AND status <> 'ready' """, row["attachment_id"], ) else: await conn.execute( """ UPDATE attachment_jobs SET status = 'queued', attempt = $2, error_code = 'lease_expired', lease_token = NULL, lease_until = NULL, published_at = NULL, next_attempt_at = now(), updated_at = now() WHERE job_id = $1 AND status = 'processing' """, row["job_id"], nxt, ) await conn.execute( """ UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1 AND status <> 'ready' """, row["attachment_id"], ) changed += 1 return changed