forked from mtusi2026/mtusi2026lab7
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия: - внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial; - TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL), Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA; - OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь; - роли БД, S3-политики и права брокера по принципу минимальных прав; - Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS; - hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия; - отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
341 lines
17 KiB
Python
341 lines
17 KiB
Python
"""Durable attachment jobs: state machine in PostgreSQL, delivery through the outbox and the broker.
|
|
|
|
State lives in `attachment_jobs` (source of truth); the broker only carries a reference to it
|
|
(contracts/jobs.schema.json). Every transition below is one SQL transaction that also writes
|
|
`job_audit`, and, when the job must run again, an `outbox` row in the same COMMIT.
|
|
|
|
enqueue nothing -> queued (API, same txn as attachment 'queued')
|
|
claim queued(due) -> processing, lease (worker; also takes over an expired lease)
|
|
heartbeat processing: lease_until += lease (only while owner is still alive)
|
|
complete processing -> succeeded + variants (fenced by lease_owner)
|
|
fail_attempt processing -> queued(+backoff) | failed (transient vs permanent, bounded attempts)
|
|
sweep_leases processing(expired lease) -> queued | failed
|
|
replay failed -> queued (explicit operator action, audited)
|
|
"""
|
|
import json
|
|
import random
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import List, Optional
|
|
|
|
from app import config, telemetry
|
|
from app.cursor import fmt
|
|
|
|
JOB_TYPE = "attachment.process.v1"
|
|
SCHEMA_VERSION = 1
|
|
VARIANT_ORDER = ("thumbnail", "crop", "optimized")
|
|
REQUIRED_VARIANTS = VARIANT_ORDER
|
|
|
|
|
|
def backoff_seconds(attempt: int) -> float:
|
|
"""Equal jitter: half of the exponential delay is fixed, the other half random (never zero, never herd)."""
|
|
ceiling = min(config.JOB_BACKOFF_MAX_SECONDS, config.JOB_BACKOFF_BASE_SECONDS * (2 ** max(0, attempt - 1)))
|
|
return ceiling / 2 + random.uniform(0, ceiling / 2)
|
|
|
|
|
|
def payload(job_id: str, attachment_id: str, pipeline_version: int, attempt: int, created_at: datetime) -> dict:
|
|
return {
|
|
"schema_version": SCHEMA_VERSION,
|
|
"job_id": str(job_id),
|
|
"type": JOB_TYPE,
|
|
"attachment_id": str(attachment_id),
|
|
"pipeline_version": pipeline_version,
|
|
"attempt": attempt,
|
|
"created_at": fmt(created_at),
|
|
}
|
|
|
|
|
|
def parse_message(body: bytes) -> Optional[dict]:
|
|
"""Strict check against jobs.schema.json; anything else goes to the DLQ untouched."""
|
|
try:
|
|
data = json.loads(body.decode("utf-8"))
|
|
except (UnicodeDecodeError, ValueError):
|
|
return None
|
|
required = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
|
|
if not isinstance(data, dict) or not required <= set(data) or set(data) - required - {"traceparent", "tracestate"}:
|
|
return None
|
|
if data["schema_version"] != SCHEMA_VERSION or data["type"] != JOB_TYPE:
|
|
return None
|
|
if "traceparent" in data and not (isinstance(data["traceparent"], str)
|
|
and telemetry.TRACEPARENT_RE.match(data["traceparent"])):
|
|
return None
|
|
if "tracestate" in data and not (isinstance(data["tracestate"], str) and len(data["tracestate"]) <= 512):
|
|
return None
|
|
for key in ("pipeline_version", "attempt"):
|
|
if not isinstance(data[key], int) or isinstance(data[key], bool) or data[key] < 1:
|
|
return None
|
|
try:
|
|
data["job_id"] = str(uuid.UUID(data["job_id"]))
|
|
data["attachment_id"] = str(uuid.UUID(data["attachment_id"]))
|
|
except (ValueError, AttributeError, TypeError):
|
|
return None
|
|
return data
|
|
|
|
|
|
async def audit(conn, job_id, attachment_id, action: str, actor: str, attempt: int, detail: Optional[dict] = None):
|
|
await conn.execute(
|
|
"INSERT INTO job_audit (job_id, attachment_id, action, actor, attempt, detail, created_at)"
|
|
" VALUES (%s, %s, %s, %s, %s, %s::jsonb, clock_timestamp())",
|
|
(job_id, attachment_id, action, actor, attempt, json.dumps(detail or {})),
|
|
)
|
|
|
|
|
|
async def _outbox(conn, job: dict, attempt: int, available_at_sql: str = "clock_timestamp()", delay: float = 0.0):
|
|
body = payload(job["id"], job["attachment_id"], job["pipeline_version"], attempt, job["created_at"])
|
|
# W3C trace context of the transaction that schedules the job (upload request span or the failed consumer
|
|
# span for a retry) travels in the job message (jobs.schema.json traceparent/tracestate).
|
|
body.update(telemetry.inject())
|
|
await conn.execute(
|
|
"INSERT INTO outbox (job_id, payload, available_at, created_at)"
|
|
" VALUES (%s, %s::jsonb, " + available_at_sql + " + make_interval(secs => %s), clock_timestamp())",
|
|
(job["id"], json.dumps(body), delay),
|
|
)
|
|
|
|
|
|
async def enqueue(conn, attachment_id: str, actor: str) -> dict:
|
|
cur = await conn.execute(
|
|
"INSERT INTO attachment_jobs (id, attachment_id, pipeline_version, state, attempt, max_attempts,"
|
|
" next_attempt_at, created_at, updated_at)"
|
|
" VALUES (gen_random_uuid(), %s, %s, 'queued', 1, %s, clock_timestamp(), clock_timestamp(), clock_timestamp())"
|
|
" RETURNING id, attachment_id, pipeline_version, attempt, created_at",
|
|
(attachment_id, config.PIPELINE_VERSION, config.JOB_MAX_ATTEMPTS),
|
|
)
|
|
job = await cur.fetchone()
|
|
await _outbox(conn, job, 1)
|
|
await audit(conn, job["id"], attachment_id, "enqueued", actor, 1)
|
|
return job
|
|
|
|
|
|
async def pending_count(conn) -> int:
|
|
cur = await conn.execute("SELECT count(*) AS n FROM attachment_jobs WHERE state IN ('queued', 'processing')")
|
|
return (await cur.fetchone())["n"]
|
|
|
|
|
|
async def queue_stats(conn) -> dict:
|
|
"""Backlog for metrics: queued / processing jobs, age of the oldest unfinished job, unpublished outbox rows."""
|
|
cur = await conn.execute(
|
|
"SELECT count(*) FILTER (WHERE state = 'queued') AS queued,"
|
|
" count(*) FILTER (WHERE state = 'processing') AS processing,"
|
|
" coalesce(extract(epoch FROM clock_timestamp() - min(created_at)), 0)::float8 AS oldest_age"
|
|
" FROM attachment_jobs WHERE state IN ('queued', 'processing')"
|
|
)
|
|
row = dict(await cur.fetchone())
|
|
cur = await conn.execute("SELECT count(*) AS n FROM outbox WHERE published_at IS NULL")
|
|
row["outbox"] = (await cur.fetchone())["n"]
|
|
return row
|
|
|
|
|
|
# ---------------------------------------------------------------- worker side
|
|
|
|
JOB_COLUMNS = (
|
|
"j.id, j.attachment_id, j.pipeline_version, j.state, j.attempt, j.max_attempts, j.lease_owner, j.lease_until,"
|
|
" j.next_attempt_at, j.created_at, (j.lease_until < clock_timestamp()) AS lease_expired,"
|
|
" (j.next_attempt_at <= clock_timestamp()) AS due"
|
|
)
|
|
|
|
|
|
async def claim(conn, msg: dict, owner: str):
|
|
"""Returns (decision, job). decision: claimed | done | busy | stale | early | missing | newer_version."""
|
|
cur = await conn.execute(
|
|
"SELECT " + JOB_COLUMNS + ", a.pipeline_version AS published_version, a.status AS attachment_status"
|
|
" FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id"
|
|
" WHERE j.id = %s FOR UPDATE OF j",
|
|
(msg["job_id"],),
|
|
)
|
|
job = await cur.fetchone()
|
|
if job is None or str(job["attachment_id"]) != msg["attachment_id"]:
|
|
return "missing", None
|
|
if job["state"] in ("succeeded", "failed"):
|
|
return "done", job
|
|
if msg["pipeline_version"] != job["pipeline_version"] or job["published_version"] > job["pipeline_version"]:
|
|
return "newer_version", job
|
|
if msg["attempt"] != job["attempt"]:
|
|
return "stale", job
|
|
if job["state"] == "processing" and not job["lease_expired"]:
|
|
return "busy", job
|
|
if job["state"] == "queued" and not job["due"]:
|
|
return "early", job
|
|
takeover = job["state"] == "processing"
|
|
await conn.execute(
|
|
"UPDATE attachment_jobs SET state = 'processing', lease_owner = %s,"
|
|
" lease_until = clock_timestamp() + make_interval(secs => %s),"
|
|
" started_at = clock_timestamp(), first_started_at = coalesce(first_started_at, clock_timestamp()),"
|
|
" updated_at = clock_timestamp() WHERE id = %s",
|
|
(owner, config.JOB_LEASE_SECONDS, job["id"]),
|
|
)
|
|
await conn.execute(
|
|
"UPDATE attachments SET status = 'processing', updated_at = clock_timestamp()"
|
|
" WHERE id = %s AND status IN ('queued', 'processing')",
|
|
(job["attachment_id"],),
|
|
)
|
|
await audit(conn, job["id"], job["attachment_id"], "lease_takeover" if takeover else "claimed", owner, job["attempt"])
|
|
return "claimed", job
|
|
|
|
|
|
async def heartbeat(conn, job_id, owner: str) -> bool:
|
|
cur = await conn.execute(
|
|
"UPDATE attachment_jobs SET lease_until = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp()"
|
|
" WHERE id = %s AND state = 'processing' AND lease_owner = %s",
|
|
(config.JOB_LEASE_SECONDS, job_id, owner),
|
|
)
|
|
return cur.rowcount == 1
|
|
|
|
|
|
async def attachment_source(conn, attachment_id) -> Optional[dict]:
|
|
cur = await conn.execute(
|
|
"SELECT id, filename, content_type, size_bytes, sha256, staging_key, object_key, status"
|
|
" FROM attachments WHERE id = %s",
|
|
(attachment_id,),
|
|
)
|
|
return await cur.fetchone()
|
|
|
|
|
|
async def complete(conn, job: dict, owner: str, variants: List[dict]) -> bool:
|
|
"""Atomically publish the result. False when the lease was lost: someone else owns the effect now."""
|
|
cur = await conn.execute(
|
|
"UPDATE attachment_jobs SET state = 'succeeded', finished_at = clock_timestamp(), lease_owner = NULL,"
|
|
" lease_until = NULL, error_code = NULL, updated_at = clock_timestamp()"
|
|
" WHERE id = %s AND state = 'processing' AND lease_owner = %s",
|
|
(job["id"], owner),
|
|
)
|
|
if cur.rowcount != 1:
|
|
return False
|
|
for v in variants:
|
|
await conn.execute(
|
|
"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, clock_timestamp())"
|
|
" ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING",
|
|
(job["attachment_id"], job["pipeline_version"], v["name"], v["object_key"], v["content_type"],
|
|
v["size_bytes"], v["width"], v["height"], v["sha256"]),
|
|
)
|
|
# Never move a newer pipeline_version back, never touch an attachment that is already ready.
|
|
await conn.execute(
|
|
"UPDATE attachments SET status = 'ready', error_code = NULL, pipeline_version = %s, updated_at = clock_timestamp()"
|
|
" WHERE id = %s AND status <> 'ready' AND pipeline_version <= %s",
|
|
(job["pipeline_version"], job["attachment_id"], job["pipeline_version"]),
|
|
)
|
|
await audit(conn, job["id"], job["attachment_id"], "succeeded", owner, job["attempt"],
|
|
{"variants": [v["name"] for v in variants]})
|
|
return True
|
|
|
|
|
|
async def _reschedule_or_fail(conn, job: dict, actor: str, error_code: str, detail: str, transient: bool) -> str:
|
|
attempt = job["attempt"]
|
|
if transient and attempt < job["max_attempts"]:
|
|
delay = backoff_seconds(attempt)
|
|
await conn.execute(
|
|
"UPDATE attachment_jobs SET state = 'queued', attempt = attempt + 1, lease_owner = NULL, lease_until = NULL,"
|
|
" next_attempt_at = clock_timestamp() + make_interval(secs => %s), last_error = %s, error_code = %s,"
|
|
" updated_at = clock_timestamp() WHERE id = %s",
|
|
(delay, detail[:500], error_code, job["id"]),
|
|
)
|
|
await conn.execute(
|
|
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp()"
|
|
" WHERE id = %s AND status IN ('queued', 'processing')",
|
|
(job["attachment_id"],),
|
|
)
|
|
await _outbox(conn, job, attempt + 1, delay=delay)
|
|
await audit(conn, job["id"], job["attachment_id"], "retry_scheduled", actor, attempt,
|
|
{"error_code": error_code, "detail": detail[:200], "delay_seconds": round(delay, 2)})
|
|
return "retry"
|
|
final_code = error_code if not transient else "retry_exhausted"
|
|
await conn.execute(
|
|
"UPDATE attachment_jobs SET state = 'failed', lease_owner = NULL, lease_until = NULL, finished_at = clock_timestamp(),"
|
|
" last_error = %s, error_code = %s, updated_at = clock_timestamp() WHERE id = %s",
|
|
(detail[:500], final_code, job["id"]),
|
|
)
|
|
await conn.execute(
|
|
"UPDATE attachments SET status = 'failed', error_code = %s, updated_at = clock_timestamp()"
|
|
" WHERE id = %s AND status IN ('queued', 'processing')",
|
|
(final_code, job["attachment_id"]),
|
|
)
|
|
await audit(conn, job["id"], job["attachment_id"], "failed", actor, attempt,
|
|
{"error_code": final_code, "cause": error_code, "detail": detail[:200]})
|
|
return "failed"
|
|
|
|
|
|
async def fail_attempt(conn, job: dict, owner: str, error_code: str, detail: str, transient: bool) -> str:
|
|
"""Returns retry | failed | lost (lease is not ours any more: the new owner decides)."""
|
|
cur = await conn.execute(
|
|
"SELECT id, attachment_id, pipeline_version, attempt, max_attempts, created_at FROM attachment_jobs"
|
|
" WHERE id = %s AND state = 'processing' AND lease_owner = %s FOR UPDATE",
|
|
(job["id"], owner),
|
|
)
|
|
row = await cur.fetchone()
|
|
if row is None:
|
|
return "lost"
|
|
return await _reschedule_or_fail(conn, row, owner, error_code, detail, transient)
|
|
|
|
|
|
async def sweep_leases(conn, actor: str) -> List[str]:
|
|
"""Expired lease = the owner is dead or hung (no heartbeat). Counts as a used attempt."""
|
|
cur = await conn.execute(
|
|
"SELECT id, attachment_id, pipeline_version, attempt, max_attempts, created_at, lease_owner"
|
|
" FROM attachment_jobs WHERE state = 'processing' AND lease_until < clock_timestamp()"
|
|
" ORDER BY lease_until LIMIT 20 FOR UPDATE SKIP LOCKED",
|
|
)
|
|
outcomes = []
|
|
for row in await cur.fetchall():
|
|
outcome = await _reschedule_or_fail(conn, row, actor, "lease_expired",
|
|
"lease of %s expired" % (row["lease_owner"] or "?"), True)
|
|
outcomes.append("%s:%s" % (row["id"], outcome))
|
|
return outcomes
|
|
|
|
|
|
async def replay(conn, attachment_id: str, actor: str, staging_exists) -> dict:
|
|
"""failed -> queued with a fresh attempt budget. Refuses (no-op) for anything that is not failed."""
|
|
cur = await conn.execute(
|
|
"SELECT j.id, j.attachment_id, j.pipeline_version, j.state, j.attempt, j.max_attempts, j.created_at,"
|
|
" a.status AS attachment_status, a.staging_key"
|
|
" FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id"
|
|
" WHERE j.attachment_id = %s ORDER BY j.pipeline_version DESC LIMIT 1 FOR UPDATE OF j, a",
|
|
(attachment_id,),
|
|
)
|
|
job = await cur.fetchone()
|
|
if job is None:
|
|
return {"result": "refused", "reason": "no job for attachment"}
|
|
if job["state"] != "failed" or job["attachment_status"] != "failed":
|
|
await audit(conn, job["id"], job["attachment_id"], "replay_refused", actor, job["attempt"],
|
|
{"state": job["state"], "attachment_status": job["attachment_status"]})
|
|
return {"result": "refused", "reason": "job is %s, attachment is %s" % (job["state"], job["attachment_status"])}
|
|
if not job["staging_key"] or not await staging_exists(job["staging_key"]):
|
|
await audit(conn, job["id"], job["attachment_id"], "replay_refused", actor, job["attempt"], {"reason": "staging_missing"})
|
|
return {"result": "refused", "reason": "staging object is gone (retention), re-upload is required"}
|
|
attempt = job["attempt"] + 1
|
|
await conn.execute(
|
|
"UPDATE attachment_jobs SET state = 'queued', attempt = %s, max_attempts = %s, next_attempt_at = clock_timestamp(),"
|
|
" finished_at = NULL, error_code = NULL, updated_at = clock_timestamp() WHERE id = %s",
|
|
(attempt, attempt + config.JOB_MAX_ATTEMPTS - 1, job["id"]),
|
|
)
|
|
await conn.execute(
|
|
"UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()"
|
|
" WHERE id = %s AND status = 'failed'",
|
|
(job["attachment_id"],),
|
|
)
|
|
await _outbox(conn, job, attempt)
|
|
await audit(conn, job["id"], job["attachment_id"], "replayed", actor, attempt)
|
|
return {"result": "queued", "job_id": str(job["id"]), "attempt": attempt}
|
|
|
|
|
|
async def failed_jobs(conn, limit: int = 50) -> List[dict]:
|
|
cur = await conn.execute(
|
|
"SELECT j.id, j.attachment_id, j.attempt, j.max_attempts, j.error_code, j.last_error, j.updated_at"
|
|
" FROM attachment_jobs j WHERE j.state = 'failed' ORDER BY j.updated_at DESC LIMIT %s",
|
|
(limit,),
|
|
)
|
|
return [
|
|
{"job_id": str(r["id"]), "attachment_id": str(r["attachment_id"]), "attempt": r["attempt"],
|
|
"max_attempts": r["max_attempts"], "error_code": r["error_code"], "last_error": r["last_error"],
|
|
"failed_at": fmt(r["updated_at"])}
|
|
for r in await cur.fetchall()
|
|
]
|
|
|
|
|
|
def utcnow() -> datetime:
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
def older_than(seconds: int) -> datetime:
|
|
return utcnow() - timedelta(seconds=seconds)
|