"""Репозиторий jobs и outbox + реестр failed + replay.""" import json import logging import uuid from datetime import datetime, timezone from . import config, repo log = logging.getLogger("jobs") # --- создание задания (API) ---------------------------------------------- def create_job_for_attachment(conn, attachment_id: uuid.UUID, pipeline_version: int = 1) -> dict: """INSERT job + INSERT outbox в одной транзакции. Вызывается API после того, как staging-объект сохранён и строка attachments вставлена со status='queued' и staging_key. """ job_id = uuid.uuid4() job = conn.execute( """INSERT INTO jobs (job_id, attachment_id, pipeline_version, status, max_attempts) VALUES (%s, %s, %s, 'queued', %s) ON CONFLICT (attachment_id, pipeline_version) DO NOTHING RETURNING job_id, attachment_id, pipeline_version, attempt, type""", (job_id, attachment_id, pipeline_version, config.JOB_MAX_ATTEMPTS)).fetchone() if job is None: # Уже есть — идемпотентно, но outbox тоже не создаём. return None payload = { "schema_version": 1, "job_id": str(job["job_id"]), "type": job["type"], "attachment_id": str(job["attachment_id"]), "pipeline_version": job["pipeline_version"], "attempt": 1, "created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"), } # INSERT без RETURNING — НЕ вызываем .fetchone(). conn.execute( """INSERT INTO outbox (topic, payload) VALUES (%s, %s::jsonb)""", (job["type"], json.dumps(payload))) return payload # --- outbox publisher ----------------------------------------------------- def publish_pending_outbox(conn, publish_fn) -> int: """Публикует неопубликованные outbox-записи. Возвращает число опубликованных. Ошибки не роняют цикл — запись помечается attempts+1 и last_error. """ rows = conn.execute( """SELECT id, topic, payload FROM outbox WHERE published_at IS NULL AND attempts < 20 ORDER BY id LIMIT 50 FOR UPDATE SKIP LOCKED""").fetchall() published = 0 for row in rows: try: publish_fn(row["payload"] if isinstance(row["payload"], dict) else json.loads(row["payload"])) except Exception as exc: conn.execute( """UPDATE outbox SET attempts = attempts + 1, last_error = %s WHERE id = %s""", (type(exc).__name__, row["id"])) log.warning("outbox %s publish failed: %s", row["id"], type(exc).__name__) break # стоп — брокер, возможно, недоступен conn.execute( """UPDATE outbox SET published_at = clock_timestamp() WHERE id = %s""", (row["id"],)) published += 1 return published # --- worker: claim, processing, retry, failed ---------------------------- def claim_job(conn, job_id: uuid.UUID) -> dict: """Атомарно переводит queued → processing, выдаёт lease. Возвращает строку job, если claim успешен (attempt++). Иначе None — значит, задачу уже взял другой worker или она в другом статусе. """ return conn.execute( """UPDATE jobs SET status = 'processing', attempt = attempt + 1, lease_until = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE job_id = %s AND status = 'queued' AND (next_attempt_at IS NULL OR next_attempt_at <= clock_timestamp()) RETURNING job_id, attachment_id, pipeline_version, attempt, max_attempts, type""", (config.JOB_TIMEOUT_SECONDS, job_id)).fetchone() def mark_ready(conn, job_id: uuid.UUID) -> None: conn.execute( """UPDATE jobs SET status = 'ready', error_code = NULL, lease_until = NULL, updated_at = clock_timestamp() WHERE job_id = %s""", (job_id,)) def mark_retry(conn, job_id: uuid.UUID, error_code: str, backoff_seconds: float) -> None: conn.execute( """UPDATE jobs SET status = 'queued', lease_until = NULL, next_attempt_at = clock_timestamp() + make_interval(secs => %s), error_code = %s, updated_at = clock_timestamp() WHERE job_id = %s""", (backoff_seconds, error_code, job_id)) def mark_failed(conn, job_id: uuid.UUID, error_code: str) -> None: conn.execute( """UPDATE jobs SET status = 'failed', error_code = %s, lease_until = NULL, updated_at = clock_timestamp() WHERE job_id = %s""", (error_code, job_id)) def find_expired_leases(conn, limit: int = 50): """Возвращает job, у которых истёк lease — зависший processing.""" return conn.execute( """SELECT job_id, attachment_id, attempt, max_attempts FROM jobs WHERE status = 'processing' AND lease_until < clock_timestamp() ORDER BY lease_until LIMIT %s FOR UPDATE SKIP LOCKED""", (limit,)).fetchall() def requeue_expired(conn, row) -> str: """Expired lease: attempt уже инкрементирован при claim. Если попытки исчерпаны — failed, иначе — queued с backoff.""" if row["attempt"] >= row["max_attempts"]: mark_failed(conn, row["job_id"], "worker_timeout") return "failed" backoff = min(60.0, 2.0 ** row["attempt"]) * (0.5 + 0.5 * (uuid.uuid4().int & 0xFFFF) / 0xFFFF) mark_retry(conn, row["job_id"], "worker_timeout", backoff) return "queued" # --- operator replay ------------------------------------------------------ def replay_failed(conn, job_id: uuid.UUID) -> dict: """Операторский replay: failed → queued, attempt=0, INSERT outbox. Не перезапускает успешные задачи. Ошибки не глушит. """ row = conn.execute( """UPDATE jobs SET status = 'queued', attempt = 0, error_code = NULL, lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp() WHERE job_id = %s AND status = 'failed' RETURNING job_id, attachment_id, pipeline_version, type""", (job_id,)).fetchone() if row is None: return None payload = { "schema_version": 1, "job_id": str(row["job_id"]), "type": row["type"], "attachment_id": str(row["attachment_id"]), "pipeline_version": row["pipeline_version"], "attempt": 1, "created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"), } conn.execute("INSERT INTO outbox (topic, payload) VALUES (%s, %s::jsonb)", (row["type"], json.dumps(payload))) return payload