Files
mtusi2026lab6/app/pipeline.py
T

183 lines
8.2 KiB
Python

"""Shared durable-job plumbing, deliberately separate from the HTTP API."""
from __future__ import annotations
import json
import logging
import math
import os
import random
import re
from datetime import datetime
from uuid import UUID
import aio_pika
from sqlalchemy import text
from app.config import read_value
from app.db import SessionLocal
from app import advanced
from app.telemetry import emit, span
from app.trace_context import carrier, parent_context
from opentelemetry.trace import SpanKind
logger = logging.getLogger("messenger.pipeline")
QUEUE = "attachments"
MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
LEASE_SECONDS = int(os.getenv("JOB_LEASE_SECONDS", "120"))
IMAGE_TIMEOUT = float(os.getenv("JOB_TIMEOUT_SECONDS", "30"))
TOTAL_TIMEOUT = float(os.getenv("JOB_TOTAL_TIMEOUT_SECONDS", "90"))
RETENTION_SECONDS = int(os.getenv("STAGING_RETENTION_SECONDS", "604800"))
RETRY_BASE_SECONDS = float(os.getenv("RETRY_BASE_SECONDS", "1"))
if (MAX_ATTEMPTS < 1 or not math.isfinite(IMAGE_TIMEOUT) or IMAGE_TIMEOUT <= 0
or not 0 < TOTAL_TIMEOUT < LEASE_SECONDS):
raise RuntimeError("Invalid job limits; total timeout must be below lease.")
if not math.isfinite(RETRY_BASE_SECONDS) or RETRY_BASE_SECONDS <= 0:
raise RuntimeError("RETRY_BASE_SECONDS must be finite and positive.")
def retry_delay(attempts_run: int) -> float:
# Equal jitter: never zero, capped exponential delay, one durable due date.
upper = min(60.0, RETRY_BASE_SECONDS * 2 ** min(max(attempts_run - 1, 0), 10))
return random.uniform(upper / 2, upper)
async def broker_channel():
connection = await aio_pika.connect_robust(read_value("BROKER_URL"), timeout=5)
try:
channel = await connection.channel(publisher_confirms=True, on_return_raises=True)
await channel.set_qos(prefetch_count=1)
dead = await channel.declare_exchange("attachments.dead", aio_pika.ExchangeType.FANOUT,
durable=True)
dlq = await channel.declare_queue("attachments.dlq", durable=True)
await dlq.bind(dead)
queue = await channel.declare_queue(
QUEUE, durable=True, arguments={"x-dead-letter-exchange": "attachments.dead"}
)
return connection, channel, queue
except BaseException:
await connection.close()
raise
def envelope(row) -> dict:
job = {
"schema_version": 1, "job_id": str(row["job_id"]),
"type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]),
"pipeline_version": int(row.get("pipeline_version", 1)),
"attempt": int(row["attempt"]),
"created_at": row["created_at"].isoformat().replace("+00:00", "Z"),
}
job.update({name: row[name] for name in ("traceparent", "tracestate") if row.get(name)})
return job
def parse_envelope(raw: bytes) -> dict:
job = json.loads(raw)
required = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version",
"attempt", "created_at"}
if not isinstance(job, dict) or not required <= job.keys() or (
job.keys() - required - {"traceparent", "tracestate"}
):
raise ValueError("invalid job fields")
if type(job["schema_version"]) is not int or job["schema_version"] != 1 or job["type"] != "attachment.process.v1":
raise ValueError("unsupported job schema")
if type(job["attempt"]) is not int or job["attempt"] < 1:
raise ValueError("invalid attempt")
if type(job["pipeline_version"]) is not int or job["pipeline_version"] != 1:
raise ValueError("unsupported pipeline")
UUID(job["job_id"])
UUID(job["attachment_id"])
if datetime.fromisoformat(job["created_at"].replace("Z", "+00:00")).tzinfo is None:
raise ValueError("job timestamp must include timezone")
if "traceparent" in job and not re.fullmatch(
r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}", job["traceparent"]
):
raise ValueError("invalid traceparent")
if "tracestate" in job and (not isinstance(job["tracestate"], str) or
len(job["tracestate"]) > 512):
raise ValueError("invalid tracestate")
return job
async def publish(channel, job: dict) -> None:
with span("attachments publish", kind=SpanKind.PRODUCER, parent=parent_context(job), attributes={
"messaging.system": "rabbitmq", "messaging.destination.name": QUEUE,
"messaging.operation": "publish", "job_id": job["job_id"], "attempt": job["attempt"],
}):
# The confirmed envelope names this producer span as the consumer's
# parent. Durable outbox remains unchanged if confirmation is lost.
outgoing = {**job, **carrier()}
await channel.default_exchange.publish(
aio_pika.Message(json.dumps(outgoing).encode("utf-8"), content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=job["job_id"]),
routing_key=QUEUE, mandatory=True, timeout=5,
)
emit("job.published", job_id=job["job_id"], attempt=job["attempt"], queue=QUEUE)
async def event(db, row, name: str, detail: str = "") -> None:
await db.execute(text("""
INSERT INTO job_events(attachment_id,event,attempt,detail)
VALUES (:id,:event,:attempt,:detail)
"""), {"id": row["id"], "attempt": row["attempt"], "event": name, "detail": detail})
async def arm_from_env(variable: str) -> None:
point = os.getenv(variable, "")
if point:
async with SessionLocal() as db:
await db.execute(text("""
INSERT INTO fault_injections(point,remaining) VALUES (:point,1)
ON CONFLICT (point) DO NOTHING
"""), {"point": point})
await db.commit()
async def crash_if_armed(point: str) -> None:
async with SessionLocal() as db:
result = await db.execute(text("""
UPDATE fault_injections SET remaining=remaining-1,hits=hits+1,updated_at=now()
WHERE point=:point AND remaining>0 RETURNING point
"""), {"point": point})
hit = result.first() is not None
await db.commit()
if hit:
logger.error("FAULT: %s (one-shot durable hit)", point)
os._exit(70)
async def retry_or_fail(db, row, code: str, *, permanent: bool = False) -> None:
"""Caller owns the attachment row lock. Commit before acking old delivery."""
if permanent or row["attempts_run"] >= MAX_ATTEMPTS:
final_code = code if permanent else "retry_exhausted"
await db.execute(text("""
UPDATE attachments SET status='failed',error_code=:code,
lease_token=NULL,lease_until=NULL,updated_at=now()
WHERE id=:id
"""), {"id": row["id"], "code": final_code})
await event(db, row, "failed", final_code)
logger.warning("failed attachment=%s code=%s", row["id"], final_code)
return
delay = retry_delay(row["attempts_run"])
# A consumer retry continues from its active span. Lease recovery may have
# no active span, so retain the context durably recorded by the old claim.
context = carrier() or {name: row.get(name) for name in ("traceparent", "tracestate")}
await db.execute(text("""
UPDATE attachments SET status='queued',error_code=NULL,attempt=attempt+1,
lease_token=NULL,lease_until=NULL,
traceparent=:traceparent,tracestate=:tracestate,
next_attempt_at=now()+make_interval(secs => CAST(:delay AS double precision)),
updated_at=now() WHERE id=:id
"""), {"id": row["id"], "delay": delay,
"traceparent": context.get("traceparent"), "tracestate": context.get("tracestate")})
await db.execute(text("""
INSERT INTO outbox(job_id,attachment_id,attempt,available_at,traceparent,tracestate)
SELECT job_id,id,attempt,next_attempt_at,traceparent,tracestate FROM attachments WHERE id=:id
"""), {"id": row["id"]})
await event(db, row, "retry", f"{code}; delay={delay:.3f}s")
logger.info("retry attachment=%s after=%.3fs", row["id"], delay)
advanced.retries.add(1, {"job_type": "attachment.process.v1"})
emit("job.retry", job_id=str(row["job_id"]), attachment_id=str(row["id"]),
attempt=row["attempt"] + 1, outcome="retry", queue=QUEUE)