Files
mtusi2026lab5/src/messenger/jobs.py
T
2026-10-26 19:40:34 +03:00

463 lines
30 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.
"""Задания обработки вложений в PostgreSQL (с lab5): состояния, lease, повторы, outbox, replay.
Источник истины о задании — строка attachment_jobs, а не сообщение в брокере. Брокер только
доставляет «напоминание»: обработай задание job_id, попытку attempt. Поэтому дубль, устаревшее
или потерянное сообщение ничего не ломают — решение принимается по строке задания:
сообщение (job_id, attempt) что делает worker
задание ready / failed -> ack, ничего не делает (повтор не создаёт второй набор)
attempt в сообщении устарел -> ack, ничего не делает (есть сообщение новее)
processing, lease действует -> ack, ничего не делает (задание уже обрабатывается)
processing, lease истёк -> попытка считается неудачной, назначается следующая
queued, attempt совпадает -> взять под lease и обработать
Переходы (contracts/attachment-states.md):
queued -> processing claim(): lease с жетоном (token) и сроком (lease_until);
processing -> ready complete(): только с тем же жетоном (fencing);
processing -> queued retry() при временной ошибке или reap() при истёкшем lease:
attempt+1, пауза backoff с jitter, новая строка outbox;
processing -> failed fail() при постоянной ошибке или когда попытки исчерпаны;
failed -> queued replay(): явная команда оператора, с записью в журнал.
Каждый переход — одна транзакция: строка задания, статус вложения, outbox и журнал
меняются вместе или не меняются вовсе.
"""
import argparse
import json
import logging
import random
import sys
import uuid
from contextlib import contextmanager
from dataclasses import dataclass
import psycopg
from psycopg.types.json import Jsonb
from psycopg_pool import PoolTimeout
from . import broker, config
from .errors import Unavailable
log = logging.getLogger("messenger.jobs")
def backoff(attempt: int) -> float:
"""Пауза перед попыткой attempt+1. «Равный jitter»: случайно в [d/2, d], d = min(MAX, BASE·2^(attempt-1)).
Удвоение даёт временному сбою время пройти. Случайная часть разводит по времени задания,
упавшие одновременно (например, все при остановке S3): иначе они повторялись бы одной волной.
"""
limit = min(config.RETRY_MAX_SECONDS, config.RETRY_BASE_SECONDS * 2 ** (attempt - 1))
return limit / 2 + random.uniform(0, limit / 2)
def predecessor_of(owner: str | None, me: str) -> bool:
"""owner — прошлая жизнь ЭТОГО ЖЕ контейнера (тот же hostname, другой запуск)?
В контейнере один процесс worker. Если lease держит прежний запуск того же контейнера,
значит, тот процесс точно мёртв (контейнер перезапустился): ждать истечения lease не нужно.
"""
if not owner:
return False
return owner.partition("/")[0] == me.partition("/")[0] and owner != me
@dataclass(frozen=True)
class Lease:
job_id: str
attachment_id: str
pipeline_version: int
attempt: int
max_attempts: int
token: str
staging_key: str | None
storage_key: str
content_type: str
size_bytes: int
sha256: str
width: int
height: int
@dataclass(frozen=True)
class Decision:
kind: str # claimed | ready | failed | stale | in_progress | rescheduled | unknown
lease: Lease | None = None
detail: str = ""
def event(conn, job_id, attachment_id, attempt, name: str, actor: str, detail: str | None = None) -> None:
conn.execute("""INSERT INTO job_events (job_id, attachment_id, attempt, event, actor, detail)
VALUES (%s, %s, %s, %s, %s, %s)""",
(job_id, attachment_id, attempt, name, actor[:120], detail[:300] if detail else None))
def enqueue(conn, job_id, attachment_id, pipeline_version: int, attempt: int, delay_seconds: float = 0.0) -> None:
"""Строка outbox в ТЕКУЩЕЙ транзакции: сообщение уйдёт в брокер не раньше чем через delay_seconds."""
payload = broker.build_message(str(job_id), str(attachment_id), pipeline_version, attempt)
conn.execute("""INSERT INTO outbox (job_id, attempt, payload, available_at)
VALUES (%s, %s, %s, now() + make_interval(secs => %s))""",
(job_id, attempt, Jsonb(payload), delay_seconds))
def create(conn, attachment_id, actor: str) -> uuid.UUID:
"""Новое задание для только что принятого вложения (в транзакции загрузки, см. store.py)."""
job_id = uuid.uuid4()
conn.execute("""INSERT INTO attachment_jobs (job_id, attachment_id, pipeline_version, status, attempt, max_attempts)
VALUES (%s, %s, %s, 'queued', 1, %s)""",
(job_id, attachment_id, config.PIPELINE_VERSION, config.JOB_MAX_ATTEMPTS))
enqueue(conn, job_id, attachment_id, config.PIPELINE_VERSION, 1)
event(conn, job_id, attachment_id, 1, "queued", actor, "загрузка принята, оригинал в staging")
return job_id
_CLEAR_LEASE = "lease_owner = NULL, lease_token = NULL, lease_until = NULL"
class LockBusy(Exception):
"""Строку задания дольше lock_timeout держит другая транзакция (уборщик, worker)."""
class JobStore:
def __init__(self, pool, actor: str):
self.pool = pool
self.actor = actor # кто выполняет переходы: worker-<id> или operator
@contextmanager
def _tx(self):
try:
with self.pool.connection() as conn:
with conn.transaction():
yield conn
except (psycopg.OperationalError, PoolTimeout) as exc:
log.warning("PostgreSQL недоступен: %s", type(exc).__name__)
raise Unavailable("PostgreSQL недоступен") from None
# ---------- переход «попытка закончилась неудачей» ----------
def _attempt_over(self, conn, job_id, attachment_id, version, attempt, max_attempts,
code: str, message: str, permanent: bool) -> str:
"""processing -> queued (следующая попытка через backoff) или -> failed. Возвращает retry|failed."""
if permanent or attempt >= max_attempts:
final = code if permanent else "retry_exhausted"
conn.execute(f"""UPDATE attachment_jobs SET status = 'failed', {_CLEAR_LEASE},
last_error_code = %s, last_error = %s, finished_at = now(), updated_at = now()
WHERE job_id = %s""", (code, message[:300], job_id))
conn.execute("""UPDATE attachments SET status = 'failed', error_code = %s, updated_at = now()
WHERE id = %s AND status IN ('queued', 'processing')""", (final, attachment_id))
event(conn, job_id, attachment_id, attempt, "failed", self.actor,
f"{final}; последняя ошибка {code}: {message}")
return "failed"
delay = backoff(attempt)
conn.execute(f"""UPDATE attachment_jobs SET status = 'queued', attempt = attempt + 1, {_CLEAR_LEASE},
next_attempt_at = now() + make_interval(secs => %s),
last_error_code = %s, last_error = %s, updated_at = now()
WHERE job_id = %s""", (delay, code, message[:300], job_id))
conn.execute("""UPDATE attachments SET status = 'queued', updated_at = now()
WHERE id = %s AND status IN ('queued', 'processing')""", (attachment_id,))
enqueue(conn, job_id, attachment_id, version, attempt + 1, delay)
event(conn, job_id, attachment_id, attempt, "retry_scheduled", self.actor,
f"{code}: {message}; попытка {attempt + 1} через {delay:.1f} с")
return "retry"
# ---------- worker ----------
def claim(self, message: dict, worker_id: str) -> Decision:
"""Решить, что делать с доставленным сообщением, и при необходимости взять задание под lease."""
with self._tx() as conn:
row = conn.execute(
"""SELECT j.job_id, j.attachment_id, j.pipeline_version, j.status, j.attempt, j.max_attempts,
j.lease_owner, j.lease_until < now(),
a.staging_key, a.storage_key, a.content_type, a.size_bytes, a.sha256, a.width, a.height
FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE j.job_id = %s FOR UPDATE OF j""", (uuid.UUID(message["job_id"]),)).fetchone()
if row is None:
return Decision("unknown", detail="нет такого задания")
(job_id, attachment_id, version, status, attempt, max_attempts, owner, expired,
staging_key, storage_key, content_type, size_bytes, sha256, width, height) = row
if str(attachment_id) != message["attachment_id"] or version != message["pipeline_version"]:
return Decision("unknown", detail="сообщение не совпадает с заданием")
if status in ("ready", "failed"):
event(conn, job_id, attachment_id, message["attempt"], "duplicate_ignored", self.actor,
f"задание уже {status}: повторная доставка, ack без обработки")
return Decision(status)
if message["attempt"] != attempt:
event(conn, job_id, attachment_id, message["attempt"], "stale_ignored", self.actor,
f"устаревшее сообщение: актуальная попытка {attempt}")
return Decision("stale")
if status == "processing":
if owner == worker_id:
return Decision("in_progress", detail="уже обрабатывается этим worker")
dead = predecessor_of(owner, worker_id)
if not expired and not dead:
event(conn, job_id, attachment_id, attempt, "duplicate_in_progress", self.actor,
"задание под действующим lease другого worker")
return Decision("in_progress")
reason = "прежний запуск этого контейнера упал" if dead else "lease истёк"
event(conn, job_id, attachment_id, attempt, "lease_expired", self.actor, reason)
outcome = self._attempt_over(conn, job_id, attachment_id, version, attempt, max_attempts,
"worker_crashed", reason, permanent=False)
return Decision("rescheduled", detail=outcome)
token = uuid.uuid4()
conn.execute("""UPDATE attachment_jobs SET status = 'processing', lease_owner = %s, lease_token = %s,
lease_until = now() + make_interval(secs => %s), updated_at = now()
WHERE job_id = %s""", (worker_id, token, config.JOB_LEASE_SECONDS, job_id))
conn.execute("""UPDATE attachments SET status = 'processing', updated_at = now()
WHERE id = %s AND status IN ('queued', 'processing')""", (attachment_id,))
event(conn, job_id, attachment_id, attempt, "claimed", self.actor,
f"lease на {config.JOB_LEASE_SECONDS} с")
return Decision("claimed", Lease(str(job_id), str(attachment_id), version, attempt, max_attempts, str(token),
staging_key, storage_key, content_type, int(size_bytes), sha256,
int(width), int(height)))
def renew(self, tokens: list[str]) -> set[str]:
"""Продлить lease заданий, которые этот worker ещё обрабатывает. Возвращает продлённые жетоны.
Жетона нет в ответе — lease уже забрали (истёк и задание переназначено): работу надо бросить.
"""
if not tokens:
return set()
with self._tx() as conn:
rows = conn.execute("""UPDATE attachment_jobs
SET lease_until = now() + make_interval(secs => %s), updated_at = now()
WHERE status = 'processing' AND lease_token = ANY(%s::uuid[])
RETURNING lease_token""",
(config.JOB_LEASE_SECONDS, [uuid.UUID(t) for t in tokens])).fetchall()
return {str(r[0]) for r in rows}
def _fenced(self, conn, lease: Lease):
"""Строка задания, если lease всё ещё наш (тот же жетон). Иначе None: результат не принимается."""
return conn.execute("""SELECT attempt, max_attempts FROM attachment_jobs
WHERE job_id = %s AND lease_token = %s AND status = 'processing'
FOR UPDATE""", (uuid.UUID(lease.job_id), uuid.UUID(lease.token))).fetchone()
def complete(self, lease: Lease, variants: list[dict]) -> bool:
"""processing -> ready: варианты, статус вложения и задания — одной транзакцией."""
with self._tx() as conn:
if self._fenced(conn, lease) is None:
return False
attachment_id, job_id = uuid.UUID(lease.attachment_id), uuid.UUID(lease.job_id)
for v in variants:
# Первичный ключ (attachment_id, pipeline_version, name) — ключ эффекта: второй набор невозможен.
conn.execute("""INSERT INTO attachment_variants (attachment_id, pipeline_version, name, storage_key,
content_type, size_bytes, width, height, sha256, job_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
storage_key = EXCLUDED.storage_key, content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width,
height = EXCLUDED.height, sha256 = EXCLUDED.sha256, job_id = EXCLUDED.job_id""",
(attachment_id, lease.pipeline_version, v["name"], v["storage_key"], v["content_type"],
v["size_bytes"], v["width"], v["height"], v["sha256"], job_id))
conn.execute("""UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = now()
WHERE id = %s AND status IN ('queued', 'processing')""", (attachment_id,))
conn.execute(f"""UPDATE attachment_jobs SET status = 'ready', {_CLEAR_LEASE},
finished_at = now(), updated_at = now()
WHERE job_id = %s""", (job_id,))
event(conn, job_id, attachment_id, lease.attempt, "ready", self.actor,
"оригинал опубликован, варианты: " + ", ".join(v["name"] for v in variants))
return True
def fail(self, lease: Lease, code: str, message: str) -> bool:
"""Постоянная ошибка: processing -> failed сразу, без повторов."""
with self._tx() as conn:
row = self._fenced(conn, lease)
if row is None:
return False
self._attempt_over(conn, uuid.UUID(lease.job_id), uuid.UUID(lease.attachment_id), lease.pipeline_version,
row[0], row[1], code, message, permanent=True)
return True
def retry(self, lease: Lease, code: str, message: str) -> str:
"""Временная ошибка: следующая попытка с backoff или failed. Возвращает retry | failed | lost."""
with self._tx() as conn:
row = self._fenced(conn, lease)
if row is None:
return "lost"
return self._attempt_over(conn, uuid.UUID(lease.job_id), uuid.UUID(lease.attachment_id),
lease.pipeline_version, row[0], row[1], code, message, permanent=False)
def reap(self, limit: int = 50) -> list[tuple[str, str]]:
"""Задания с истёкшим lease (worker умер или завис и не продлевал аренду) -> следующая попытка."""
done = []
with self._tx() as conn:
rows = conn.execute("""SELECT job_id, attachment_id, pipeline_version, attempt, max_attempts, lease_owner
FROM attachment_jobs
WHERE status = 'processing' AND lease_until < now()
ORDER BY lease_until LIMIT %s
FOR UPDATE SKIP LOCKED""", (limit,)).fetchall()
for job_id, attachment_id, version, attempt, max_attempts, owner in rows:
event(conn, job_id, attachment_id, attempt, "lease_expired", self.actor,
f"lease {owner} истёк: worker не продлил аренду (упал или завис)")
done.append((str(attachment_id), self._attempt_over(
conn, job_id, attachment_id, version, attempt, max_attempts,
"lease_expired", "worker не продлил lease", permanent=False)))
return done
def republish_stale(self, age_seconds: int, limit: int = 50) -> int:
"""Страховка: задание давно в queued, а свежей отправки нет — отправить сообщение ещё раз."""
with self._tx() as conn:
rows = conn.execute(
"""SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt FROM attachment_jobs j
WHERE j.status = 'queued' AND j.next_attempt_at < now() - make_interval(secs => %s)
AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.job_id AND o.attempt = j.attempt
AND (o.published_at IS NULL
OR o.published_at > now() - make_interval(secs => %s)))
LIMIT %s FOR UPDATE OF j SKIP LOCKED""", (age_seconds, age_seconds, limit)).fetchall()
for job_id, attachment_id, version, attempt in rows:
enqueue(conn, job_id, attachment_id, version, attempt)
event(conn, job_id, attachment_id, attempt, "republished", self.actor,
f"нет обработки дольше {age_seconds} с: сообщение отправлено повторно")
return len(rows)
# ---------- оператор ----------
def replay(self, attachment_id: str, staging_exists) -> dict:
"""failed -> queued по команде оператора. Готовое или ещё идущее задание НЕ повторяется.
Всё в ОДНОЙ транзакции под блокировкой строк задания и вложения — тех же, что берёт уборщик
(store.cleanup_attachment), в том же порядке. Поэтому уборщик не удалит staging между
проверкой исходника и переводом в queued (замечание к MR):
- уборщик успел раньше: он уже пометил staging удалённым (staging_key = NULL) и удалил его,
replay ждал блокировку и теперь безопасно отказывает (source_missing), задание остаётся failed;
- replay успел раньше: уборщик ждёт блокировку, потом видит queued — исходник нужен текущей
работе, и он его не трогает.
Наличие объекта в S3 (staging_exists) проверяется тоже под блокировкой.
"""
aid = uuid.UUID(attachment_id)
try:
return self._replay(aid, staging_exists)
except LockBusy:
return {"result": "busy", "detail": "вложение сейчас обрабатывает уборщик или worker, повторите позже"}
def _replay(self, aid: uuid.UUID, staging_exists) -> dict:
with self._tx() as conn:
# Команда оператора может подождать блокировку дольше обычного запроса (5 с).
conn.execute("SET LOCAL lock_timeout = '20s'")
conn.execute("SET LOCAL statement_timeout = '25s'")
try:
row = conn.execute("""SELECT job_id, status, attempt, last_error_code FROM attachment_jobs
WHERE attachment_id = %s AND pipeline_version = %s FOR UPDATE""",
(aid, config.PIPELINE_VERSION)).fetchone()
if row is None:
return {"result": "not_found"}
staging_key, error_code = conn.execute(
"SELECT staging_key, error_code FROM attachments WHERE id = %s FOR UPDATE", (aid,)).fetchone()
except psycopg.errors.LockNotAvailable:
raise LockBusy() from None
job_id, status, attempt, last_code = row
if status != "failed":
event(conn, job_id, aid, attempt, "replay_refused", self.actor,
f"задание в состоянии {status}: повторять нечего")
return {"result": "noop", "reason": status}
if not staging_key or not staging_exists(staging_key):
detail = "оригинал в staging уже удалён (истёк STAGING_RETENTION_SECONDS)"
event(conn, job_id, aid, attempt, "replay_refused", self.actor, "source_missing: " + detail)
return {"result": "refused", "reason": "source_missing", "detail": detail}
new_attempt = attempt + 1
conn.execute(f"""UPDATE attachment_jobs SET status = 'queued', attempt = %s, max_attempts = %s,
{_CLEAR_LEASE}, next_attempt_at = now(), finished_at = NULL, updated_at = now()
WHERE job_id = %s""", (new_attempt, attempt + config.JOB_MAX_ATTEMPTS, job_id))
conn.execute("""UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = %s AND status = 'failed'""", (aid,))
enqueue(conn, job_id, aid, config.PIPELINE_VERSION, new_attempt)
event(conn, job_id, aid, new_attempt, "replay_requested", self.actor,
f"replay оператора: было {error_code} (последняя ошибка {last_code}); "
f"новая попытка {new_attempt}, ещё {config.JOB_MAX_ATTEMPTS} попыток")
return {"result": "queued", "attempt": new_attempt, "previous_error": error_code}
def failed(self, limit: int = 50) -> list[dict]:
"""Реестр failed для оператора: что упало, с каким кодом, сколько было попыток."""
with self._tx() as conn:
rows = conn.execute("""SELECT j.attachment_id, j.job_id, a.error_code, j.last_error_code, j.last_error,
j.attempt, j.finished_at
FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE j.status = 'failed' ORDER BY j.finished_at DESC LIMIT %s""",
(limit,)).fetchall()
return [{"attachment_id": str(r[0]), "job_id": str(r[1]), "error_code": r[2], "last_error_code": r[3],
"last_error": r[4], "attempts": r[5], "finished_at": r[6].isoformat() if r[6] else None}
for r in rows]
def show(self, attachment_id: str) -> dict:
"""Всё о задании вложения: состояние, журнал, строки outbox, варианты (без ключей доступа)."""
with self._tx() as conn:
job = conn.execute("""SELECT job_id, status, attempt, max_attempts, lease_owner, lease_until,
next_attempt_at, last_error_code, last_error, created_at, finished_at
FROM attachment_jobs WHERE attachment_id = %s""",
(uuid.UUID(attachment_id),)).fetchone()
if job is None:
return {"result": "not_found"}
events = conn.execute("""SELECT created_at, attempt, event, actor, detail FROM job_events
WHERE job_id = %s ORDER BY id""", (job[0],)).fetchall()
outbox = conn.execute("""SELECT id, attempt, available_at, published_at, published_by FROM outbox
WHERE job_id = %s ORDER BY id""", (job[0],)).fetchall()
variants = conn.execute("""SELECT name, storage_key, size_bytes, width, height, sha256
FROM attachment_variants WHERE attachment_id = %s
ORDER BY pipeline_version, name""", (uuid.UUID(attachment_id),)).fetchall()
status = conn.execute("SELECT status, error_code FROM attachments WHERE id = %s",
(uuid.UUID(attachment_id),)).fetchone()
def t(value):
return value.isoformat() if value else None
names = ("job_id", "status", "attempt", "max_attempts", "lease_owner", "lease_until", "next_attempt_at",
"last_error_code", "last_error", "created_at", "finished_at")
return {"attachment_status": status[0], "error_code": status[1],
"job": {k: (t(v) if hasattr(v, "isoformat") else (str(v) if isinstance(v, uuid.UUID) else v))
for k, v in zip(names, job)},
"events": [{"at": t(e[0]), "attempt": e[1], "event": e[2], "actor": e[3], "detail": e[4]}
for e in events],
"outbox": [{"id": o[0], "attempt": o[1], "available_at": t(o[2]), "published_at": t(o[3]),
"published_by": o[4]} for o in outbox],
"variants": [{"name": v[0], "storage_key": v[1], "size_bytes": v[2], "width": v[3], "height": v[4],
"sha256": v[5]} for v in variants]}
def stats(self) -> dict:
with self._tx() as conn:
by_status = dict(conn.execute("SELECT status, count(*) FROM attachment_jobs GROUP BY status").fetchall())
unpublished = conn.execute("SELECT count(*) FROM outbox WHERE published_at IS NULL").fetchone()[0]
processing = conn.execute("SELECT count(*) FROM attachment_jobs WHERE status = 'processing'").fetchone()[0]
return {"jobs": by_status, "outbox_unpublished": unpublished, "processing_now": processing}
def main(argv=None) -> int:
"""Команды оператора (внутри контейнера worker):
python -m messenger.jobs failed реестр failed
python -m messenger.jobs show <attachment_id> состояние, журнал, outbox, варианты
python -m messenger.jobs replay <attachment_id> [--actor имя] явный повтор failed
python -m messenger.jobs stats сколько заданий в каждом состоянии
"""
parser = argparse.ArgumentParser(description="Задания обработки вложений")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("failed")
sub.add_parser("stats")
show = sub.add_parser("show")
show.add_argument("attachment_id", type=uuid.UUID)
replay = sub.add_parser("replay")
replay.add_argument("attachment_id", type=uuid.UUID)
replay.add_argument("--actor", default="operator")
args = parser.parse_args(argv)
logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")
config.validate()
from . import db
pool = db.create_pool()
pool.open()
try:
if args.command == "replay":
config.validate_s3()
from . import objects
store = JobStore(pool, "operator:" + args.actor[:40])
result = store.replay(str(args.attachment_id), objects.exists)
else:
store = JobStore(pool, "operator")
result = {"failed": store.failed, "stats": store.stats}.get(args.command, None)
result = result() if result else store.show(str(args.attachment_id))
print(json.dumps(result, ensure_ascii=False, default=str))
except Unavailable as exc:
print(json.dumps({"error": exc.message}, ensure_ascii=False))
return 1
finally:
pool.close()
return 0
if __name__ == "__main__":
sys.exit(main())