import asyncio import hashlib import json import logging import ssl import sys import uuid from io import BytesIO import asyncpg import boto3 import pika from PIL import Image, ImageOps from .config import load_settings, env from .db import pg_ssl from .vault import login settings = load_settings("worker") try: vault = login(settings, "worker") except Exception as exc: logger = logging.getLogger("messenger-worker") logger.error("worker_startup_secret_auth_failed", extra={ "event": "worker_startup_secret_auth_failed", "error_type": type(exc).__name__, }) raise RuntimeError("worker OpenBao AppRole authentication unavailable") from None secrets = vault["secrets"] settings = settings.__class__(**{**settings.__dict__, "database_url": secrets["database_url"], "broker_url": secrets["broker_url"], "s3_access_key": secrets["s3_access_key"], "s3_secret_key": secrets["s3_secret_key"], }) logger = logging.getLogger("messenger-worker") async def pool(): ca = env("PG_CACERT", env("TLS_CA_FILE")) pool = await asyncpg.create_pool(settings.database_url, ssl=pg_ssl(settings.database_url, ca), min_size=1, max_size=5) return pool def s3(): return boto3.client( "s3", endpoint_url=settings.s3_endpoint, region_name=settings.s3_region, aws_access_key_id=settings.s3_access_key, aws_secret_access_key=settings.s3_secret_key, verify=settings.s3_verify, ) async def process_attachment(pool, attachment_id): async with pool.acquire() as con: row = await con.fetchrow("SELECT * FROM attachments WHERE id=$1", attachment_id) if not row: return "missing" if row["status"] == "ready": return "ready" await con.execute( "UPDATE attachments SET status='processing',updated_at=NOW() WHERE id=$1", attachment_id, ) client = s3() original = await asyncio.to_thread( client.get_object, Bucket=settings.s3_bucket, Key=row["staging_key"] ) data = await asyncio.to_thread(original["Body"].read) try: with Image.open(BytesIO(data)) as source: source.load() image = ImageOps.exif_transpose(source) if image.mode in ("RGBA", "LA") or "transparency" in image.info: alpha = image.convert("RGBA") white = Image.new("RGBA", alpha.size, (255, 255, 255, 255)) white.alpha_composite(alpha) image = white.convert("RGB") else: image = image.convert("RGB") width, height = image.size if width >= 1 and height >= 1: scale = min(256 / width, 256 / height, 1.0) tw = max(1, int(width * scale)) th = max(1, int(height * scale)) thumbnail = image.resize((tw, th), Image.Resampling.LANCZOS) else: raise ValueError("invalid image dimensions") output = BytesIO() thumbnail.save(output, format="JPEG", quality=85, optimize=True) thumb = output.getvalue() except Exception as exc: logger.error("attachment_processing_failed_safe", extra={ "event": "attachment_processing_failed", "attachment_id": str(attachment_id), "error_type": type(exc).__name__, }) async with pool.acquire() as con: await con.execute( "UPDATE attachments SET status='failed',error_code='invalid_image'," "updated_at=NOW() WHERE id=$1", attachment_id, ) return "failed" final_key = f"attachments/{attachment_id}/original" thumb_key = f"attachments/{attachment_id}/thumbnail" try: await asyncio.to_thread( client.put_object, Bucket=settings.s3_bucket, Key=final_key, Body=data, ContentType=row["content_type"], ) await asyncio.to_thread( client.put_object, Bucket=settings.s3_bucket, Key=thumb_key, Body=thumb, ContentType="image/jpeg", ) except Exception as exc: logger.error("attachment_publish_failed_safe", extra={ "event": "attachment_publish_failed", "attachment_id": str(attachment_id), "error_type": type(exc).__name__, }) async with pool.acquire() as con: await con.execute( "UPDATE attachments SET status='failed',error_code='processing_failed'," "updated_at=NOW() WHERE id=$1", attachment_id, ) return "failed" thumb_sha = hashlib.sha256(thumb).hexdigest() async with pool.acquire() as con: async with con.transaction(): await con.execute( "INSERT INTO attachment_variants" "(attachment_id,name,content_type,size_bytes,width,height,sha256,object_key)" " VALUES($1,'thumbnail','image/jpeg',$2,$3,$4,$5,$6)" " ON CONFLICT (attachment_id,name) DO UPDATE SET " "size_bytes=EXCLUDED.size_bytes,width=EXCLUDED.width,height=EXCLUDED.height," "sha256=EXCLUDED.sha256,object_key=EXCLUDED.object_key", attachment_id, len(thumb), tw, th, thumb_sha, thumb_key, ) await con.execute( "UPDATE attachments SET status='ready',error_code=NULL,final_key=$1," "updated_at=NOW() WHERE id=$2", final_key, attachment_id, ) return "ready" async def fail_retry_exhausted(pool, attachment_id): async with pool.acquire() as con: await con.execute( "UPDATE attachments SET status='failed',error_code='retry_exhausted'," "updated_at=NOW() WHERE id=$1", attachment_id, ) def main(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) db_pool = loop.run_until_complete(pool()) params = pika.URLParameters(settings.broker_url) if settings.broker_url.startswith("amqps://"): ssl_context = ssl.create_default_context(cafile=settings.broker_verify) ssl_context.check_hostname = True ssl_context.verify_mode = ssl.CERT_REQUIRED params.ssl_options = pika.SSLOptions(ssl_context) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue="attachment.jobs", durable=True) channel.basic_qos(prefetch_count=settings.job_attempts) channel.confirm_delivery() def on_message(ch, method, properties, body): job = None try: job = json.loads(body) if set(job) - {"schema_version","job_id","type","attachment_id","pipeline_version","attempt","created_at","traceparent","tracestate"}: raise ValueError("invalid job") if job.get("schema_version") != 1 or job.get("type") != "attachment.process.v1": raise ValueError("invalid job") import uuid uuid.UUID(job["job_id"]) aid = uuid.UUID(job["attachment_id"]) outcome = loop.run_until_complete(process_attachment(db_pool, aid)) if outcome in ("ready", "missing", "failed"): ch.basic_ack(delivery_tag=method.delivery_tag) else: ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True) except Exception as exc: logger.error("worker_job_failed_safe", extra={ "event": "worker_job_failed", "job_id": job.get("job_id") if isinstance(job, dict) else None, "attachment_id": job.get("attachment_id") if isinstance(job, dict) else None, "error_type": type(exc).__name__, }) attempt = int(job.get("attempt", 1)) if isinstance(job, dict) else 1 if attempt >= settings.job_attempts: try: aid = uuid.UUID(job["attachment_id"]) loop.run_until_complete(fail_retry_exhausted(db_pool, aid)) except Exception as exc: logger.error("retry_exhausted_update_failed_safe", extra={ "event": "retry_exhausted_update_failed", "attachment_id": job.get("attachment_id") if isinstance(job, dict) else None, "error_type": type(exc).__name__, }) ch.basic_ack(delivery_tag=method.delivery_tag) else: next_job = dict(job) next_job["attempt"] = attempt + 1 ch.basic_publish( exchange="", routing_key="attachment.jobs", body=json.dumps(next_job, separators=(",", ":")).encode("utf-8"), properties=pika.BasicProperties(delivery_mode=2), ) ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_consume(queue="attachment.jobs", on_message_callback=on_message) channel.start_consuming() if __name__ == "__main__": main()