Files
mtusi2026lab7/app/jobs.py
T
eqktrinandO3 Agent Claude 23ac69428e ЛР7: перенести минимум lab6 в приложение (API, worker, OTel)
- бизнес-API без изменений контракта; транспорт теперь HTTPS за mTLS-relay
- retry задачи переопубликовывается через outbox (в lab6 задача после
  ошибки оставалась в queued навсегда); trace context сохраняется в
  outbox.headers, поэтому API -> broker -> worker остаётся одной трассой
- структурные JSON-логи: trace_id/span_id в теле строки (SDK игнорирует
  formatter, поэтому добавлен JsonLoggingHandler)
- закрыты дефекты lab6: закреплён uid datasource в dashboard, убрана
  зависимость от Valkey (сессии и rate limit - в PostgreSQL)
- метрики/логи/трассы уходят в Collector по OTLP с клиентским сертификатом

Co-Authored-By: O3 Agent Claude <noreply@ozon.ru>
2026-11-27 19:58:21 +03:00

181 lines
7.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Репозиторий jobs и outbox + реестр failed + replay.
lab7: pending-outbox публикация, retry и операторский replay сохраняют
W3C trace context в outbox.headers, поэтому цепочка upload → publish → consume
не рвётся при фоновой публикации и повторе.
"""
import json
import logging
import uuid
from datetime import datetime, timezone
from . import config, telemetry
log = logging.getLogger("jobs")
JOB_TYPE = "attachment.process.v1"
def _payload(job_row):
return {
"schema_version": 1,
"job_id": str(job_row["job_id"]),
"type": job_row["type"],
"attachment_id": str(job_row["attachment_id"]),
"pipeline_version": job_row["pipeline_version"],
"attempt": max(1, int(job_row.get("attempt") or 0)),
"created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
}
def _insert_outbox(conn, topic, payload, carrier=None):
conn.execute(
"""INSERT INTO outbox (topic, payload, headers) VALUES (%s, %s::jsonb, %s::jsonb)""",
(topic, json.dumps(payload), json.dumps(carrier or {})))
# --- создание задания (API) ----------------------------------------------
def create_job_for_attachment(conn, attachment_id, pipeline_version=1):
"""INSERT job + INSERT outbox в одной транзакции.
trace context текущего запроса сохраняется вместе с outbox-строкой:
публикация может произойти позже, в фоновом цикле без активного span.
"""
carrier = telemetry.inject_headers({})
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""",
(uuid.uuid4(), attachment_id, pipeline_version, config.JOB_MAX_ATTEMPTS)).fetchone()
if job is None:
return None
payload = _payload(job)
_insert_outbox(conn, job["type"], payload, carrier)
return payload
# --- outbox publisher -----------------------------------------------------
def publish_pending_outbox(conn, publish_fn):
"""Публикует неопубликованные outbox-записи. Возвращает число опубликованных."""
rows = conn.execute(
"""SELECT id, topic, payload, headers 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:
payload = row["payload"] if isinstance(row["payload"], dict) else json.loads(row["payload"])
headers = row["headers"] if isinstance(row["headers"], dict) else json.loads(row["headers"] or "{}")
try:
publish_fn(payload, headers)
except Exception as exc: # noqa: BLE001 - цикл не должен падать
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):
"""Атомарно переводит queued → processing, выдаёт lease."""
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):
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, error_code, backoff_seconds, carrier=None):
"""queued с backoff + НОВАЯ outbox-строка.
Без повторной публикации задача с next_attempt_at не была бы доставлена:
брокер уже получил ack. Поэтому retry = UPDATE jobs + INSERT outbox в одной
транзакции; контекст текущей попытки сохраняется в headers.
"""
row = 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
RETURNING job_id, attachment_id, pipeline_version, attempt, type""",
(backoff_seconds, error_code, job_id)).fetchone()
if row is not None:
_insert_outbox(conn, row["type"], _payload(row), carrier)
return row
def mark_failed(conn, job_id, error_code):
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=50):
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):
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):
"""Операторский 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"),
}
_insert_outbox(conn, row["type"], payload)
return payload