Files
mtusi2026lab7/src/messenger/jobs.py
T

346 lines
16 KiB
Python

"""PostgreSQL owns job state; broker deliveries are repeatable notifications."""
import json
import logging
import os
import random
import time
from datetime import UTC, datetime
from uuid import uuid4
import redis
from opentelemetry import propagate
from opentelemetry.trace import SpanKind
from . import telemetry
from .config import secret
from .domain import Failure
from .postgres import public
logger = logging.getLogger("messenger.jobs")
STREAM = "attachment-jobs:v1"
GROUP = "image-workers"
def broker_client():
return redis.Redis.from_url(
secret("BROKER_URL"),
decode_responses=False,
socket_connect_timeout=2,
socket_timeout=3,
)
def fault(store, point, attachment_id):
"""Only enabled in the explicit fault-test overlay; never accepts HTTP controls."""
if os.getenv("ENABLE_FAULT_INJECTION") != "1":
return
with store.connection() as conn:
row = conn.execute(
"UPDATE test_faults SET reached_at=now() WHERE id=("
"SELECT id FROM test_faults WHERE point=%s AND reached_at IS NULL "
"AND (attachment_id IS NULL OR attachment_id=%s) ORDER BY id LIMIT 1) RETURNING *",
(point, attachment_id),
).fetchone()
if row is None:
return
logger.warning(json.dumps({"event": "fault_reached", "point": point, "fault_id": row["id"]}))
if row["action"] == "crash":
os._exit(86)
if row["action"] == "error":
raise RuntimeError("injected_transient_failure")
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
with store.connection() as conn:
released = conn.execute(
"SELECT released FROM test_faults WHERE id=%s", (row["id"],)
).fetchone()
if released and released["released"]:
return
time.sleep(0.1)
raise RuntimeError("fault_barrier_timeout")
class Jobs:
def __init__(self, store):
self.store = store
self.attempt_limit = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
self.lease_seconds = int(os.getenv("JOB_LEASE_SECONDS", "45"))
if not 1 <= self.attempt_limit <= 20 or not 5 <= self.lease_seconds <= 300:
raise RuntimeError("Invalid job retry/lease configuration")
def enqueue(self, conn, attachment_id, source_key, version=1):
job_id = str(uuid4())
conn.execute(
"INSERT INTO attachment_jobs(id,attachment_id,pipeline_version,source_key,state,attempt_limit,traceparent,tracestate,accepted_at) "
"VALUES (%s,%s,%s,%s,'queued',%s,%s,%s,clock_timestamp())",
(
job_id,
attachment_id,
version,
source_key,
self.attempt_limit,
telemetry.carrier().get("traceparent"),
telemetry.carrier().get("tracestate"),
),
)
conn.execute("INSERT INTO job_outbox(job_id) VALUES (%s)", (job_id,))
self.audit(conn, job_id, "accepted", 0)
return job_id
@staticmethod
def audit(conn, job_id, event, attempt):
conn.execute(
"INSERT INTO job_audit(job_id,event,attempt) VALUES (%s,%s,%s)",
(job_id, event, attempt),
)
def publish_one(self, broker):
with self.store.connection() as conn, conn.transaction():
job = conn.execute(
"SELECT j.* FROM job_outbox o JOIN attachment_jobs j ON j.id=o.job_id "
"WHERE o.published_at IS NULL AND j.available_at<=now() "
"ORDER BY j.available_at LIMIT 1 FOR UPDATE OF o SKIP LOCKED"
).fetchone()
if job is None:
return False
if job["state"] == "queued":
body = {
"schema_version": 1,
"job_id": str(job["id"]),
"type": "attachment.process.v1",
"attachment_id": str(job["attachment_id"]),
"pipeline_version": job["pipeline_version"],
"attempt": job["attempt"] + 1,
"created_at": public({"v": job["created_at"]})["v"],
}
# XADD response with appendfsync=always is the broker acceptance boundary.
parent = {
key: job.get(key) for key in ("traceparent", "tracestate") if job.get(key)
}
with telemetry.operation(
"attachments publish", context=propagate.extract(parent), kind=SpanKind.PRODUCER
):
body.update(telemetry.carrier())
broker.xadd(STREAM, {"body": json.dumps(body)})
fault(self.store, "after_publish", job["attachment_id"])
conn.execute("UPDATE job_outbox SET published_at=now() WHERE job_id=%s", (job["id"],))
return True
def claim(self, job_id, attachment_id, version):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if attachment is None:
return None
job = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job_id,)
).fetchone()
if (
job is None
or str(job["attachment_id"]) != str(attachment_id)
or job["pipeline_version"] != version
):
return None
if attachment["pipeline_version"] != version:
conn.execute(
"UPDATE attachment_jobs SET state='superseded',updated_at=now() WHERE id=%s AND state NOT IN ('ready','superseded')",
(job_id,),
)
return None
if job["state"] != "queued":
return None
lease_id = str(uuid4())
job = conn.execute(
"UPDATE attachment_jobs SET state='processing',attempt=attempt+1,lease_id=%s,"
"lease_until=now()+(%s * interval '1 second'),updated_at=now() "
"WHERE id=%s AND available_at<=now() RETURNING *",
(lease_id, self.lease_seconds, job_id),
).fetchone()
if job is None:
return None
conn.execute(
"UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s",
(attachment_id,),
)
self.audit(conn, job_id, "claimed", job["attempt"])
job["source_sha256"] = attachment["sha256"]
job["source_size"] = attachment["size_bytes"]
job["source_content_type"] = attachment["content_type"]
return job
def complete(self, job, object_key, variants):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (job["attachment_id"],)
).fetchone()
current = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job["id"],)
).fetchone()
if (
attachment["pipeline_version"] != job["pipeline_version"]
or current["state"] != "processing"
or current["lease_id"] != job["lease_id"]
):
self.audit(conn, job["id"], "stale_publish_rejected", job["attempt"])
return False
conn.execute(
"UPDATE attachments SET status='ready',error_code=NULL,object_key=%s,variants=%s::jsonb,updated_at=now() WHERE id=%s",
(object_key, json.dumps(variants), job["attachment_id"]),
)
conn.execute(
"UPDATE attachment_jobs SET state='ready',lease_until=NULL,error_code=NULL,updated_at=now() WHERE id=%s",
(job["id"],),
)
self.audit(conn, job["id"], "published", job["attempt"])
t = telemetry.current()
if t:
t.ready_duration.record(
(datetime.now(UTC) - job["accepted_at"]).total_seconds(),
{"job_type": "attachment.process.v1"},
)
return True
def fail(self, job, code, permanent=False):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (job["attachment_id"],)
).fetchone()
current = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job["id"],)
).fetchone()
if (
attachment["pipeline_version"] != job["pipeline_version"]
or current["lease_id"] != job["lease_id"]
or current["state"] != "processing"
):
return
if permanent or current["attempt"] >= current["attempt_limit"]:
final_code = code if permanent else "retry_exhausted"
self._failed(conn, current, final_code)
else:
delay = min(30, 2 ** (current["attempt"] - 1)) + random.uniform(0, 0.5)
conn.execute(
"UPDATE attachment_jobs SET state='queued',error_code=%s,lease_until=NULL,"
"available_at=now()+(%s * interval '1 second'),updated_at=now() WHERE id=%s",
(code, delay, job["id"]),
)
conn.execute(
"UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],)
)
conn.execute(
"UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",
(job["attachment_id"],),
)
self.audit(conn, job["id"], "retry_scheduled", job["attempt"])
def _failed(self, conn, job, code):
conn.execute(
"UPDATE attachment_jobs SET state='failed',error_code=%s,lease_until=NULL,updated_at=now() WHERE id=%s",
(code, job["id"]),
)
conn.execute(
"UPDATE attachments SET status='failed',error_code=%s,updated_at=now() WHERE id=%s",
(code, job["attachment_id"]),
)
conn.execute(
"INSERT INTO failed_jobs(job_id,error_code) VALUES (%s,%s) "
"ON CONFLICT(job_id) DO UPDATE SET error_code=excluded.error_code,failed_at=now()",
(job["id"], code),
)
self.audit(conn, job["id"], "failed:" + code, job["attempt"])
def recover_one(self):
with self.store.connection() as conn, conn.transaction():
candidate = conn.execute(
"SELECT a.id FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id "
"WHERE j.state='processing' AND j.lease_until<now() LIMIT 1 FOR UPDATE OF a SKIP LOCKED"
).fetchone()
if candidate is None:
return False
job = conn.execute(
"SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
"WHERE j.attachment_id=%s AND j.state='processing' AND j.lease_until<now() "
"AND j.pipeline_version=a.pipeline_version FOR UPDATE OF j",
(candidate["id"],),
).fetchone()
if job is None:
return False
if job["attempt"] >= job["attempt_limit"]:
self._failed(conn, job, "retry_exhausted")
else:
conn.execute(
"UPDATE attachment_jobs SET state='queued',lease_until=NULL,available_at=now(),updated_at=now() WHERE id=%s",
(job["id"],),
)
conn.execute(
"UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",
(job["attachment_id"],),
)
conn.execute(
"UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],)
)
self.audit(conn, job["id"], "lease_recovered", job["attempt"])
return True
def replay(self, attachment_id, storage):
with self.store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if not a or a["status"] != "failed":
raise Failure(409, "Повтор разрешён только для failed")
job = conn.execute(
"SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE",
(attachment_id, a["pipeline_version"]),
).fetchone()
if not job["source_key"] or not storage.exists(job["source_key"]):
raise Failure(409, "Источник больше недоступен")
fault(self.store, "replay_before_commit", attachment_id)
conn.execute(
"UPDATE attachment_jobs SET state='queued',attempt_limit=attempt+%s,available_at=now(),error_code=NULL,updated_at=now() WHERE id=%s",
(self.attempt_limit, job["id"]),
)
conn.execute(
"UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s",
(attachment_id,),
)
conn.execute("UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],))
conn.execute(
"UPDATE failed_jobs SET replay_count=replay_count+1 WHERE job_id=%s", (job["id"],)
)
self.audit(conn, job["id"], "operator_replay", job["attempt"])
return str(job["id"])
def reprocess(self, attachment_id, version, storage):
if version not in (1, 2):
raise Failure(400, "Поддерживаются версии pipeline 1 и 2")
with self.store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if not a:
raise Failure(404, "Вложение отсутствует")
if version <= a["pipeline_version"]:
raise Failure(409, "Нужна более новая версия pipeline")
source = a["object_key"] if a["status"] == "ready" else a["stage_key"]
if not source or not storage.exists(source):
raise Failure(409, "Источник больше недоступен")
if a["status"] == "ready" and a["stage_key"] and a["stage_key"].startswith("staging/"):
# A worker can be paused after publishing ready but before its
# staging cleanup. Do not orphan that key when choosing final v1
# as the new source. Delete stays under the same attachment lock;
# a storage failure leaves the ready version unchanged.
fault(self.store, "reprocess_before_staging_delete", attachment_id)
storage.delete(a["stage_key"])
conn.execute(
"UPDATE attachment_jobs SET state='superseded',updated_at=now() WHERE attachment_id=%s AND state IN ('queued','processing','failed')",
(attachment_id,),
)
conn.execute(
"UPDATE attachments SET pipeline_version=%s,status='queued',variants='[]',error_code=NULL,stage_key=%s,updated_at=now() WHERE id=%s",
(version, source, attachment_id),
)
return self.enqueue(conn, attachment_id, source, version)