Files
mtusi2026lab7/app/worker.py
T
Бахрам 1df2202403
Skeleton contracts / contracts (pull_request) Canceled after 0s
Complete lab 7 TLS and secret management
2026-12-01 22:44:28 +03:00

230 lines
11 KiB
Python

"""Durable RabbitMQ consumer and PostgreSQL outbox publisher."""
import hashlib
import json
import logging
import os
import ssl
import threading
import time
from io import BytesIO
import boto3
import pika
import psycopg
from psycopg.types.json import Jsonb
from PIL import Image, ImageOps
from jsonschema import Draft202012Validator, FormatChecker
from opentelemetry import propagate
from opentelemetry.trace import SpanKind, Status, StatusCode
from app.secrets import load_secrets
load_secrets()
from app.telemetry import JOB_DURATION, JOBS_PROCESSED, tracer
DSN = os.environ['DATABASE_URL']
BUCKET = os.getenv('S3_STAGING_BUCKET',os.getenv('S3_BUCKET','attachments')+'-staging')
STAGING_BUCKET = BUCKET
ORIGINAL_BUCKET = os.getenv('S3_ORIGINAL_BUCKET',BUCKET+'-original')
VARIANTS_BUCKET = os.getenv('S3_VARIANTS_BUCKET',BUCKET+'-variants')
QUEUE = 'attachment.process.v1'
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS','5'))
MAX_BYTES = 10*1024*1024
Image.MAX_IMAGE_PIXELS = 40_000_000
schemas = json.load(open('contracts/jobs.schema.json'))
job_validator = Draft202012Validator(schemas,format_checker=FormatChecker())
def s3():
return boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],
aws_access_key_id=os.environ['S3_ACCESS_KEY'],aws_secret_access_key=os.environ['S3_SECRET_KEY'],
region_name='us-east-1',verify=os.getenv('S3_CA_CERT') or True,
config=boto3.session.Config(connect_timeout=2,read_timeout=10,retries={'max_attempts':0},
s3={'addressing_style':'path'}))
def broker():
params=pika.URLParameters(os.environ['BROKER_URL'])
params.heartbeat=30
params.blocked_connection_timeout=5
tls=ssl.create_default_context(cafile=os.environ['BROKER_CA_CERT'])
tls.check_hostname=True
params.ssl_options=pika.SSLOptions(tls,server_hostname='broker')
return pika.BlockingConnection(params)
def publish(payload):
connection=broker()
try:
channel=connection.channel()
channel.queue_declare(queue=QUEUE,durable=True)
channel.confirm_delivery()
parent=propagate.extract(payload)
with tracer.start_as_current_span('rabbitmq.publish',context=parent,kind=SpanKind.PRODUCER,
attributes={'messenger.job.type':payload['type']}):
headers={}
propagate.inject(headers)
channel.basic_publish('',QUEUE,json.dumps(payload).encode(),
pika.BasicProperties(content_type='application/json',delivery_mode=2,message_id=payload['job_id'],type=payload['type'],headers=headers))
finally:
connection.close()
def dispatch_outbox():
while True:
try:
with psycopg.connect(DSN,connect_timeout=3) as db:
rows=db.execute("SELECT job_id,payload FROM attachment_jobs WHERE published_at IS NULL AND status IN ('queued','processing') ORDER BY created_at LIMIT 20").fetchall()
for job_id,payload in rows:
try:
publish(payload)
with psycopg.connect(DSN) as db:
db.execute('UPDATE attachment_jobs SET published_at=now() WHERE job_id=%s AND published_at IS NULL',(job_id,))
except Exception:
logging.warning('Outbox publish is pending for job %s',job_id)
break
except Exception:
logging.exception('Outbox scan failed')
time.sleep(2)
def make_thumbnail(data):
with Image.open(BytesIO(data)) as source:
source.load()
image=ImageOps.exif_transpose(source)
image.thumbnail((256,256),Image.Resampling.LANCZOS)
if image.mode in ('RGBA','LA') or (image.mode=='P' and 'transparency' in image.info):
rgba=image.convert('RGBA')
background=Image.new('RGBA',rgba.size,'white')
background.alpha_composite(rgba)
image=background.convert('RGB')
else:
image=image.convert('RGB')
output=BytesIO()
image.save(output,format='JPEG',quality=85,optimize=True)
result=output.getvalue()
return result,image.width,image.height
def process(payload):
errors=list(job_validator.iter_errors(payload))
if errors:
raise ValueError('invalid_job')
job_id,ident=payload['job_id'],payload['attachment_id']
with psycopg.connect(DSN) as db:
row=db.execute('SELECT a.doc,a.stage_key,j.attempt,j.status FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE j.job_id=%s AND a.id=%s',(job_id,ident)).fetchone()
if not row:
return 'orphan'
doc,stage_key,attempt,status=row
if doc['status']=='ready' or status=='done':
return 'done'
if doc['status']=='failed' or status=='failed':
return 'failed'
if attempt>=MAX_ATTEMPTS:
doc.update(status='failed',error_code='retry_exhausted',updated_at=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat().replace('+00:00','Z'))
db.execute("UPDATE attachments SET doc=%s WHERE id=%s",(Jsonb(doc),ident))
db.execute("UPDATE attachment_jobs SET status='failed',last_error='retry_exhausted' WHERE job_id=%s",(job_id,))
return 'failed'
attempt=max(attempt+1,payload['attempt'])
db.execute("UPDATE attachment_jobs SET status='processing',attempt=%s,last_error=NULL WHERE job_id=%s",(attempt,job_id))
doc.update(status='processing',updated_at=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat().replace('+00:00','Z'))
db.execute('UPDATE attachments SET doc=%s WHERE id=%s',(Jsonb(doc),ident))
db.commit()
client=s3()
obj=client.get_object(Bucket=STAGING_BUCKET,Key=stage_key)
try:
data=obj['Body'].read(MAX_BYTES+1)
finally:
obj['Body'].close()
if len(data)>MAX_BYTES or hashlib.sha256(data).hexdigest()!=doc['sha256']:
raise ValueError('invalid_image')
thumb,width,height=make_thumbnail(data)
client.put_object(Bucket=ORIGINAL_BUCKET,Key='original/'+ident,Body=data,ContentType=doc['content_type'])
client.put_object(Bucket=VARIANTS_BUCKET,Key='variants/'+ident+'/thumbnail.jpg',Body=thumb,ContentType='image/jpeg')
stamp=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat().replace('+00:00','Z')
variant={'name':'thumbnail','content_type':'image/jpeg','size_bytes':len(thumb),'width':width,'height':height,'sha256':hashlib.sha256(thumb).hexdigest()}
doc.update(status='ready',variants=[variant],error_code=None,updated_at=stamp)
# S3 writes are deterministic and idempotent; PostgreSQL publishes ready only
# after both objects exist. A redelivery safely overwrites those same keys.
with psycopg.connect(DSN) as db:
db.execute("UPDATE attachments SET doc=%s WHERE id=%s AND doc->>'status'!='ready'",(Jsonb(doc),ident))
db.execute("UPDATE attachment_jobs SET status='done',last_error=NULL WHERE job_id=%s",(job_id,))
try:
client.delete_object(Bucket=STAGING_BUCKET,Key=stage_key)
except Exception:
logging.warning('Finished attachment retained staging object %s',ident)
return 'done'
def callback(channel,method,properties,body):
started=time.perf_counter()
payload={}
outcome='failed'
try:
payload=json.loads(body)
parent=propagate.extract(properties.headers or {})
with tracer.start_as_current_span('attachment.process',context=parent,kind=SpanKind.CONSUMER,
attributes={'messenger.job.type':payload.get('type','unknown'),'messenger.job.attempt':int(payload.get('attempt',0))}) as span:
result=process(payload)
channel.basic_ack(method.delivery_tag)
outcome='success' if result=='done' else result
logging.info('worker.job.completed',extra={'event':'worker.job.completed','job_type':'attachment.process.v1','outcome':outcome,'attempt':int(payload.get('attempt',0))})
span.set_attribute('messenger.job.outcome',outcome)
except ValueError as exc:
try:
payload=json.loads(body)
job_id,ident=payload.get('job_id'),payload.get('attachment_id')
with psycopg.connect(DSN) as db:
row=db.execute('SELECT doc,attempt FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE j.job_id=%s',(job_id,)).fetchone()
if row:
doc,attempt=row
stamp=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat().replace('+00:00','Z')
if attempt>=MAX_ATTEMPTS:
doc.update(status='failed',error_code='invalid_image' if str(exc)=='invalid_image' else 'retry_exhausted',updated_at=stamp)
db.execute('UPDATE attachments SET doc=%s WHERE id=%s',(Jsonb(doc),ident))
db.execute("UPDATE attachment_jobs SET status='failed',last_error=%s WHERE job_id=%s",(str(exc)[:80],job_id))
channel.basic_ack(method.delivery_tag)
outcome='failed'
else:
doc.update(status='queued',error_code=None,updated_at=stamp)
db.execute('UPDATE attachments SET doc=%s WHERE id=%s',(Jsonb(doc),ident))
db.execute("UPDATE attachment_jobs SET status='queued',last_error=%s WHERE job_id=%s",(str(exc)[:80],job_id))
time.sleep(min(2**max(attempt-1,0),8))
channel.basic_nack(method.delivery_tag,requeue=True)
outcome='retry'
else:
channel.basic_ack(method.delivery_tag)
except Exception:
logging.error('worker.job.record_failure_failed')
channel.basic_nack(method.delivery_tag,requeue=True)
except Exception:
logging.error('worker.job.transient_failure')
try:
channel.basic_nack(method.delivery_tag,requeue=True)
except Exception:
pass
finally:
elapsed=time.perf_counter()-started
attrs={'job_type':'attachment.process.v1','outcome':outcome}
JOBS_PROCESSED.add(1,attrs)
JOB_DURATION.record(elapsed,attrs)
def main():
threading.Thread(target=dispatch_outbox,daemon=True,name='outbox-publisher').start()
while True:
try:
connection=broker()
channel=connection.channel()
channel.queue_declare(queue=QUEUE,durable=True)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=QUEUE,on_message_callback=callback,auto_ack=False)
logging.info('Worker consuming durable queue %s',QUEUE)
channel.start_consuming()
except KeyboardInterrupt:
break
except Exception:
logging.error('worker.broker.unavailable')
time.sleep(2)
if __name__=='__main__':
main()