Files
mtusi2026lab7/jobs.py
T

441 lines
22 KiB
Python

"""Outbox relay and image pipeline worker for lab 5."""
from __future__ import annotations
import hashlib
import io
import json
import logging
import os
import random
import signal
import threading
import time
import uuid
import warnings
from datetime import datetime, timezone
import boto3
import pika
import psycopg
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from PIL import Image, ImageOps, UnidentifiedImageError
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from security_runtime import CA, client_context, database_url
from telemetry import JOB_TYPE, OTEL, SpanKind, parent_context, trace_carrier
LOG = logging.getLogger("attachment-jobs")
QUEUE = os.getenv("JOB_QUEUE", "attachment-processing-v1")
BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
LEASE_SECONDS = int(os.getenv("JOB_LEASE_SECONDS", "120"))
MAX_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
def utcnow():
return datetime.now(timezone.utc)
def pool():
timeout = int(os.getenv("DB_STATEMENT_TIMEOUT_MS", "1500"))
return ConnectionPool(database_url(), min_size=1, max_size=4, timeout=5,
kwargs={"row_factory": dict_row, "options": f"-c statement_timeout={timeout}"},
open=True)
def broker_parameters():
return pika.ConnectionParameters(
host="rabbitmq", port=5671, virtual_host="/messenger",
credentials=pika.credentials.ExternalCredentials(),
ssl_options=pika.SSLOptions(client_context(), "rabbitmq"),
blocked_connection_timeout=15, socket_timeout=5, stack_timeout=10,
)
def s3_client():
return boto3.client(
"s3", endpoint_url="https://rustfs:9000", region_name="us-east-1",
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
verify=CA,
config=Config(connect_timeout=3, read_timeout=10, retries={"max_attempts": 1},
s3={"addressing_style": "path"}),
)
def outbox_loop(stop_event: threading.Event):
"""Publish committed intentions with confirms; duplicates are expected."""
while not stop_event.is_set():
db = None
connection = None
try:
db = pool()
OTEL.set_pool("outbox", db)
connection = pika.BlockingConnection(broker_parameters())
channel = connection.channel()
channel.confirm_delivery()
while not stop_event.is_set():
item = None
with db.connection() as conn:
with conn.transaction():
item = conn.execute("""SELECT job_id,attempt,attachment_id,pipeline_version,traceparent,tracestate FROM job_outbox
WHERE published_at IS NULL AND available_at<=now()
ORDER BY available_at,created_at LIMIT 1 FOR UPDATE SKIP LOCKED""").fetchone()
if item:
publish_job(channel, item)
conn.execute("UPDATE job_outbox SET published_at=now() WHERE job_id=%s AND attempt=%s",
(item["job_id"], item["attempt"]))
if not item:
connection.process_data_events(time_limit=0)
# Watchdog handles leases even if a broker delivery was acknowledged after a worker crash.
recover_expired(db)
stop_event.wait(0.4)
except Exception as exc:
LOG.warning("outbox relay reconnecting (%s)", type(exc).__name__)
stop_event.wait(1.0)
finally:
if connection and connection.is_open:
connection.close()
if db:
db.close()
def publish_job(channel, item):
carrier = {key: item[key] for key in ("traceparent", "tracestate") if item[key]}
attributes = {
"messaging.destination.name": QUEUE, "messaging.system": "rabbitmq",
"job_id": str(item["job_id"]), "attempt": item["attempt"],
}
message = {
"schema_version": 1, "job_id": str(item["job_id"]), "type": JOB_TYPE,
"attachment_id": str(item["attachment_id"]), "pipeline_version": item["pipeline_version"],
"attempt": item["attempt"], "created_at": utcnow().isoformat().replace("+00:00", "Z"),
}
with OTEL.span(f"{QUEUE} publish", SpanKind.PRODUCER, attributes, parent_context(carrier)):
# When telemetry is disabled, an existing outbox carrier can still be forwarded.
message.update(trace_carrier() or carrier)
channel.basic_publish(
exchange="", routing_key=QUEUE, body=json.dumps(message, separators=(",", ":")).encode(),
properties=pika.BasicProperties(content_type="application/json", delivery_mode=2,
message_id=message["job_id"], type=JOB_TYPE), mandatory=True,
)
OTEL.event("job_published", job_id=message["job_id"], attempt=message["attempt"])
def recover_expired(db):
"""Re-enqueue expired leases and delayed rows using an atomic outbox write."""
with db.connection() as conn:
with conn.transaction():
rows = conn.execute("""SELECT id,job_id,pipeline_version,attempts,status FROM attachments
WHERE status='processing' AND lease_until<now()
ORDER BY updated_at LIMIT 100 FOR UPDATE SKIP LOCKED""").fetchall()
for row in rows:
if row["attempts"] >= MAX_ATTEMPTS:
conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',lease_until=NULL,updated_at=now() WHERE id=%s", (row["id"],))
conn.execute(
"INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event) VALUES (%s,%s,%s,'retry_exhausted')",
(row["id"], row["job_id"], row["pipeline_version"]),
)
continue
attempt = row["attempts"] + 1
conn.execute("UPDATE attachments SET status='queued',lease_until=NULL,next_attempt_at=NULL,updated_at=now() WHERE id=%s", (row["id"],))
conn.execute("""INSERT INTO job_outbox(job_id,attempt,attachment_id,pipeline_version,traceparent,tracestate)
SELECT job_id,%s,attachment_id,pipeline_version,traceparent,tracestate
FROM job_outbox WHERE job_id=%s AND attempt=%s ON CONFLICT DO NOTHING""",
(attempt, row["job_id"], row["attempts"]))
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event) VALUES (%s,%s,%s,'lease_recovered')",
(row["id"], row["job_id"], row["pipeline_version"]))
def fit_within(image, limit):
largest = max(image.size)
if largest <= limit:
return image
size = tuple(max(1, dimension * limit // largest) for dimension in image.size)
return image.resize(size, Image.Resampling.LANCZOS)
def transform_image(raw: bytes, version: int):
"""Deterministic, metadata-free variants for a versioned pipeline."""
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", Image.DecompressionBombWarning)
with Image.open(io.BytesIO(raw), formats=("PNG", "JPEG")) as source:
if source.width * source.height > MAX_PIXELS:
raise PermanentJobError("image_too_large")
ImageOps.exif_transpose(source, in_place=True)
source.load()
if "A" in source.getbands() or "transparency" in source.info:
rgba = source if source.mode == "RGBA" else source.convert("RGBA")
if rgba is not source:
source.close()
base = Image.new("RGB", rgba.size, "white")
alpha = rgba.getchannel("A")
base.paste(rgba, mask=alpha)
alpha.close()
rgba.close()
else:
base = source.convert("RGB")
source.close()
except Image.DecompressionBombError as exc:
raise PermanentJobError("image_too_large") from exc
except (UnidentifiedImageError, OSError, ValueError) as exc:
raise PermanentJobError("invalid_image") from exc
outputs = []
thumb = fit_within(base, 256)
outputs.append(("thumbnail", "image/jpeg", thumb, {"format": "JPEG", "quality": 90 if version >= 3 else 85, "optimize": True}))
if version >= 2:
crop = ImageOps.fit(base, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5))
outputs.append(("crop", "image/jpeg", crop, {"format": "JPEG", "quality": 82, "optimize": True}))
optimized = fit_within(base, 1280)
outputs.append(("optimized", "image/webp", optimized, {"format": "WEBP", "quality": 82, "method": 4}))
result = []
for name, content_type, image, options in outputs:
stream = io.BytesIO()
image.save(stream, **options)
data = stream.getvalue()
result.append({"name": name, "content_type": content_type, "size_bytes": len(data), "width": image.width,
"height": image.height, "sha256": hashlib.sha256(data).hexdigest(), "bytes": data})
return raw, result
class PermanentJobError(Exception):
def __init__(self, code):
self.code = code
super().__init__(code)
def cleanup_staging(s3, row):
if row["staging_key"]:
try:
with OTEL.dependency("s3", "delete staging"):
s3.delete_object(Bucket=BUCKET, Key=row["staging_key"])
except (BotoCoreError, ClientError):
LOG.warning("staging cleanup deferred for %s", row["id"])
def owns_attempt(row, job_id, version, attempt):
return row and (row["job_id"], row["pipeline_version"], row["attempts"], row["status"]) == (
job_id, version, attempt, "processing"
)
def process_payload(db, s3, payload, fault=None):
"""One idempotent delivery. fault is used only by deterministic tests."""
required = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
if not isinstance(payload, dict) or not required <= payload.keys() or payload.keys() - required - {"traceparent", "tracestate"}:
raise PermanentJobError("invalid_job")
if payload.get("schema_version") != 1 or payload.get("type") != "attachment.process.v1":
raise PermanentJobError("invalid_job")
try:
attachment_id = uuid.UUID(payload["attachment_id"])
job_id = uuid.UUID(payload["job_id"])
except (ValueError, TypeError, AttributeError) as exc:
raise PermanentJobError("invalid_job") from exc
job_version = payload["pipeline_version"]
attempt = payload["attempt"]
if type(job_version) is not int or job_version < 1 or type(attempt) is not int or not 1 <= attempt <= MAX_ATTEMPTS:
raise PermanentJobError("invalid_job")
with OTEL.connection(db, "claim job") as conn:
with conn.transaction():
row = conn.execute("SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)).fetchone()
if not row:
return "orphan_job"
if job_version != row["pipeline_version"] or job_id != row["job_id"]:
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event) VALUES (%s,%s,%s,'stale_ignored')",
(attachment_id, job_id, job_version))
return "stale_ignored"
if row["status"] == "ready":
cleanup_staging(s3, row)
return "duplicate_ready"
if row["status"] == "processing":
return "already_leased"
if row["status"] == "failed":
return "already_failed"
if attempt <= row["attempts"]:
return "stale_attempt"
scheduled = conn.execute(
"SELECT 1 FROM job_outbox WHERE job_id=%s AND attempt=%s AND available_at<=now()",
(job_id, attempt),
).fetchone()
if not scheduled:
return "unscheduled_attempt"
conn.execute("UPDATE attachments SET status='processing',attempts=%s,lease_until=now()+(%s * interval '1 second'),next_attempt_at=NULL,error_code=NULL,updated_at=now() WHERE id=%s",
(attempt, LEASE_SECONDS, attachment_id))
if fault:
fault("before_effect", payload)
try:
with OTEL.dependency("s3", "get staging"):
source_obj = s3.get_object(Bucket=BUCKET, Key=row["staging_key"])
with source_obj["Body"] as body:
raw = body.read(int(row["size_bytes"]) + 1)
if len(raw) != row["size_bytes"] or hashlib.sha256(raw).hexdigest() != row["sha256"]:
raise PermanentJobError("staging_integrity_error")
with OTEL.span("transform image"):
_, variants = transform_image(raw, job_version)
original_key = f"attachments/{attachment_id}/v{job_version}/original"
with OTEL.dependency("s3", "put original"):
s3.put_object(Bucket=BUCKET, Key=original_key, Body=raw, ContentType=row["content_type"], Metadata={"sha256": row["sha256"]})
if fault:
fault("after_original", payload)
public_variants = []
for variant in variants:
key = f"attachments/{attachment_id}/v{job_version}/{variant['name']}"
with OTEL.dependency("s3", "put variant"):
s3.put_object(Bucket=BUCKET, Key=key, Body=variant["bytes"], ContentType=variant["content_type"],
Metadata={"sha256": variant["sha256"], "pipeline-version": str(job_version)})
public_variants.append({k: variant[k] for k in ("name", "content_type", "size_bytes", "width", "height", "sha256")})
if fault:
fault("before_commit", payload)
with OTEL.connection(db, "commit ready") as conn:
with conn.transaction():
current = conn.execute("SELECT pipeline_version,job_id,attempts,status FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)).fetchone()
if not owns_attempt(current, job_id, job_version, attempt):
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event) VALUES (%s,%s,%s,'stale_completion_blocked')",
(attachment_id, job_id, job_version))
return "stale_completion_blocked"
result_row = conn.execute("""UPDATE attachments SET object_key=%s,status='ready',variants=%s::jsonb,error_code=NULL,
lease_until=NULL,next_attempt_at=NULL,updated_at=now(),
slo_first_ready_at=coalesce(slo_first_ready_at,clock_timestamp())
WHERE id=%s AND pipeline_version=%s RETURNING slo_first_ready_at""",
(original_key, json.dumps(public_variants), attachment_id, job_version)).fetchone()
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event,detail) VALUES (%s,%s,%s,'ready',jsonb_build_object('variants',%s::integer))",
(attachment_id, job_id, job_version, len(public_variants)))
if OTEL.enabled and row["slo_accepted_at"] and not row["slo_first_ready_at"]:
elapsed = (result_row["slo_first_ready_at"] - row["slo_accepted_at"]).total_seconds()
OTEL.ready_duration.record(max(0, elapsed), {"job_type": JOB_TYPE})
if fault:
fault("after_commit", payload)
cleanup_staging(s3, row)
return "ready"
except PermanentJobError as exc:
with OTEL.connection(db, "commit failure") as conn:
with conn.transaction():
current = conn.execute("SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)).fetchone()
if not owns_attempt(current, job_id, job_version, attempt):
return "stale_completion_blocked"
conn.execute("UPDATE attachments SET status='failed',error_code=%s,lease_until=NULL,updated_at=now() WHERE id=%s AND pipeline_version=%s AND status<>'ready'",
(exc.code, attachment_id, job_version))
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event,detail) VALUES (%s,%s,%s,'failed',jsonb_build_object('code',%s::text))",
(attachment_id, job_id, job_version, exc.code))
return "failed"
except (BotoCoreError, ClientError, psycopg.Error, TimeoutError, RuntimeError) as exc:
delay = min(300, 2 ** min(attempt, 8)) * random.uniform(0.75, 1.25)
current_carrier = trace_carrier()
with OTEL.connection(db, "schedule retry") as conn:
with conn.transaction():
current = conn.execute("SELECT attempts,pipeline_version,job_id,status FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)).fetchone()
if current and current["status"] == "ready":
return "ready_after_crash"
if not owns_attempt(current, job_id, job_version, attempt):
return "stale_completion_blocked"
if attempt < MAX_ATTEMPTS:
next_attempt = attempt + 1
next_job = row["job_id"]
conn.execute("UPDATE attachments SET status='queued',attempts=%s,lease_until=NULL,next_attempt_at=now()+(%s * interval '1 second'),error_code='temporary_failure',updated_at=now() WHERE id=%s",
(attempt, delay, attachment_id))
conn.execute("""INSERT INTO job_outbox(job_id,attempt,attachment_id,pipeline_version,available_at,traceparent,tracestate)
VALUES (%s,%s,%s,%s,now()+(%s * interval '1 second'),%s,%s) ON CONFLICT DO NOTHING""",
(next_job, next_attempt, attachment_id, job_version, delay,
current_carrier.get("traceparent", payload.get("traceparent")),
current_carrier.get("tracestate", payload.get("tracestate"))))
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event,detail) VALUES (%s,%s,%s,'retry_scheduled',jsonb_build_object('attempt',%s::integer,'delay_seconds',%s::double precision))",
(attachment_id, job_id, job_version, next_attempt, round(delay, 2)))
else:
conn.execute("UPDATE attachments SET status='failed',lease_until=NULL,error_code='retry_exhausted',updated_at=now() WHERE id=%s",
(attachment_id,))
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event) VALUES (%s,%s,%s,'retry_exhausted')",
(attachment_id, job_id, job_version))
OTEL.event("job_attempt_error", logging.WARNING, job_id=str(job_id), attempt=attempt, error_type=type(exc).__name__)
return "retry_scheduled" if attempt < MAX_ATTEMPTS else "failed"
def delivery(channel, method, body, db, s3, fault):
started = time.monotonic()
OTEL.worker_busy = 1
attributes = {"messaging.destination.name": QUEUE, "messaging.system": "rabbitmq"}
event_fields = {}
payload = None
try:
try:
payload = json.loads(body)
except (ValueError, UnicodeError):
pass
carrier = {}
if isinstance(payload, dict):
carrier = {key: payload[key] for key in ("traceparent", "tracestate")
if isinstance(payload.get(key), str) and len(payload[key]) <= 512}
try:
event_fields["job_id"] = str(uuid.UUID(payload.get("job_id", "")))
except (ValueError, TypeError, AttributeError):
pass
attempt = payload.get("attempt")
if type(attempt) is int and 1 <= attempt <= MAX_ATTEMPTS:
event_fields["attempt"] = attempt
with OTEL.span(f"{QUEUE} process", SpanKind.CONSUMER, {**attributes, **event_fields}, parent_context(carrier)) as span:
outcome = "delivery_error"
try:
timeout = max(1, int(os.getenv("JOB_TIMEOUT_SECONDS", "60")))
def deadline(_signal, _frame):
raise TimeoutError("job timeout")
signal.signal(signal.SIGALRM, deadline)
signal.setitimer(signal.ITIMER_REAL, timeout)
outcome = process_payload(db, s3, payload, fault=fault)
except PermanentJobError:
outcome = "invalid_job"
except Exception as exc:
OTEL.event("delivery_error", logging.ERROR, error_type=type(exc).__name__, **event_fields)
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
OTEL.finish_job(span, outcome, started, event_fields)
if outcome == "delivery_error":
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
else:
channel.basic_ack(delivery_tag=method.delivery_tag)
finally:
if OTEL.enabled:
OTEL.worker_busy_time.add(time.monotonic() - started)
OTEL.worker_busy = 0
def run_worker(fault=None):
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO").upper(), format="%(asctime)s %(levelname)s %(message)s")
db = pool()
s3 = s3_client()
OTEL.start("messenger-worker")
OTEL.set_pool("worker", db)
concurrency = max(1, min(8, int(os.getenv("WORKER_CONCURRENCY", "1"))))
stop = threading.Event()
def shutdown(_sig, _frame): stop.set()
signal.signal(signal.SIGTERM, shutdown)
signal.signal(signal.SIGINT, shutdown)
while not stop.is_set():
connection = None
try:
recover_expired(db)
connection = pika.BlockingConnection(broker_parameters())
channel = connection.channel()
channel.basic_qos(prefetch_count=concurrency)
def on_message(ch, method, properties, body):
delivery(ch, method, body, db, s3, fault)
channel.basic_consume(queue=QUEUE, on_message_callback=on_message, auto_ack=False)
while not stop.is_set() and connection.is_open:
connection.process_data_events(time_limit=1)
recover_expired(db)
except Exception as exc:
LOG.warning("worker reconnecting (%s)", type(exc).__name__)
stop.wait(1)
finally:
if connection and connection.is_open:
connection.close()
db.close()
OTEL.close()
if __name__ == "__main__":
run_worker()