"""Durable outbox relay and idempotent Redis Streams image worker with OpenTelemetry.""" from concurrent.futures import ThreadPoolExecutor import hashlib import io import json import logging import os import random import threading import time import uuid import boto3 from botocore.config import Config from opentelemetry.metrics import Observation from opentelemetry.trace import SpanKind from PIL import Image, ImageOps, UnidentifiedImageError import psycopg from psycopg.rows import dict_row from psycopg_pool import ConnectionPool import redis from app.migrate import setting from app.telemetry import Telemetry def envsetting(name): return setting(name) if os.getenv(name + '_FILE') else os.environ[name] db = ConnectionPool(setting('DATABASE_URL'), min_size=1, max_size=8, kwargs={'row_factory': dict_row, 'connect_timeout': 3}) broker = redis.Redis.from_url(setting('BROKER_URL'), socket_connect_timeout=1, socket_timeout=2, decode_responses=True) s3 = boto3.client( 's3', endpoint_url=os.getenv('S3_ENDPOINT', 'http://rustfs:9000'), region_name=os.getenv('S3_REGION', 'us-east-1'), aws_access_key_id=envsetting('S3_ACCESS_KEY_ID'), aws_secret_access_key=envsetting('S3_SECRET_ACCESS_KEY'), config=Config(connect_timeout=3, read_timeout=10, retries={'max_attempts': 2}), ) bucket = os.getenv('S3_BUCKET', 'messenger-attachments') stream = 'attachment-jobs' group = 'image-workers' attempts = int(os.getenv('JOB_MAX_ATTEMPTS', '5')) concurrency = int(os.getenv('WORKER_CONCURRENCY', '2')) timeout = int(os.getenv('JOB_TIMEOUT_SECONDS', '60')) instance = os.getenv('HOSTNAME', 'worker') + '-' + uuid.uuid4().hex[:8] tel = Telemetry('messenger-worker', instance) jobs_counter = tel.meter.create_counter('worker.jobs', unit='1', description='Processed worker jobs') job_duration_hist = tel.meter.create_histogram( 'worker.job.duration', unit='s', description='Worker job execution duration in seconds', explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0], ) e2e_ready_hist = tel.meter.create_histogram( 'attachment.time_to_ready', unit='s', description='End-to-end attachment time from durable acceptance to ready', explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0], ) _busy_lock = threading.Lock() _busy_threads = 0 def _threads_callback(_opts): with _busy_lock: busy = _busy_threads return [ Observation(busy, {'state': 'busy'}), Observation(concurrency, {'state': 'capacity'}), ] def _queue_callbacks(_opts): counts = {'pending': 0, 'published': 0, 'processing': 0} try: with db.connection() as c: rows = c.execute( "SELECT state, count(*) AS n " "FROM attachment_jobs WHERE state IN ('pending','published','processing') GROUP BY state" ).fetchall() for r in rows: counts[r['state']] = int(r['n']) except Exception: return [] return [Observation(v, {'queue_name': stream, 'state': k}) for k, v in counts.items()] def _oldest_age_callback(_opts): try: with db.connection() as c: row = c.execute( "SELECT COALESCE(EXTRACT(EPOCH FROM (clock_timestamp() - min(created_at))), 0) AS age " "FROM attachment_jobs WHERE state IN ('pending','published','processing')" ).fetchone() age = max(0.0, float(row['age'])) if row else 0.0 return [Observation(age, {'queue_name': stream})] except Exception: return [] tel.meter.create_observable_gauge('worker.threads', callbacks=[_threads_callback], unit='', description='Worker thread saturation') tel.meter.create_observable_gauge('worker.queue.depth', callbacks=[_queue_callbacks], unit='', description='Queued jobs by state') tel.meter.create_observable_gauge('worker.oldest_job.age', callbacks=[_oldest_age_callback], unit='s', description='Age of oldest unfinished job in seconds') try: broker.xgroup_create(stream, group, id='0', mkstream=True) except redis.ResponseError as e: if 'BUSYGROUP' not in str(e): raise def publish_outbox(): with db.connection() as c: rows = c.execute( "SELECT job_id,attachment_id,pipeline_version,attempt,created_at,traceparent,tracestate " "FROM attachment_jobs WHERE state IN ('pending','published') AND available_at<=clock_timestamp() " "ORDER BY created_at LIMIT 100 FOR UPDATE SKIP LOCKED" ).fetchall() for r in rows: parent_ctx = tel.extract_context(r.get('traceparent'), r.get('tracestate')) with tel.span( 'outbox.publish', attributes={ 'messaging.system': 'redis', 'messaging.destination.name': stream, 'messaging.operation.type': 'publish', 'job.id': str(r['job_id']), 'attachment.id': str(r['attachment_id']), }, kind=SpanKind.PRODUCER, context=parent_ctx, ): carrier = tel.inject_context() msg = { 'schema_version': 1, 'job_id': str(r['job_id']), 'type': 'attachment.process.v1', 'attachment_id': str(r['attachment_id']), 'pipeline_version': r['pipeline_version'], 'attempt': max(1, r['attempt'] + 1), 'created_at': r['created_at'].isoformat().replace('+00:00', 'Z'), } if carrier.get('traceparent'): msg['traceparent'] = carrier['traceparent'] if carrier.get('tracestate'): msg['tracestate'] = carrier['tracestate'] broker.xadd(stream, {'job': json.dumps(msg, separators=(',', ':'))}) c.execute("UPDATE attachment_jobs SET state='published',available_at=clock_timestamp()+interval '15 seconds' WHERE job_id=%s AND state IN ('pending','published')", (r['job_id'],)) tel.log(logging.INFO, 'outbox.published', job_id=str(r['job_id']), attachment_id=str(r['attachment_id'])) def resize(raw): im = Image.open(io.BytesIO(raw)); im.load(); im = ImageOps.exif_transpose(im) if im.width * im.height > 40_000_000: raise ValueError('oversized_image') if im.mode in ('RGBA', 'LA') or 'transparency' in im.info: rgba = im.convert('RGBA'); bg = Image.new('RGBA', rgba.size, 'white'); bg.alpha_composite(rgba); im = bg.convert('RGB') else: im = im.convert('RGB') thumb = im.copy(); thumb.thumbnail((256, 256), Image.Resampling.LANCZOS) out = io.BytesIO(); thumb.save(out, format='JPEG', quality=85, optimize=True) crop = ImageOps.fit(im, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)); cropout = io.BytesIO(); crop.save(cropout, format='JPEG', quality=85, optimize=True) opt = im.copy(); opt.thumbnail((1280, 1280), Image.Resampling.LANCZOS); webp = io.BytesIO(); opt.save(webp, format='WEBP', quality=82, method=4, exif=b'') return [ ('thumbnail', 'image/jpeg', thumb.size, out.getvalue()), ('crop', 'image/jpeg', crop.size, cropout.getvalue()), ('optimized', 'image/webp', opt.size, webp.getvalue()), ] def process(job): global _busy_threads jid = uuid.UUID(job['job_id']); aid = uuid.UUID(job['attachment_id']) parent_ctx = tel.extract_context(job.get('traceparent'), job.get('tracestate')) started = time.monotonic() outcome = 'noop' with _busy_lock: _busy_threads += 1 try: with tel.span( 'worker.process', attributes={ 'messaging.system': 'redis', 'messaging.destination.name': stream, 'messaging.operation.type': 'process', 'job.id': str(jid), 'job.type': job.get('type', 'attachment.process.v1'), 'attachment.id': str(aid), }, kind=SpanKind.CONSUMER, context=parent_ctx, ) as sp: with tel.span('db.claim_job', {'db.system': 'postgresql'}): with db.connection() as c: c.execute('BEGIN') r = c.execute( 'SELECT j.*, a.chat_id, a.owner_id, a.object_key, a.staging_key, a.content_type, a.sha256, a.status, a.created_at AS att_created_at ' 'FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s FOR UPDATE OF j,a', (jid,), ).fetchone() if not r: c.rollback() return if r['state'] in ('done', 'failed') or (r['state'] == 'processing' and r['lease_until'] and r['lease_until'].timestamp() > time.time()): c.rollback() return c.execute("UPDATE attachment_jobs SET state='processing',attempt=attempt+1,lease_until=clock_timestamp()+(%s * interval '1 second') WHERE job_id=%s", (timeout, jid)) c.execute("UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=%s AND status<>'ready'", (aid,)) c.execute("INSERT INTO attachment_job_audit(job_id,event) VALUES (%s,'processing')", (jid,)) c.commit() attempt_num = r['attempt'] + 1 sp.set_attribute('job.attempt', attempt_num) tel.log(logging.INFO, 'worker.processing', job_id=str(jid), attachment_id=str(aid), attempt=attempt_num) try: with tel.span('s3.get_staging', {'storage.system': 's3'}): raw = s3.get_object(Bucket=bucket, Key=r['staging_key'])['Body'].read(10_485_761) if len(raw) > 10_485_760 or hashlib.sha256(raw).hexdigest() != r['sha256'].strip(): raise ValueError('invalid_image') with tel.span('image.resize'): variants = resize(raw) with tel.span('s3.put_variants', {'storage.system': 's3'}): s3.put_object(Bucket=bucket, Key=r['object_key'], Body=raw, ContentType=r['content_type'], Metadata={'sha256': r['sha256'].strip()}) meta = [] for name, mime, size, data in variants: key = f'variants/v1/{aid}/{name}' s3.put_object(Bucket=bucket, Key=key, Body=data, ContentType=mime, Metadata={'pipeline-version': '1'}) meta.append({'name': name, 'content_type': mime, 'size_bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'width': size[0], 'height': size[1]}) if os.getenv('FAULT_AFTER_S3_WRITE_ONCE', '0') == '1': with db.connection() as c: seen = c.execute("SELECT 1 FROM attachment_job_audit WHERE job_id=%s AND event='fault_injected'", (jid,)).fetchone() if not seen: c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'fault_injected','crash after deterministic S3 writes, before ready commit')", (jid,)) c.commit() os._exit(72) with tel.span('db.commit_ready', {'db.system': 'postgresql'}): with db.connection() as c: c.execute("UPDATE attachments SET status='ready',variants=%s::jsonb,error_code=NULL,updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=1 AND status<>'ready'", (json.dumps(meta), aid)) c.execute("UPDATE attachment_jobs SET state='done',lease_until=NULL,last_error=NULL WHERE job_id=%s", (jid,)) c.execute("INSERT INTO attachment_job_audit(job_id,event) VALUES (%s,'ready')", (jid,)) row_now = c.execute('SELECT clock_timestamp() AS now').fetchone() with tel.span('s3.delete_staging', {'storage.system': 's3'}): s3.delete_object(Bucket=bucket, Key=r['staging_key']) outcome = 'ready' e2e_sec = max(0.0, (row_now['now'] - r['att_created_at']).total_seconds()) e2e_ready_hist.record(e2e_sec, {'pipeline_version': '1'}) tel.log(logging.INFO, 'worker.ready', job_id=str(jid), attachment_id=str(aid), e2e_seconds=round(e2e_sec, 3)) except (UnidentifiedImageError, ValueError) as exc: outcome = 'failed' retry_or_fail(jid, aid, 'invalid_image', True) sp.record_exception(exc) except Exception as exc: outcome = retry_or_fail(jid, aid, 'processing_failed', False) sp.record_exception(exc) finally: with _busy_lock: _busy_threads -= 1 elapsed = time.monotonic() - started attrs = {'job.type': job.get('type', 'attachment.process.v1'), 'outcome': outcome} jobs_counter.add(1, attrs) job_duration_hist.record(elapsed, attrs) def retry_or_fail(jid, aid, code, permanent): with db.connection() as c: r = c.execute('SELECT attempt,state FROM attachment_jobs WHERE job_id=%s', (jid,)).fetchone() if not r or r['state'] == 'done': return 'noop' n = r['attempt'] if permanent or n >= attempts: c.execute("UPDATE attachment_jobs SET state='failed',lease_until=NULL,last_error=%s WHERE job_id=%s", (code, jid)) c.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=clock_timestamp() WHERE id=%s", ('invalid_image' if permanent else 'retry_exhausted', aid)) c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'failed',%s)", (jid, code)) broker.xadd('attachment-jobs-dlq', {'job_id': str(jid), 'attachment_id': str(aid), 'error_code': code}) tel.log(logging.ERROR, 'worker.failed', job_id=str(jid), attachment_id=str(aid), error_code=code, attempt=n) return 'failed' delay = min(60, 2 ** n) * (0.8 + random.random() * 0.4) c.execute("UPDATE attachment_jobs SET state='pending',available_at=clock_timestamp()+(%s * interval '1 second'),lease_until=NULL,last_error=%s WHERE job_id=%s", (delay, code, jid)) c.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s", (aid,)) tel.log(logging.WARNING, 'worker.retry', job_id=str(jid), attachment_id=str(aid), error_code=code, attempt=n, retry_delay_s=round(delay, 2)) return 'retry' def recover_leases(): with db.connection() as c: expired = c.execute("SELECT job_id,attachment_id,attempt FROM attachment_jobs WHERE state='processing' AND lease_until= attempts: c.execute("UPDATE attachment_jobs SET state='failed',lease_until=NULL,last_error='retry_exhausted' WHERE job_id=%s", (row['job_id'],)) c.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=%s", (row['attachment_id'],)) c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'failed','lease attempts exhausted')", (row['job_id'],)) broker.xadd('attachment-jobs-dlq', {'job_id': str(row['job_id']), 'attachment_id': str(row['attachment_id']), 'error_code': 'retry_exhausted'}) tel.log(logging.ERROR, 'worker.lease_exhausted', job_id=str(row['job_id']), attachment_id=str(row['attachment_id'])) else: c.execute("UPDATE attachment_jobs SET state='pending',lease_until=NULL,available_at=clock_timestamp() WHERE job_id=%s", (row['job_id'],)) tel.log(logging.WARNING, 'worker.lease_recovered', job_id=str(row['job_id']), attachment_id=str(row['attachment_id'])) c.execute("UPDATE attachments a SET status='queued',updated_at=clock_timestamp() FROM attachment_jobs j WHERE j.attachment_id=a.id AND j.state='pending' AND a.status='processing'") def main(): consumer = f'worker-{uuid.uuid4()}' while True: try: recover_leases(); publish_outbox() if os.getenv('WORKER_PAUSE_CONSUME', '0') == '1': time.sleep(0.2); continue msgs = broker.xreadgroup(group, consumer, {stream: '>'}, count=concurrency, block=1000) claimed = broker.xautoclaim(stream, group, consumer, min_idle_time=timeout * 1000, start_id='0-0', count=concurrency) if claimed and claimed[1]: msgs.append((stream, claimed[1])) for _, entries in msgs: with ThreadPoolExecutor(max_workers=concurrency) as executor: futures = [] for mid, fields in entries: try: job = json.loads(fields['job']) except Exception: broker.xadd('attachment-jobs-dlq', {'message_id': mid, 'error_code': 'invalid_job'}) broker.xack(stream, group, mid) continue futures.append((mid, executor.submit(process, job))) for mid, future in futures: try: future.result(); broker.xack(stream, group, mid) except Exception: pass except Exception: time.sleep(1) if __name__ == '__main__': main()