Files
mtusi2026lab5/app/jobs.py

104 lines
4.5 KiB
Python

"""Job state machine in PostgreSQL (source of truth). The broker only wakes workers up.
Every state change that needs a message writes an outbox row in the SAME transaction (transactional outbox),
so there is no window where a job is queued in the DB without a pending publication.
"""
from __future__ import annotations
import json
import random
import uuid
from typing import Optional
import asyncpg
from app import config
from app.broker import job_payload
def backoff_seconds(attempt: int) -> float:
"""Exponential backoff with 'equal jitter': half fixed, half random. attempt = failed attempt number (1..)."""
ceiling = min(config.RETRY_MAX_SECONDS, config.RETRY_BASE_SECONDS * (2 ** max(0, attempt - 1)))
return ceiling / 2 + random.uniform(0, ceiling / 2)
async def event(conn: asyncpg.Connection, job_id: Optional[uuid.UUID], attachment_id: Optional[uuid.UUID],
name: str, actor: str, attempt: Optional[int] = None, detail: Optional[str] = None) -> None:
await conn.execute(
"INSERT INTO job_events (job_id, attachment_id, event, attempt, actor, detail) VALUES ($1, $2, $3, $4, $5, $6)",
job_id, attachment_id, name, attempt, actor, detail,
)
async def enqueue(conn: asyncpg.Connection, job_id: uuid.UUID, attachment_id: uuid.UUID, pipeline_version: int,
attempt: int, delay: float = 0.0) -> None:
"""Outbox row for the given attempt; must run inside the transaction that made the job 'queued'."""
payload = job_payload(job_id, attachment_id, pipeline_version, attempt)
await conn.execute(
"""
INSERT INTO outbox (job_id, payload, available_at)
VALUES ($1, $2::jsonb, clock_timestamp() + make_interval(secs => $3))
""",
job_id, json.dumps(payload), float(delay),
)
if delay <= 0:
await conn.execute("SELECT pg_notify('outbox', '')")
async def create_job(conn: asyncpg.Connection, attachment_id: uuid.UUID, pipeline_version: int, actor: str) -> uuid.UUID:
job_id = uuid.uuid4()
await conn.execute(
"""
INSERT INTO jobs (job_id, attachment_id, pipeline_version, max_attempts)
VALUES ($1, $2, $3, $4)
""",
job_id, attachment_id, pipeline_version, config.JOB_MAX_ATTEMPTS,
)
await enqueue(conn, job_id, attachment_id, pipeline_version, 1)
await event(conn, job_id, attachment_id, "accepted", actor, 0, "pipeline_version=%d" % pipeline_version)
return job_id
async def fail(conn: asyncpg.Connection, job: asyncpg.Record, code: str, last_error: str, actor: str) -> None:
"""processing -> failed. The attachment fails only if no version has been published yet."""
await conn.execute(
"""
UPDATE jobs SET status = 'failed', lease_owner = NULL, lease_until = NULL, error_code = $2,
last_error = $3, updated_at = clock_timestamp()
WHERE job_id = $1
""",
job["job_id"], code, last_error[:200],
)
await conn.execute(
"""
UPDATE attachments SET status = 'failed', error_code = $2, updated_at = clock_timestamp()
WHERE id = $1 AND status IN ('queued', 'processing')
""",
job["attachment_id"], code,
)
await event(conn, job["job_id"], job["attachment_id"], "failed", actor, job["attempt"], code + " (" + last_error[:120] + ")")
async def retry_or_fail(conn: asyncpg.Connection, job: asyncpg.Record, reason: str, actor: str) -> str:
"""processing -> queued (with backoff) while attempts remain, otherwise -> failed retry_exhausted."""
if job["attempt"] >= job["max_attempts"]:
await fail(conn, job, "retry_exhausted", reason, actor)
return "failed"
delay = backoff_seconds(job["attempt"])
await conn.execute(
"""
UPDATE jobs SET status = 'queued', lease_owner = NULL, lease_until = NULL, last_error = $2,
next_attempt_at = clock_timestamp() + make_interval(secs => $3), updated_at = clock_timestamp()
WHERE job_id = $1
""",
job["job_id"], reason[:200], delay,
)
await conn.execute(
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = $1 AND status = 'processing'",
job["attachment_id"],
)
await enqueue(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1, delay)
await event(conn, job["job_id"], job["attachment_id"], "retry_scheduled", actor, job["attempt"],
"%s; next attempt %d in %.2fs" % (reason[:120], job["attempt"] + 1, delay))
return "queued"