import hashlib, io, json, os, time from PIL import Image, ImageOps from psycopg.types.json import Jsonb from main import db, transaction, s3, S3_BUCKET from queueing import connect, publish, QUEUE from opentelemetry import trace from telemetry import jobs_processed, job_duration, event, propagator MAX_ATTEMPTS=int(os.getenv('JOB_MAX_ATTEMPTS','5')) def dispatch(): while True: try: c,ch=connect() try: with transaction() as conn: jobs=conn.execute('SELECT * FROM jobs WHERE NOT published FOR UPDATE SKIP LOCKED LIMIT 20').fetchall() for job in jobs: publish(ch,job) event('job.published', job_type='attachment.process.v1', outcome='published') conn.execute('UPDATE jobs SET published=true WHERE id=%s',(job['id'],)) finally: c.close() except Exception as e: print('dispatch retry:',type(e).__name__,flush=True) time.sleep(0.5) def _process(payload): jid=payload['job_id'] # Session advisory lock spans processing and commit; released on worker death. with db() as lock: lock.execute('SELECT pg_advisory_lock(hashtextextended(%s,0))',(jid,)) with transaction() as conn: job=conn.execute('SELECT * FROM jobs WHERE id=%s',(jid,)).fetchone() if not job:return row=conn.execute('SELECT * FROM attachments WHERE id=%s',(job['attachment_id'],)).fetchone() if row['status'] in ('ready','failed') or payload['attempt']!=job['attempt']:return conn.execute("UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s",(row['id'],)) try: client=s3(); data=client.get_object(Bucket=S3_BUCKET,Key=row['object_key'])['Body'].read() if hashlib.sha256(data).hexdigest()!=row['sha256']:raise ValueError('checksum') with Image.open(io.BytesIO(data)) as source: img=ImageOps.exif_transpose(source).convert('RGBA') w,h=img.size; scale=min(1,256/max(w,h)); size=(max(1,int(w*scale)),max(1,int(h*scale))) img=img.resize(size,Image.Resampling.LANCZOS) rgb=Image.new('RGB',size,'white'); rgb.paste(img,mask=img.getchannel('A')) out=io.BytesIO(); rgb.save(out,format='JPEG',quality=85); thumb=out.getvalue() key=f"attachments/{row['chat_id']}/{row['id']}" client.put_object(Bucket=S3_BUCKET,Key=key,Body=data,ContentType=row['content_type']) client.put_object(Bucket=S3_BUCKET,Key=key+'/thumbnail',Body=thumb,ContentType='image/jpeg') v=dict(name='thumbnail',content_type='image/jpeg',width=size[0],height=size[1],size_bytes=len(thumb),sha256=hashlib.sha256(thumb).hexdigest()) with transaction() as conn: conn.execute("UPDATE attachments SET status='ready',object_key=%s,variants=%s,error_code=NULL,updated_at=now() WHERE id=%s",(key,Jsonb([v]),row['id'])) try:client.delete_object(Bucket=S3_BUCKET,Key=row['object_key']) except Exception:pass except Exception as e: print( 'processing error:', type(e).__name__, 'checksum mismatch' if isinstance(e, ValueError) and str(e) == 'checksum' else 'other error', flush=True ) with transaction() as conn: if conn.execute('SELECT status FROM attachments WHERE id=%s',(row['id'],)).fetchone()['status']=='ready':return if job['attempt']>=MAX_ATTEMPTS: conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now() WHERE id=%s AND status!='ready'",(row['id'],)) else: conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s AND status!='ready'",(row['id'],)) conn.execute('UPDATE jobs SET attempt=attempt+1,published=false WHERE id=%s',(jid,)) return 'failed' if job['attempt']>=MAX_ATTEMPTS else 'retry' def process(payload, headers=None): context=propagator.extract(headers or {}) tracer=trace.get_tracer('messenger.worker') started=time.perf_counter() outcome='success' with tracer.start_as_current_span('job.process', context=context) as span: span.set_attribute('messaging.system','rabbitmq') span.set_attribute('messaging.destination.name',QUEUE) span.set_attribute('messaging.operation','process') span.set_attribute('job.type','attachment.process.v1') try: result=_process(payload) if result in ('retry','failed'): outcome='error' span.set_attribute('job.outcome', result) if result == 'failed': span.set_status(trace.Status(trace.StatusCode.ERROR)) except Exception as exc: outcome='error' span.record_exception(exc) span.set_status(trace.Status(trace.StatusCode.ERROR)) raise finally: duration=time.perf_counter()-started attrs={'job_type':'attachment.process.v1','outcome':outcome} jobs_processed.add(1,attrs); job_duration.record(duration,attrs) event('job.processed' if outcome=='success' else 'job.failed', 'ERROR' if outcome!='success' else 'INFO', job_type='attachment.process.v1', outcome=outcome, duration_seconds=round(duration,6)) def consume(): while True: try: c,ch=connect(); ch.basic_qos(prefetch_count=1) def callback(channel,method,props,body): try: process(json.loads(body), props.headers or {}); channel.basic_ack(method.delivery_tag) except Exception: channel.basic_nack(method.delivery_tag,requeue=True); time.sleep(1) ch.basic_consume(QUEUE,callback); ch.start_consuming() except Exception as e: print('consumer reconnect:',type(e).__name__,flush=True); time.sleep(2) if __name__=='__main__': import sys (dispatch if 'dispatch' in sys.argv else consume)()