"""Задания обработки вложений: схема сообщения, переходы состояний, retry, lease, replay. Используется API (постановка в очередь), worker, relay (reaper) и ops-CLI. Все переходы — SQL-транзакции над строкой jobs под FOR UPDATE, поэтому решение «что делать с сообщением» принимается по устойчивому состоянию в PostgreSQL, а не по факту доставки. Сообщение брокера (contracts/jobs.schema.json) — только ссылка: job_id, attachment_id, pipeline_version, attempt. Bytes, credentials, URL и ключи S3 в сообщение не попадают: worker берёт доверенные storage metadata из БД. Переходы (contracts/attachment-states.md): enqueue нет -> queued API, одна транзакция с outbox claim queued -> processing worker: attempt+1, lease_owner/token/until heartbeat processing (продление) worker, только со своим lease_token complete processing -> ready worker, только со своим lease_token (fencing) retry processing -> queued временная ошибка, backoff + jitter, outbox с available_at fail processing -> failed постоянная ошибка или исчерпаны попытки lease expired processing -> queued reaper (relay), если аренду никто не продлил replay failed -> queued оператор (ops.py), audit, ready не трогается Lab6 (W3C Trace Context через очередь): add_outbox внутри активной трассы создаёт PRODUCER span «attachment.process.v1 create» и пишет его traceparent/tracestate в payload outbox (поля разрешены contracts/jobs.schema.json). Relay публикует сообщение в span-е «send» (child), worker обрабатывает в CONSUMER span-е «process» (child от send). Retry из worker пишет новый outbox в контексте текущей попытки -> следующая попытка в той же трассе. Фоновые переходы без трассы (reaper, redrive, replay оператора) берут traceparent последнего outbox этого job — цепочка upload -> все попытки остаётся одной трассой. """ import datetime as dt import json import random import re import uuid import telemetry from telemetry import SpanKind, db_operation SCHEMA_VERSION = 1 # Аудит F11: публикация результата и выборка вариантов согласованы только для v1. SUPPORTED_PIPELINE_VERSIONS = (1,) JOB_TYPE = "attachment.process.v1" VARIANT_NAMES = ("thumbnail", "crop", "optimized") # Постоянные ошибки: повтор не поможет (тот же вход даст тот же результат). PERMANENT_ERRORS = {"invalid_image", "image_too_large", "staging_corrupted", "staging_missing", "resource_limit"} _UUID_FIELDS = ("job_id", "attachment_id") _ALLOWED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at", "traceparent", "tracestate"} class InvalidMessage(Exception): """Сообщение не соответствует jobs.schema.json -> reject в DLQ.""" def utc_now_text(): return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def make_payload(job_id, attachment_id, pipeline_version, attempt, created_at=None, trace_fields=None): payload = { "schema_version": SCHEMA_VERSION, "job_id": str(job_id), "type": JOB_TYPE, "attachment_id": str(attachment_id), "pipeline_version": int(pipeline_version), "attempt": int(attempt), "created_at": created_at or utc_now_text(), } for key in ("traceparent", "tracestate"): value = (trace_fields or {}).get(key) if key == "traceparent" and value and _TRACEPARENT_RE.match(value): payload[key] = value elif key == "tracestate" and value and len(value) <= 512: payload[key] = value return payload _UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$") # RFC 3339 date-time: обязательно время и зона (Z или ±hh:mm). _DATETIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$") _TRACEPARENT_RE = re.compile(r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$") def _strict_int(v): # В Python True == 1 и isinstance(True, int): bool исключается явно (аудит F12). # По JSON Schema 2020-12 integer — число с нулевой дробной частью: 1.0 тоже допустимо. return type(v) is int or (type(v) is float and v.is_integer()) def parse_message(body): """bytes -> dict строго по jobs.schema.json (без внешних библиотек). Иначе InvalidMessage. Аудит F12: раньше проходили schema_version=true, created_at без времени, traceparent-число и tracestate длиннее 512. Соответствие сверяется с jsonschema тестом job_schema_check.py.""" try: msg = json.loads(body.decode("utf-8")) except (UnicodeDecodeError, ValueError): raise InvalidMessage("not json") if not isinstance(msg, dict): raise InvalidMessage("not object") if set(msg) - _ALLOWED: raise InvalidMessage("extra fields") for field in ("schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"): if field not in msg: raise InvalidMessage("missing " + field) if not _strict_int(msg["schema_version"]) or msg["schema_version"] != SCHEMA_VERSION: raise InvalidMessage("unsupported schema_version") if msg["type"] != JOB_TYPE: raise InvalidMessage("unsupported type") for field in _UUID_FIELDS: if not isinstance(msg[field], str) or not _UUID_RE.match(msg[field]): raise InvalidMessage("bad " + field) for field in ("pipeline_version", "attempt"): if not _strict_int(msg[field]) or msg[field] < 1: raise InvalidMessage("bad " + field) created = msg["created_at"] if not isinstance(created, str) or not _DATETIME_RE.match(created): raise InvalidMessage("bad created_at") try: dt.datetime.fromisoformat(created.upper().replace("Z", "+00:00")) except ValueError: raise InvalidMessage("bad created_at") if "traceparent" in msg and (not isinstance(msg["traceparent"], str) or not _TRACEPARENT_RE.match(msg["traceparent"])): raise InvalidMessage("bad traceparent") if "tracestate" in msg and (not isinstance(msg["tracestate"], str) or len(msg["tracestate"]) > 512): raise InvalidMessage("bad tracestate") for field in ("schema_version", "pipeline_version", "attempt"): msg[field] = int(msg[field]) # 1.0 -> 1 return msg def backoff_seconds(attempt, base, cap, rng=random): """Экспоненциальный backoff с «equal jitter»: d = min(cap, base*2^(attempt-1)), задержка равномерно в [d/2, d]. Половина гарантирует паузу (не долбим упавший S3), случайная половина разносит повторы многих заданий во времени (нет «стада»).""" d = min(float(cap), float(base) * (2 ** max(0, attempt - 1))) return d / 2 + rng.uniform(0, d / 2) def add_event(conn, job_id, event, attempt=None, actor=None, detail=None): conn.execute( "INSERT INTO job_events (job_id, event, attempt, actor, detail) VALUES (%s, %s, %s, %s, %s)", (job_id, event, attempt, actor, json.dumps(detail, ensure_ascii=False) if detail is not None else None)) def _previous_trace(conn, job_id): row = conn.execute( """SELECT payload->>'traceparent' AS traceparent, payload->>'tracestate' AS tracestate FROM outbox WHERE job_id = %s AND payload ? 'traceparent' ORDER BY id DESC LIMIT 1""", (job_id,)).fetchone() if row is None: return {} row = row if isinstance(row, dict) else {"traceparent": row[0], "tracestate": row[1]} return {k: v for k, v in row.items() if v} def add_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds=0.0): if telemetry.has_active_span(): attrs = {"messaging.system": "rabbitmq", "messaging.operation.type": "create", "messaging.operation.name": "create", "messaging.destination.name": "attachments", "messenger.job.id": str(job_id), "messenger.attachment.id": str(attachment_id), "messenger.job.attempt": int(attempt), "messenger.outbox.delay_s": round(float(delay_seconds), 3)} with telemetry.child_span(JOB_TYPE + " create", SpanKind.PRODUCER, attrs): return _insert_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds, telemetry.inject_dict()) return _insert_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds, _previous_trace(conn, job_id)) def _insert_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds, trace_fields): payload = make_payload(job_id, attachment_id, pipeline_version, attempt, trace_fields=trace_fields) conn.execute( """INSERT INTO outbox (job_id, payload, available_at) VALUES (%s, %s, now() + make_interval(secs => %s))""", (job_id, json.dumps(payload), delay_seconds)) return payload # --------------------------------------------------------------------------- # API: постановка в очередь # --------------------------------------------------------------------------- @db_operation("jobs.enqueue") def enqueue(conn, attachment_id, pipeline_version, max_attempts): """В ТЕКУЩЕЙ транзакции: pending -> queued, jobs, outbox, событие. job_id или None.""" row = conn.execute( """UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = %s AND status = 'pending' RETURNING id""", (attachment_id,)).fetchone() if row is None: return None job_id = uuid.uuid4() conn.execute( """INSERT INTO jobs (id, attachment_id, pipeline_version, status, attempt, max_attempts, next_attempt_at, created_at, updated_at) VALUES (%s, %s, %s, 'queued', 0, %s, now(), now(), now())""", (job_id, attachment_id, pipeline_version, max_attempts)) add_event(conn, job_id, "enqueued", 1, "api") add_outbox(conn, job_id, attachment_id, pipeline_version, 1) return job_id # --------------------------------------------------------------------------- # Worker # --------------------------------------------------------------------------- JOB_COLUMNS = """j.id AS job_id, j.attachment_id, j.pipeline_version, j.status AS job_status, j.attempt, j.max_attempts, j.next_attempt_at, j.error_code, j.lease_owner, j.lease_token, j.lease_until, j.replay_count, j.lease_until > now() AS lease_alive, j.next_attempt_at > now() + interval '1 second' AS too_early, GREATEST(0, EXTRACT(EPOCH FROM now() - j.next_attempt_at))::float8 AS eligible_wait_s, EXTRACT(EPOCH FROM now() - j.created_at)::float8 AS job_age_s, a.status AS attachment_status, a.content_type, a.size_bytes, a.sha256, a.width, a.height, a.object_key, a.staging_key, a.filename, a.pipeline_version AS current_pipeline_version""" def load_job(conn, job_id, lock=False): return conn.execute( "SELECT " + JOB_COLUMNS + " FROM jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = %s" + (" FOR UPDATE OF j" if lock else ""), (job_id,)).fetchone() def _owner_host(owner): return (owner or "").split(":", 1)[0] @db_operation("jobs.claim") def claim(conn, msg, owner, lease_seconds): """Решение по сообщению. Возвращает (action, job): 'process' — аренда взята (job со свежим lease_token), можно работать; 'ack' — ничего делать не нужно (уже ready/failed, занято живой арендой, ранний дубль); 'reject' — сообщение не соответствует заданию (в DLQ, разбирает оператор). Вызывается в транзакции; при 'process' коммит фиксирует processing ДО начала работы.""" job = load_job(conn, msg["job_id"], lock=True) if job is None: return "reject", "unknown_job" if str(job["attachment_id"]) != msg["attachment_id"] or job["pipeline_version"] != msg["pipeline_version"]: return "reject", "job_mismatch" status = job["job_status"] if status == "ready": add_event(conn, job["job_id"], "duplicate_ignored", msg["attempt"], owner, {"status": "ready"}) return "ack", job if status == "failed": add_event(conn, job["job_id"], "duplicate_ignored", msg["attempt"], owner, {"status": "failed"}) return "ack", job if job["current_pipeline_version"] > job["pipeline_version"]: # Устаревшая job после новой версии pipeline: результат не публикуем. conn.execute("""UPDATE jobs SET status = 'failed', error_code = 'superseded', lease_owner = NULL, lease_token = NULL, lease_until = NULL, updated_at = now(), finished_at = now() WHERE id = %s""", (job["job_id"],)) add_event(conn, job["job_id"], "superseded", msg["attempt"], owner) return "ack", job if status == "processing" and job["lease_alive"]: prev = job["lease_owner"] or "" # Тот же контейнер (hostname), но другой процесс (boot id): прежняя инкарнация этого # worker умерла (crash/restart) — два процесса одного контейнера одновременно не живут. if not (_owner_host(prev) == _owner_host(owner) and prev != owner): add_event(conn, job["job_id"], "busy_ignored", msg["attempt"], owner, {"lease_owner": prev}) return "ack", job add_event(conn, job["job_id"], "lease_taken_over", job["attempt"], owner, {"previous_owner": prev, "reason": "previous process of this container died"}) elif status == "processing": add_event(conn, job["job_id"], "lease_taken_over", job["attempt"], owner, {"previous_owner": job["lease_owner"], "reason": "lease expired"}) elif job["too_early"]: # queued, но время следующей попытки ещё не пришло: это старый дубль, а запланированное # сообщение relay опубликует само (outbox.available_at). add_event(conn, job["job_id"], "early_duplicate_ignored", msg["attempt"], owner) return "ack", job if job["attempt"] >= job["max_attempts"]: _finish_failed(conn, job, "retry_exhausted", owner, "attempts exhausted before claim") return "ack", job token = uuid.uuid4() conn.execute( """UPDATE jobs SET status = 'processing', attempt = attempt + 1, lease_owner = %s, lease_token = %s, lease_until = now() + make_interval(secs => %s), updated_at = now() WHERE id = %s""", (owner, token, lease_seconds, job["job_id"])) conn.execute("UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = %s", (job["attachment_id"],)) job = dict(job, attempt=job["attempt"] + 1, lease_token=token, job_status="processing") add_event(conn, job["job_id"], "claimed", job["attempt"], owner, {"redelivered_message_attempt": msg["attempt"]}) return "process", job @db_operation("jobs.heartbeat") def heartbeat(conn, job_id, token, lease_seconds): """Продлить аренду. False — аренда потеряна (reaper/другой worker), работу надо бросить.""" cur = conn.execute( """UPDATE jobs SET lease_until = now() + make_interval(secs => %s) WHERE id = %s AND lease_token = %s AND status = 'processing'""", (lease_seconds, job_id, token)) return cur.rowcount == 1 @db_operation("jobs.complete") def complete(conn, job, variants, owner): """processing -> ready атомарно с метаданными вариантов. Только владелец аренды (fencing по lease_token): опоздавший процесс, у которого аренду забрали, ничего не перезапишет. Возвращает 'ready' | 'already_ready' | 'lease_lost'.""" cur = conn.execute( """UPDATE jobs SET status = 'ready', lease_owner = NULL, lease_token = NULL, lease_until = NULL, error_code = NULL, last_error = NULL, updated_at = now(), finished_at = now() WHERE id = %s AND status = 'processing' AND lease_token = %s RETURNING EXTRACT(EPOCH FROM clock_timestamp() - created_at)::float8 AS time_to_ready_s""", (job["job_id"], job["lease_token"])) row = cur.fetchone() if cur.rowcount == 1 else None if row is not None: # От durable acceptance (COMMIT enqueue в API = jobs.created_at) до публикации ready. job["time_to_ready_s"] = row["time_to_ready_s"] if isinstance(row, dict) else row[0] if cur.rowcount != 1: now = load_job(conn, job["job_id"]) add_event(conn, job["job_id"], "commit_rejected_lease_lost", job["attempt"], owner, {"current_status": now["job_status"]}) return "already_ready" if now["job_status"] == "ready" else "lease_lost" with conn.cursor() as cur: # Ключ эффекта — PK (attachment_id, pipeline_version, name): второго набора не будет. cur.executemany( """INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256, created_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, now()) ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type, size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height, sha256 = EXCLUDED.sha256""", [(job["attachment_id"], job["pipeline_version"], v["name"], v["key"], v["content_type"], v["size_bytes"], v["width"], v["height"], v["sha256"]) for v in variants]) # Не откатываем более новую версию pipeline (на случай нескольких версий, трек 5). conn.execute( """UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = now() WHERE id = %s AND pipeline_version <= %s""", (job["attachment_id"], job["pipeline_version"])) add_event(conn, job["job_id"], "ready", job["attempt"], owner, {"variants": {v["name"]: [v["width"], v["height"]] for v in variants}}) return "ready" def _finish_failed(conn, job, code, actor, detail): row = conn.execute( """UPDATE jobs SET status = 'failed', error_code = %s, last_error = %s, lease_owner = NULL, lease_token = NULL, lease_until = NULL, updated_at = now(), finished_at = now() WHERE id = %s RETURNING EXTRACT(EPOCH FROM clock_timestamp() - created_at)::float8 AS t""", (code, (detail or "")[:500], job["job_id"])).fetchone() if row is not None and isinstance(job, dict): job["time_to_terminal_s"] = row["t"] if isinstance(row, dict) else row[0] conn.execute("UPDATE attachments SET status = 'failed', error_code = %s, updated_at = now() WHERE id = %s", (code, job["attachment_id"])) add_event(conn, job["job_id"], "failed", job["attempt"], actor, {"error_code": code, "detail": detail}) @db_operation("jobs.fail_or_retry") def fail_or_retry(conn, job, code, detail, owner, base, cap, rng=random): """Ошибка попытки. Постоянная -> failed(code); временная -> queued с backoff, пока есть попытки, иначе failed(retry_exhausted). Только владелец аренды. Возвращает 'failed' | 'retry' | 'lease_lost' и задержку.""" cur = load_job(conn, job["job_id"], lock=True) if cur["job_status"] != "processing" or cur["lease_token"] != job["lease_token"]: add_event(conn, job["job_id"], "error_ignored_lease_lost", job["attempt"], owner, {"error_code": code}) return "lease_lost", None if code in PERMANENT_ERRORS: _finish_failed(conn, job, code, owner, detail) return "failed", None if cur["attempt"] >= cur["max_attempts"]: _finish_failed(conn, job, "retry_exhausted", owner, "last error: %s %s" % (code, detail or "")) return "failed", None delay = backoff_seconds(cur["attempt"], base, cap, rng) _schedule_retry(conn, cur, delay, code, detail, owner, "retry_scheduled") return "retry", delay def _schedule_retry(conn, job, delay, code, detail, actor, event): conn.execute( """UPDATE jobs SET status = 'queued', lease_owner = NULL, lease_token = NULL, lease_until = NULL, error_code = NULL, last_error = %s, next_attempt_at = now() + make_interval(secs => %s), updated_at = now() WHERE id = %s""", (("%s: %s" % (code, detail or ""))[:500], delay, job["job_id"])) conn.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = %s", (job["attachment_id"],)) add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1, delay) add_event(conn, job["job_id"], event, job["attempt"], actor, {"error_code": code, "delay_seconds": round(delay, 3), "next_attempt": job["attempt"] + 1}) # --------------------------------------------------------------------------- # Reaper (в relay): зависшие processing и потерянные сообщения # --------------------------------------------------------------------------- @db_operation("jobs.reap_expired_leases") def reap_expired_leases(conn, base, cap, actor="reaper", limit=100): """processing с истёкшей арендой (worker умер/завис и не продлевал lease) -> queued с backoff или failed(retry_exhausted). Возвращает число обработанных.""" rows = conn.execute( "SELECT " + JOB_COLUMNS + """ FROM jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.status = 'processing' AND j.lease_until < now() ORDER BY j.lease_until LIMIT %s FOR UPDATE OF j SKIP LOCKED""", (limit,)).fetchall() for job in rows: add_event(conn, job["job_id"], "lease_expired", job["attempt"], actor, {"lease_owner": job["lease_owner"]}) if job["attempt"] >= job["max_attempts"]: _finish_failed(conn, job, "retry_exhausted", actor, "lease expired on last attempt") else: _schedule_retry(conn, job, backoff_seconds(job["attempt"], base, cap), "lease_expired", "worker did not renew lease", actor, "requeued_after_lease") return len(rows) @db_operation("jobs.redrive_stale_queued") def redrive_stale_queued(conn, after_seconds, actor="reaper", limit=100): """queued-задание, по которому давно нет ни неопубликованного outbox, ни движения: сообщение могло потеряться в брокере (например, после потери его volume). Публикуем ещё раз — дубль безопасен, решение примет worker по строке jobs.""" rows = conn.execute( """SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt FROM jobs j WHERE j.status = 'queued' AND j.updated_at < now() - make_interval(secs => %s) AND j.next_attempt_at < now() - make_interval(secs => %s) AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND o.published_at IS NULL) ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED""", (after_seconds, after_seconds, limit)).fetchall() for r in rows: conn.execute("UPDATE jobs SET updated_at = now() WHERE id = %s", (r["id"],)) add_outbox(conn, r["id"], r["attachment_id"], r["pipeline_version"], r["attempt"] + 1) add_event(conn, r["id"], "redriven", r["attempt"] + 1, actor, {"stale_after_seconds": after_seconds}) return len(rows) # --------------------------------------------------------------------------- # Оператор: replay # --------------------------------------------------------------------------- @db_operation("jobs.replay") def replay(conn, attachment_id, actor, extra_attempts, reason, dry_run=False): """failed -> queued. Новая попытка того же job_id (прежний ключ эффекта), max_attempts увеличивается на extra_attempts. ready/queued/processing НЕ трогаются: «повторить» не означает выполнить дубль успешной работы. Возвращает (result, job).""" job = conn.execute( "SELECT " + JOB_COLUMNS + """ FROM jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.attachment_id = %s AND j.pipeline_version = a.pipeline_version FOR UPDATE OF j""", (attachment_id,)).fetchone() if job is None: return "not_found", None if job["job_status"] != "failed": return "refused_status_" + job["job_status"], job # Аудит F01: staging_key перечитывается ОТДЕЛЬНЫМ запросом под блокировкой строки вложения. # В READ COMMITTED «SELECT ... FOR UPDATE OF j» после ожидания блокировки перечитывает только # строку jobs, а колонки attachments из соединения могли остаться из старого снимка — и replay # принял бы работу, исходник которой janitor уже освободил. att = conn.execute("SELECT staging_key FROM attachments WHERE id = %s FOR UPDATE", (job["attachment_id"],)).fetchone() if att["staging_key"] is None: return "refused_staging_expired", job if dry_run: return "would_replay", job conn.execute( """UPDATE jobs SET status = 'queued', max_attempts = attempt + %s, error_code = NULL, next_attempt_at = now(), replay_count = replay_count + 1, updated_at = now(), finished_at = NULL WHERE id = %s""", (extra_attempts, job["job_id"])) conn.execute("UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = %s", (job["attachment_id"],)) add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1) add_event(conn, job["job_id"], "replayed", job["attempt"] + 1, actor, {"reason": reason, "previous_error": job.get("error_code"), "replay_count": job["replay_count"] + 1}) return "replayed", job