"""Задания обработки, lease, outbox, варианты и операторский replay. Модуль содержит SQL/транзакционные границы асинхронного pipeline. API использует `insert_upload_work` в своей транзакции, а worker/relay/admin — `JobRepository` с отдельной сессией на операцию. Метаданные PostgreSQL — источник истины; брокер лишь доставляет ссылки на job. """ from __future__ import annotations import random from dataclasses import dataclass from datetime import datetime from typing import Sequence from uuid import UUID, uuid4 from sqlalchemy import func, insert, select, text, update from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from .config import Config from .db import Database from .domain import AttachmentRecord, VariantRecord, utc_now from .pipeline import GeneratedVariant from .schema import ( ATTACHMENTS, JOBS, JOB_EVENTS, JOB_REPLAYS, OUTBOX, VARIANTS, FAULT_FLAGS, ) TERMINAL_JOB_STATES = ("ready", "failed", "superseded") JOB_TYPE = "attachment.process.v1" FAULT_KINDS = ( "crash_before_objects", "crash_after_objects", "transient_once", "permanent_once", "stuck_before_commit", "transient_always", ) class ReplayRejected(RuntimeError): """Явный replay невозможен: задача не failed или результат уже новее.""" @dataclass(frozen=True) class JobRecord: id: UUID attachment_id: UUID pipeline_version: int type: str state: str attempts: int max_attempts: int lease_token: UUID | None worker_id: str | None lease_expires_at: datetime | None next_attempt_at: datetime | None last_error_code: str | None replay_of: UUID | None created_at: datetime updated_at: datetime finished_at: datetime | None @dataclass(frozen=True) class Claim: granted: bool reason: str job: JobRecord | None = None attachment: AttachmentRecord | None = None lease_token: UUID | None = None @dataclass(frozen=True) class OutboxItem: outbox_id: int job: JobRecord attachment: AttachmentRecord def _interval(seconds: float): """Интервал PostgreSQL от текущего времени; значение — число из конфигурации.""" return text(f"INTERVAL '{float(seconds)} seconds'") def _job_record(row) -> JobRecord: return JobRecord( id=row.id, attachment_id=row.attachment_id, pipeline_version=row.pipeline_version, type=row.type, state=row.state, attempts=row.attempts, max_attempts=row.max_attempts, lease_token=row.lease_token, worker_id=row.worker_id, lease_expires_at=row.lease_expires_at, next_attempt_at=row.next_attempt_at, last_error_code=row.last_error_code, replay_of=row.replay_of, created_at=row.created_at, updated_at=row.updated_at, finished_at=row.finished_at, ) def _variant_record(row) -> VariantRecord: return VariantRecord( attachment_id=row.attachment_id, pipeline_version=row.pipeline_version, name=row.name, content_type=row.content_type, object_key=row.object_key, size_bytes=row.size_bytes, sha256=row.sha256, width=row.width, height=row.height, created_at=row.created_at, ) def _attachment_record(row, variants: Sequence[VariantRecord] = ()) -> AttachmentRecord: return AttachmentRecord( id=row.id, chat_id=row.chat_id, owner_id=row.owner_id, object_key=row.object_key, staging_key=row.staging_key, pipeline_version=row.pipeline_version, filename=row.filename, content_type=row.content_type, size_bytes=row.size_bytes, sha256=row.sha256, status=row.status, error_code=row.error_code, ready_at=row.ready_at, created_at=row.created_at, updated_at=row.updated_at, variants=tuple(variants), ) async def _variants_of( session: AsyncSession, attachment_id: UUID, pipeline_version: int ) -> list[VariantRecord]: if pipeline_version <= 0: return [] rows = ( await session.execute( select(VARIANTS) .where( VARIANTS.c.attachment_id == attachment_id, VARIANTS.c.pipeline_version == pipeline_version, ) .order_by(VARIANTS.c.name) ) ).all() return [_variant_record(row) for row in rows] async def insert_upload_work( session: AsyncSession, *, attachment_id: UUID, chat_id: UUID, owner_id: UUID, staging_key: str, object_key: str, filename: str, content_type: str, size_bytes: int, sha256: str, pipeline_version: int, max_attempts: int, ) -> None: """Одна транзакция: queued-вложение + job + outbox-строка. Вызывается из upload-запроса до COMMIT. После успешного COMMIT API имеет право ответить 202: и байты (staging), и намерение обработки устойчивы. """ await session.execute( ATTACHMENTS.insert().values( id=attachment_id, chat_id=chat_id, owner_id=owner_id, object_key=object_key, staging_key=staging_key, pipeline_version=0, filename=filename, content_type=content_type, size_bytes=size_bytes, sha256=sha256, status="queued", ) ) job_id = uuid4() await session.execute( JOBS.insert().values( id=job_id, attachment_id=attachment_id, pipeline_version=pipeline_version, type=JOB_TYPE, state="queued", attempts=0, max_attempts=max_attempts, ) ) await session.execute(OUTBOX.insert().values(job_id=job_id, available_at=func.now())) await session.execute( JOB_EVENTS.insert().values( job_id=job_id, from_state=None, to_state="queued", attempt=0, detail="upload_accepted", ) ) class JobRepository: """Транзакционные операции над jobs/outbox/variants.""" def __init__(self, database: Database, config: Config) -> None: self._db = database self._config = config # --- чтение ----------------------------------------------------------- async def get_job(self, job_id: UUID) -> JobRecord | None: async with self._db.session() as session: row = ( await session.execute(select(JOBS).where(JOBS.c.id == job_id).limit(1)) ).first() return None if row is None else _job_record(row) async def get_attachment(self, attachment_id: UUID) -> AttachmentRecord | None: async with self._db.session() as session: row = ( await session.execute( select(ATTACHMENTS).where(ATTACHMENTS.c.id == attachment_id).limit(1) ) ).first() if row is None: return None return _attachment_record( row, await _variants_of(session, attachment_id, row.pipeline_version) ) async def has_other_active_jobs(self, attachment_id: UUID, exclude_job_id: UUID) -> bool: """Есть ли ещё queued/processing job того же вложения (другая версия/attempt).""" async with self._db.session() as session: found = await session.scalar( select(JOBS.c.id) .where( JOBS.c.attachment_id == attachment_id, JOBS.c.id != exclude_job_id, JOBS.c.state.in_(("queued", "processing")), ) .limit(1) ) return found is not None async def jobs_for_attachment(self, attachment_id: UUID) -> list[JobRecord]: async with self._db.session() as session: rows = ( await session.execute( select(JOBS) .where(JOBS.c.attachment_id == attachment_id) .order_by(JOBS.c.created_at, JOBS.c.id) ) ).all() return [_job_record(row) for row in rows] # --- worker ----------------------------------------------------------- async def claim( self, job_id: UUID, *, worker_id: str, lease_seconds: float ) -> Claim: """Захватывает job под lease. Повторная доставка не создаёт второй эффект.""" async with self._db.session() as session: async with session.begin(): row = ( await session.execute( select(JOBS).where(JOBS.c.id == job_id).with_for_update() ) ).first() if row is None: return Claim(False, "missing") job = _job_record(row) db_now = await session.scalar(select(func.now())) if job.state in TERMINAL_JOB_STATES: return Claim(False, job.state, job=job) attachment_row = ( await session.execute( select(ATTACHMENTS) .where(ATTACHMENTS.c.id == job.attachment_id) .with_for_update() ) ).first() if attachment_row is None: return Claim(False, "missing_attachment", job=job) attachment = _attachment_record(attachment_row) if attachment.pipeline_version > job.pipeline_version: await self._supersede(session, job, "newer_pipeline_ready") return Claim(False, "superseded", job=job) if ( job.state == "processing" and job.lease_expires_at is not None and job.lease_expires_at >= db_now ): return Claim(False, "busy", job=job) if job.attempts >= job.max_attempts: await self._fail_locked( session, job, attachment, error_code="retry_exhausted", permanent=True, detail="attempts_exhausted_on_claim", ) return Claim(False, "exhausted", job=job) attempt = job.attempts + 1 token = uuid4() await session.execute( update(JOBS) .where(JOBS.c.id == job.id) .values( state="processing", attempts=attempt, lease_token=token, worker_id=worker_id, lease_expires_at=func.now() + _interval(lease_seconds), next_attempt_at=None, updated_at=func.now(), ) ) if ( attachment.pipeline_version <= job.pipeline_version and attachment.status in ("queued", "processing") ): await session.execute( update(ATTACHMENTS) .where(ATTACHMENTS.c.id == attachment.id) .values(status="processing", error_code=None, updated_at=func.now()) ) await session.execute( insert(JOB_EVENTS).values( job_id=job.id, from_state=job.state, to_state="processing", attempt=attempt, worker_id=worker_id, detail="lease_acquired", ) ) claimed = _job_record( ( await session.execute( select(JOBS).where(JOBS.c.id == job.id) ) ).first() ) return Claim( True, "claimed", job=claimed, attachment=attachment, lease_token=token, ) async def extend_lease(self, job_id: UUID, lease_token: UUID, lease_seconds: float) -> bool: async with self._db.session() as session: result = await session.execute( update(JOBS) .where( JOBS.c.id == job_id, JOBS.c.lease_token == lease_token, JOBS.c.state == "processing", ) .values(lease_expires_at=func.now() + _interval(lease_seconds)) ) await session.commit() return bool(result.rowcount) async def complete( self, *, job_id: UUID, lease_token: UUID, worker_id: str, original_key: str, variants: Sequence[GeneratedVariant], variant_keys: dict[str, str], ) -> str: """Атомарно публикует результат. Гард версии не даёт старой job перезаписать новую.""" async with self._db.session() as session: async with session.begin(): row = ( await session.execute( select(JOBS).where(JOBS.c.id == job_id).with_for_update() ) ).first() if row is None: return "missing" job = _job_record(row) if job.state != "processing" or job.lease_token != lease_token: return "lease_lost" attachment_row = ( await session.execute( select(ATTACHMENTS) .where(ATTACHMENTS.c.id == job.attachment_id) .with_for_update() ) ).first() if attachment_row is None: return "missing_attachment" attachment = _attachment_record(attachment_row) if attachment.pipeline_version > job.pipeline_version: await self._supersede(session, job, "newer_pipeline_ready") return "superseded" for variant in variants: object_key = variant_keys.get(variant.name) if not object_key: raise ValueError("variant object key is required") await session.execute( pg_insert(VARIANTS) .values( attachment_id=job.attachment_id, pipeline_version=job.pipeline_version, name=variant.name, content_type=variant.content_type, object_key=object_key, size_bytes=variant.size_bytes, sha256=variant.sha256, width=variant.width, height=variant.height, ) .on_conflict_do_update( index_elements=[ VARIANTS.c.attachment_id, VARIANTS.c.pipeline_version, VARIANTS.c.name, ], set_={ "content_type": variant.content_type, "object_key": object_key, "size_bytes": variant.size_bytes, "sha256": variant.sha256, "width": variant.width, "height": variant.height, }, ) ) await session.execute( update(ATTACHMENTS) .where(ATTACHMENTS.c.id == job.attachment_id) .values( status="ready", pipeline_version=job.pipeline_version, object_key=original_key, ready_at=func.now(), error_code=None, updated_at=func.now(), ) ) await session.execute( update(JOBS) .where(JOBS.c.id == job.id) .values( state="ready", lease_token=None, lease_expires_at=None, next_attempt_at=None, updated_at=func.now(), finished_at=func.now(), ) ) await session.execute( insert(JOB_EVENTS).values( job_id=job.id, from_state="processing", to_state="ready", attempt=job.attempts, worker_id=worker_id, detail="effect_committed", ) ) return "ready" async def fail( self, *, job_id: UUID, lease_token: UUID, worker_id: str, error_code: str, permanent: bool, ) -> str: async with self._db.session() as session: async with session.begin(): row = ( await session.execute( select(JOBS).where(JOBS.c.id == job_id).with_for_update() ) ).first() if row is None: return "missing" job = _job_record(row) if job.state != "processing" or job.lease_token != lease_token: return "lease_lost" attachment_row = ( await session.execute( select(ATTACHMENTS) .where(ATTACHMENTS.c.id == job.attachment_id) .with_for_update() ) ).first() if attachment_row is None: return "missing_attachment" attachment = _attachment_record(attachment_row) if attachment.pipeline_version > job.pipeline_version: await self._supersede(session, job, "newer_pipeline_ready") return "superseded" return await self._fail_locked( session, job, attachment, error_code=error_code, permanent=permanent, worker_id=worker_id, detail="worker_reported_failure", ) async def _fail_locked( self, session: AsyncSession, job: JobRecord, attachment: AttachmentRecord, *, error_code: str, permanent: bool, worker_id: str | None = None, detail: str, ) -> str: terminal = permanent or job.attempts >= job.max_attempts code = "retry_exhausted" if (not permanent and terminal) else error_code if terminal: await session.execute( update(JOBS) .where(JOBS.c.id == job.id) .values( state="failed", lease_token=None, lease_expires_at=None, last_error_code=code, updated_at=func.now(), finished_at=func.now(), ) ) # Готовый результат более новой/этой версии не откатываем. if attachment.pipeline_version <= job.pipeline_version and attachment.status != "ready": await session.execute( update(ATTACHMENTS) .where(ATTACHMENTS.c.id == attachment.id) .values(status="failed", error_code=code, updated_at=func.now()) ) await session.execute( insert(JOB_EVENTS).values( job_id=job.id, from_state=job.state, to_state="failed", attempt=job.attempts, error_code=code, worker_id=worker_id, detail=detail, ) ) return "failed" backoff = self._backoff_seconds(job.attempts) next_at = func.now() + _interval(backoff) await session.execute( update(JOBS) .where(JOBS.c.id == job.id) .values( state="queued", lease_token=None, lease_expires_at=None, next_attempt_at=next_at, last_error_code=code, updated_at=func.now(), ) ) await session.execute( pg_insert(OUTBOX) .values(job_id=job.id, available_at=next_at) .on_conflict_do_nothing() ) if attachment.pipeline_version <= job.pipeline_version: await session.execute( update(ATTACHMENTS) .where(ATTACHMENTS.c.id == attachment.id) .values(status="queued", error_code=None, updated_at=func.now()) ) await session.execute( insert(JOB_EVENTS).values( job_id=job.id, from_state=job.state, to_state="queued", attempt=job.attempts, error_code=code, worker_id=worker_id, detail=f"{detail}; retry_in={backoff:.2f}s", ) ) return "retry" def _backoff_seconds(self, attempts: int) -> float: base = self._config.job_backoff_base_seconds cap = self._config.job_backoff_max_seconds raw = min(cap, base * (2 ** max(0, attempts - 1))) # Jitter ±20%: несколько worker-ов не просыпаются одновременно. return max(0.05, raw * random.uniform(0.8, 1.2)) async def _supersede(self, session: AsyncSession, job: JobRecord, detail: str) -> None: await session.execute( update(JOBS) .where(JOBS.c.id == job.id) .values( state="superseded", lease_token=None, lease_expires_at=None, updated_at=func.now(), finished_at=func.now(), ) ) await session.execute( insert(JOB_EVENTS).values( job_id=job.id, from_state=job.state, to_state="superseded", attempt=job.attempts, detail=detail, ) ) async def reap_expired(self, limit: int = 50) -> int: """Возвращает в очередь processing с истёкшим lease; считает такие job.""" async with self._db.session() as session: ids = ( await session.execute( select(JOBS.c.id) .where( JOBS.c.state == "processing", JOBS.c.lease_expires_at.is_not(None), JOBS.c.lease_expires_at < func.now(), ) .order_by(JOBS.c.lease_expires_at) .limit(limit) ) ).scalars().all() recovered = 0 for job_id in ids: async with self._db.session() as session: async with session.begin(): row = ( await session.execute( select(JOBS).where(JOBS.c.id == job_id).with_for_update() ) ).first() if row is None: continue job = _job_record(row) db_now = await session.scalar(select(func.now())) if ( job.state != "processing" or job.lease_expires_at is None or job.lease_expires_at >= db_now ): continue attachment_row = ( await session.execute( select(ATTACHMENTS) .where(ATTACHMENTS.c.id == job.attachment_id) .with_for_update() ) ).first() if attachment_row is None: continue attachment = _attachment_record(attachment_row) if attachment.pipeline_version > job.pipeline_version: await self._supersede(session, job, "newer_pipeline_ready") continue if job.attempts >= job.max_attempts: await self._fail_locked( session, job, attachment, error_code="retry_exhausted", permanent=True, detail="lease_expired_after_last_attempt", ) else: await session.execute( update(JOBS) .where(JOBS.c.id == job.id) .values( state="queued", lease_token=None, lease_expires_at=None, next_attempt_at=func.now(), last_error_code="lease_expired", updated_at=func.now(), ) ) await session.execute( pg_insert(OUTBOX) .values(job_id=job.id, available_at=func.now()) .on_conflict_do_nothing() ) await session.execute( update(ATTACHMENTS) .where(ATTACHMENTS.c.id == attachment.id) .values(status="queued", updated_at=func.now()) ) await session.execute( insert(JOB_EVENTS).values( job_id=job.id, from_state="processing", to_state="queued", attempt=job.attempts, error_code="lease_expired", detail="reaper_requeued", ) ) recovered += 1 return recovered # --- outbox relay ----------------------------------------------------- async def outbox_due(self, limit: int = 20) -> list[OutboxItem]: async with self._db.session() as session: rows = ( await session.execute( select( OUTBOX.c.id.label("outbox_id"), JOBS.c.id.label("job_id"), JOBS.c.attachment_id, JOBS.c.pipeline_version, JOBS.c.type, JOBS.c.state, JOBS.c.attempts, JOBS.c.max_attempts, JOBS.c.lease_token, JOBS.c.worker_id, JOBS.c.lease_expires_at, JOBS.c.next_attempt_at, JOBS.c.last_error_code, JOBS.c.replay_of, JOBS.c.created_at, JOBS.c.updated_at, JOBS.c.finished_at, ) .select_from(OUTBOX.join(JOBS, JOBS.c.id == OUTBOX.c.job_id)) .where( OUTBOX.c.published_at.is_(None), OUTBOX.c.available_at <= func.now(), ) .order_by(OUTBOX.c.available_at, OUTBOX.c.id) .limit(limit) ) ).all() items: list[OutboxItem] = [] for row in rows: mapping = row._mapping job = JobRecord( id=mapping["job_id"], attachment_id=mapping["attachment_id"], pipeline_version=mapping["pipeline_version"], type=mapping["type"], state=mapping["state"], attempts=mapping["attempts"], max_attempts=mapping["max_attempts"], lease_token=mapping["lease_token"], worker_id=mapping["worker_id"], lease_expires_at=mapping["lease_expires_at"], next_attempt_at=mapping["next_attempt_at"], last_error_code=mapping["last_error_code"], replay_of=mapping["replay_of"], created_at=mapping["created_at"], updated_at=mapping["updated_at"], finished_at=mapping["finished_at"], ) attachment_row = ( await session.execute( select(ATTACHMENTS).where(ATTACHMENTS.c.id == job.attachment_id) ) ).first() if attachment_row is None: continue attachment = _attachment_record(attachment_row) items.append( OutboxItem( outbox_id=int(mapping["outbox_id"]), job=job, attachment=attachment, ) ) return items async def mark_published(self, outbox_id: int) -> None: async with self._db.session() as session: await session.execute( update(OUTBOX) .where(OUTBOX.c.id == outbox_id, OUTBOX.c.published_at.is_(None)) .values( published_at=func.now(), attempts=OUTBOX.c.attempts + 1, last_error=None, ) ) await session.commit() async def mark_publish_failed(self, outbox_id: int, error: str) -> None: async with self._db.session() as session: await session.execute( update(OUTBOX) .where(OUTBOX.c.id == outbox_id, OUTBOX.c.published_at.is_(None)) .values(attempts=OUTBOX.c.attempts + 1, last_error=error[:200]) ) await session.commit() # --- operator --------------------------------------------------------- async def replay( self, *, job_id: UUID | None, attachment_id: UUID | None, requested_by: str, reason: str, ) -> UUID: """Явный replay только failed-задачи; создаёт новый job_id и outbox-строку.""" if not requested_by.strip() or len(requested_by) > 128: raise ReplayRejected("requested_by must contain 1..128 characters") if not reason.strip() or len(reason) > 512: raise ReplayRejected("reason must contain 1..512 characters") async with self._db.session() as session: async with session.begin(): if job_id is not None: row = ( await session.execute( select(JOBS).where(JOBS.c.id == job_id).with_for_update() ) ).first() else: row = ( await session.execute( select(JOBS) .where( JOBS.c.attachment_id == attachment_id, JOBS.c.state == "failed", ) .order_by(JOBS.c.created_at.desc()) .limit(1) .with_for_update() ) ).first() if row is None: raise ReplayRejected("failed job not found") source = _job_record(row) if source.state != "failed": raise ReplayRejected("only failed jobs can be replayed") attachment_row = ( await session.execute( select(ATTACHMENTS) .where(ATTACHMENTS.c.id == source.attachment_id) .with_for_update() ) ).first() if attachment_row is None: raise ReplayRejected("attachment not found") if attachment_row.status == "ready": # Успешный эффект уже существует: replay не должен создавать дубль. raise ReplayRejected("attachment already has a ready result") if attachment_row.pipeline_version > source.pipeline_version: raise ReplayRejected("a newer pipeline result already exists") inflight = ( await session.execute( select(JOBS.c.id) .where( JOBS.c.attachment_id == source.attachment_id, JOBS.c.state.in_(("queued", "processing")), ) .limit(1) ) ).first() if inflight is not None: raise ReplayRejected("another job is already queued or processing") new_id = uuid4() await session.execute( insert(JOBS).values( id=new_id, attachment_id=source.attachment_id, pipeline_version=source.pipeline_version, type=JOB_TYPE, state="queued", attempts=0, max_attempts=source.max_attempts, replay_of=source.id, ) ) await session.execute( update(ATTACHMENTS) .where(ATTACHMENTS.c.id == source.attachment_id) .values(status="queued", error_code=None, updated_at=func.now()) ) await session.execute( insert(OUTBOX).values(job_id=new_id, available_at=func.now()) ) await session.execute( insert(JOB_REPLAYS).values( id=uuid4(), source_job_id=source.id, replay_job_id=new_id, requested_by=requested_by.strip(), reason=reason.strip(), ) ) await session.execute( insert(JOB_EVENTS).values( job_id=new_id, from_state=None, to_state="queued", attempt=0, detail=f"operator_replay_of={source.id}", ) ) return new_id async def force_enqueue(self, attachment_id: UUID, pipeline_version: int) -> UUID: """Тестовый/операторский enqueue конкретной версии (для fault-трека).""" async with self._db.session() as session: async with session.begin(): attachment_row = ( await session.execute( select(ATTACHMENTS) .where(ATTACHMENTS.c.id == attachment_id) .with_for_update() ) ).first() if attachment_row is None: raise ReplayRejected("attachment not found") job_id = uuid4() try: await session.execute( insert(JOBS).values( id=job_id, attachment_id=attachment_id, pipeline_version=pipeline_version, type=JOB_TYPE, state="queued", attempts=0, max_attempts=self._config.job_max_attempts, ) ) except IntegrityError: raise ReplayRejected("initial job for this version already exists") from None await session.execute( insert(OUTBOX).values(job_id=job_id, available_at=func.now()) ) await session.execute( insert(JOB_EVENTS).values( job_id=job_id, from_state=None, to_state="queued", attempt=0, detail="operator_force_enqueue", ) ) return job_id async def set_fault(self, kind: str, count: int) -> None: if kind not in FAULT_KINDS: raise ValueError("unknown fault kind") if count < 0: raise ValueError("count must be >= 0") async with self._db.session() as session: await session.execute( pg_insert(FAULT_FLAGS) .values(kind=kind, remaining=count, updated_at=func.now()) .on_conflict_do_update( index_elements=[FAULT_FLAGS.c.kind], set_={"remaining": count, "updated_at": func.now()}, ) ) await session.commit() async def consume_fault(self) -> str | None: if not self._config.allow_fault_injection: return None async with self._db.session() as session: async with session.begin(): row = ( await session.execute( select(FAULT_FLAGS) .where( FAULT_FLAGS.c.kind.in_(FAULT_KINDS), FAULT_FLAGS.c.remaining > 0, ) .order_by(FAULT_FLAGS.c.kind) .limit(1) .with_for_update(skip_locked=True) ) ).first() if row is None: return None await session.execute( update(FAULT_FLAGS) .where(FAULT_FLAGS.c.kind == row.kind) .values(remaining=FAULT_FLAGS.c.remaining - 1, updated_at=func.now()) ) return row.kind async def report(self, attachment_id: UUID) -> dict: """Снимок состояния для evidence и оператора (без секретов).""" attachment = await self.get_attachment(attachment_id) jobs = await self.jobs_for_attachment(attachment_id) async with self._db.session() as session: outbox_rows = ( await session.execute( select(OUTBOX) .where(OUTBOX.c.job_id.in_([job.id for job in jobs])) .order_by(OUTBOX.c.id) ) ).all() event_rows = ( await session.execute( select(JOB_EVENTS) .where(JOB_EVENTS.c.job_id.in_([job.id for job in jobs])) .order_by(JOB_EVENTS.c.id) ) ).all() def moment(value): return None if value is None else value.isoformat().replace("+00:00", "Z") return { "attachment": None if attachment is None else { "id": str(attachment.id), "status": attachment.status, "error_code": attachment.error_code, "pipeline_version": attachment.pipeline_version, "object_key": attachment.object_key, "staging_key": attachment.staging_key, "size_bytes": attachment.size_bytes, "sha256": attachment.sha256, "ready_at": moment(attachment.ready_at), "updated_at": moment(attachment.updated_at), "variants": [ { "name": item.name, "pipeline_version": item.pipeline_version, "content_type": item.content_type, "object_key": item.object_key, "size_bytes": item.size_bytes, "sha256": item.sha256, "width": item.width, "height": item.height, } for item in attachment.variants ], }, "jobs": [ { "id": str(job.id), "pipeline_version": job.pipeline_version, "state": job.state, "attempts": job.attempts, "max_attempts": job.max_attempts, "lease_token": str(job.lease_token) if job.lease_token else None, "worker_id": job.worker_id, "last_error_code": job.last_error_code, "replay_of": str(job.replay_of) if job.replay_of else None, "created_at": moment(job.created_at), "updated_at": moment(job.updated_at), "finished_at": moment(job.finished_at), } for job in jobs ], "outbox": [ { "id": row.id, "job_id": str(row.job_id), "available_at": moment(row.available_at), "published_at": moment(row.published_at), "attempts": row.attempts, "last_error": row.last_error, } for row in outbox_rows ], "events": [ { "job_id": str(row.job_id), "from_state": row.from_state, "to_state": row.to_state, "attempt": row.attempt, "error_code": row.error_code, "worker_id": row.worker_id, "detail": row.detail, "created_at": moment(row.created_at), } for row in event_rows ], } async def queue_stats(self) -> dict: async with self._db.session() as session: job_rows = ( await session.execute( select(JOBS.c.state, func.count()).group_by(JOBS.c.state) ) ).all() outbox_pending = await session.scalar( select(func.count()).select_from(OUTBOX).where(OUTBOX.c.published_at.is_(None)) ) oldest = await session.scalar( select(func.min(JOBS.c.created_at)).where(JOBS.c.state == "queued") ) return { "jobs_by_state": {row[0]: int(row[1]) for row in job_rows}, "outbox_pending": int(outbox_pending or 0), "oldest_queued_at": None if oldest is None else oldest.isoformat().replace("+00:00", "Z"), }