"""Worker: durable-stream consumer that publishes originals and thumbnails. Effects are idempotent by (attachment_id, pipeline_version, variant). A redelivered job for an already-ready attachment is a no-op followed by XACK. The broker message carries only IDs and counters — never bytes, S3 keys derived from client input, or credentials. """ import hashlib import io import json import logging import os import uuid import time from app import broker, s3, telemetry from app.db import db log = logging.getLogger("messenger.worker") MAX_ATTEMPTS = int(os.environ.get("MAX_ATTEMPTS", "5")) CONSUMER = os.environ.get("BROKER_CONSUMER", "worker-1") PIPELINE_VERSION = 1 def make_thumbnail(data): from PIL import Image, ImageOps image = Image.open(io.BytesIO(data)) image = ImageOps.exif_transpose(image) if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info): rgba = image.convert("RGBA") background = Image.new("RGB", rgba.size, (255, 255, 255)) background.paste(rgba, mask=rgba.getchannel("A")) image = background else: image = image.convert("RGB") # Fit into 256x256, preserve aspect ratio, never upscale. No EXIF is written. image.thumbnail((256, 256), Image.Resampling.LANCZOS) if image.width < 1 or image.height < 1: raise ValueError("invalid thumbnail size") output = io.BytesIO() image.save(output, format="JPEG", quality=85) return output.getvalue(), image.width, image.height def _update(attachment_id, **fields): assignments = ", ".join("%s = %s" % (k, v) for k, v in fields.items()) with db.transaction() as conn: conn.execute( "UPDATE attachments SET " + assignments + ", updated_at = clock_timestamp() WHERE id = %s", (uuid.UUID(attachment_id),), ) def _process(job): attachment_id = job["attachment_id"] attempt = int(job.get("attempt", 1)) with db.connection() as conn: row = conn.execute("SELECT * FROM attachments WHERE id = %s", (attachment_id,)).fetchone() if row is None: log.warning("job for unknown attachment %s", attachment_id) return "unknown" if row["status"] == "ready" and any(v.get("name") == "thumbnail" for v in (row["variants"] or [])): log.info("already ready: %s — no-op", attachment_id) return "noop" # at-least-once redelivery: identical effect, no duplicate variant _update(attachment_id, status="'processing'", attempts=str(attempt)) try: original, content_type = s3.get_object(row["object_key"]) thumb, width, height = make_thumbnail(original) final_key = row["object_key"].replace("staging/", "final/", 1) thumb_key = final_key + ".thumbnail.jpg" s3.put_object(final_key, original, content_type) s3.put_object(thumb_key, thumb, "image/jpeg") variant = { "name": "thumbnail", "content_type": "image/jpeg", "size_bytes": len(thumb), "width": width, "height": height, "sha256": hashlib.sha256(thumb).hexdigest(), } with db.transaction() as conn: conn.execute( "UPDATE attachments SET object_key = %s, status = 'ready', variants = %s::jsonb, " "error_code = NULL, updated_at = clock_timestamp() " "WHERE id = %s AND status <> 'ready'", (final_key, json.dumps([variant]), uuid.UUID(attachment_id)), ) log.info("job finished: ready", extra={"event": "job.ready"}) return "success" except Exception as exc: log.exception("processing failed: attachment=%s attempt=%s", attachment_id, attempt) if attempt < MAX_ATTEMPTS: _update(attachment_id, status="'queued'", error_code="NULL") retry = { "schema_version": 1, "job_id": job.get("job_id") or str(uuid.uuid4()), "type": "attachment.process.v1", "attachment_id": attachment_id, "pipeline_version": PIPELINE_VERSION, "attempt": attempt + 1, "created_at": job.get("created_at"), } if job.get("traceparent"): retry["traceparent"] = job["traceparent"] broker.publish(retry) log.info("job retried", extra={"event": "job.retry"}) return "retry" _update(attachment_id, status="'failed'", error_code="'processing_failed'") log.info("job failed", extra={"event": "job.failed"}) return "failed" def process_job(job): begun = time.monotonic() context = telemetry.extract({"traceparent": job["traceparent"]}) if job.get("traceparent") else None with telemetry.worker_span("attachment.process.v1", context) as span: if span is not None and span.is_recording(): span.set_attribute("attachment.id", job["attachment_id"]) span.set_attribute("job.attempt", int(job.get("attempt", 1))) outcome = "error" try: outcome = _process(job) finally: telemetry.record_job("attachment.process.v1", outcome, time.monotonic() - begun) def _handle(msg_id, fields): try: process_job(json.loads(fields["job"])) except Exception: log.exception("unhandled job message %s", msg_id) finally: broker.client.xack(broker.STREAM, broker.GROUP, msg_id) def reclaim_pending(): """Recover jobs left pending by a worker that died before XACK.""" start = "0-0" while True: next_id, claimed, _ = broker.client.xautoclaim( broker.STREAM, broker.GROUP, CONSUMER, min_idle_time=0, start_id=start, count=10 ) for msg_id, fields in claimed: _handle(msg_id, fields) if not claimed or next_id in ("0-0", None): break start = next_id def run(): logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO").upper()) from app.bao import load_secrets load_secrets() telemetry.init("messenger-worker", CONSUMER) db.start() s3.start() broker.start() reclaim_pending() log.info("worker started: consumer=%s max_attempts=%s", CONSUMER, MAX_ATTEMPTS) while True: streams = broker.client.xreadgroup( broker.GROUP, CONSUMER, {broker.STREAM: ">"}, count=1, block=2000 ) for _, messages in streams: for msg_id, fields in messages: _handle(msg_id, fields)