Files
mtusi2026lab7/pipeline/pipeline.py
T
wanderinho 7ee5192cbd
Skeleton contracts / contracts (pull_request) Blocked by required conditions
ЛР7 - БПИ2303 - Стругов - на 4
2026-12-06 23:11:49 +03:00

266 lines
15 KiB
Python

import telemetry as t
from bao import BaoSecrets, SecretsUnavailable
import hashlib
import io
import json
import os
import random
import signal
import sys
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit
import boto3
from botocore.config import Config
import psycopg
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
import redis
from PIL import Image, ImageOps, UnidentifiedImageError
STREAM, GROUP = 'attachments:v1', 'workers'
MAX = int(os.getenv('JOB_MAX_ATTEMPTS', '5'))
TIMEOUT = int(os.getenv('JOB_TIMEOUT_SECONDS', '60'))
if not 1 <= TIMEOUT <= 60:
raise SystemExit('JOB_TIMEOUT_SECONDS must be in [1, 60]')
LEASE = TIMEOUT + 15
BUCKET = os.getenv('S3_BUCKET', 'messenger-attachments')
Image.MAX_IMAGE_PIXELS = 40_000_000
def settings():
required = ('DATABASE_URL',)
if os.getenv('SERVICE_IDENTITY', 'worker') == 'worker':
required += ('S3_ACCESS_KEY', 'S3_SECRET_KEY')
if address := os.getenv('BAO_ADDR'):
return BaoSecrets(address, os.environ['SERVICE_IDENTITY'], required).read
def read_local():
values = {}
for name in required:
path = os.getenv(name + '_FILE')
values[name] = Path(path).read_text().strip() if path else os.environ[name]
return values
return read_local
def db(values):
return psycopg.connect(values['DATABASE_URL'], autocommit=True, row_factory=dict_row, connect_timeout=5, options='-c statement_timeout=10000 -c lock_timeout=5000')
def broker():
address = os.environ['BROKER_URL']
url = urlsplit(address)
if url.scheme != 'rediss' or url.username is not None or url.query:
raise ValueError('Broker requires certificate authentication over rediss')
identity = os.environ['SERVICE_IDENTITY']
return redis.Redis.from_url(
address, decode_responses=True, socket_timeout=5, socket_connect_timeout=5,
ssl_ca_certs='/pki/ca.crt', ssl_certfile=f'/pki/{identity}.crt',
ssl_keyfile=f'/pki/{identity}.key', ssl_cert_reqs='required',
ssl_check_hostname=True, lib_name=None, lib_version=None,
)
def s3(values):
return boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], aws_access_key_id=values['S3_ACCESS_KEY'], aws_secret_access_key=values['S3_SECRET_KEY'], region_name='us-east-1', config=Config(signature_version='s3v4', connect_timeout=3, read_timeout=8, retries={'total_max_attempts': 1}, s3={'addressing_style':'path'}))
def payload(j):
return json.dumps(dict(schema_version=1, job_id=str(j['id']), type='attachment.process.v1', attachment_id=str(j['attachment_id']), pipeline_version=1, attempt=j['attempt'], created_at=j['created_at'].astimezone(timezone.utc).isoformat()))
def fault(name):
# Explicit one-shot operator trigger on persistent shared volume.
p = Path('/faults') / name
try:
p.unlink()
except FileNotFoundError:
return
print('injected crash:', name, flush=True)
os._exit(70)
def publisher():
read_settings = settings()
r = broker()
while True:
try:
with db(read_settings()) as c:
with c.transaction():
j = c.execute("""SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id
WHERE a.status='queued' AND j.available_at<=now() AND (j.published_at IS NULL OR j.published_at<now()-interval '120 seconds')
ORDER BY j.available_at LIMIT 1 FOR UPDATE OF j SKIP LOCKED""").fetchone()
if j:
fault('before-publish')
with t.tr.start_as_current_span('attachments.publish',context=t.prop.extract({k:j[k] for k in ("traceparent","tracestate") if j[k]}),kind=t.SpanKind.PRODUCER,record_exception=False,set_status_on_exception=False):
carrier={}; t.prop.inject(carrier); r.xadd(STREAM, {'job':payload(j), **carrier}); t.event('published')
c.execute('UPDATE attachment_jobs SET published_at=now() WHERE id=%s',(j['id'],))
# Expired processing: row lock + conditional state transition; worker timeout is shorter than lease.
with c.transaction():
j = c.execute("""SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id
WHERE a.status='processing' AND j.lease_until<now() LIMIT 1 FOR UPDATE OF j SKIP LOCKED""").fetchone()
if j and c.execute('SELECT pg_try_advisory_xact_lock(hashtextextended(%s,0)) AS ok',(str(j['id']),)).fetchone()['ok']:
retry(c,j,'retry_exhausted',False)
q=c.execute("SELECT count(*) AS depth, COALESCE(EXTRACT(EPOCH FROM now()-min(j.created_at)),0) AS age FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.status IN ('queued','processing')").fetchone()
t.depth.set(q['depth'], {'queue':STREAM}); t.age.set(float(q['age']), {'queue':STREAM}); t.process_stats()
time.sleep(.2)
except Exception as e:
print('publisher transient:',type(e).__name__,flush=True); time.sleep(2)
def retry(c,j,code,permanent):
t.event('retry_decision')
current=c.execute('SELECT a.status,j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=%s',(j['id'],)).fetchone()
if current['status']!='processing' or current['attempt']!=j['attempt']: return
replays=c.execute('SELECT count(*) AS n FROM attachment_replays WHERE job_id=%s',(j['id'],)).fetchone()['n']
if permanent or j['attempt']>=MAX*(1+replays):
c.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=now() WHERE id=%s",(code,j['attachment_id']))
c.execute('UPDATE attachment_jobs SET lease_until=NULL WHERE id=%s',(j['id'],))
else:
delay=min(30,2**min(5,j['attempt']))+random.random()
c.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s",(j['attachment_id'],))
c.execute("UPDATE attachment_jobs SET attempt=attempt+1,available_at=now()+%s*interval '1 second',published_at=NULL,lease_until=NULL WHERE id=%s",(delay,j['id']))
def fit(im,n):
w,h=im.size
if max(w,h)<=n: return im.copy()
return im.resize((max(1,w*n//max(w,h)),max(1,h*n//max(w,h))),Image.Resampling.LANCZOS)
def variants(data):
with Image.open(io.BytesIO(data)) as im:
if im.width*im.height>40_000_000 or im.format not in ('PNG','JPEG'): raise ValueError('invalid_image')
im=ImageOps.exif_transpose(im)
rgba=im.convert('RGBA'); rgb=Image.new('RGB',rgba.size,'white'); rgb.paste(rgba,mask=rgba.getchannel('A')); del rgba,im
for name, picture, fmt, ct, quality in [('thumbnail',fit(rgb,256),'JPEG','image/jpeg',85),('crop',ImageOps.fit(rgb,(128,128),Image.Resampling.LANCZOS),'JPEG','image/jpeg',85),('optimized',fit(rgb,1280),'WEBP','image/webp',80)]:
picture.info.clear(); buf=io.BytesIO(); picture.save(buf,format=fmt,quality=quality)
raw=buf.getvalue(); yield dict(name=name,content_type=ct,width=picture.width,height=picture.height,size_bytes=len(raw),sha256=hashlib.sha256(raw).hexdigest()),raw
def process(c,storage,j):
# Hold session advisory lock through S3 effects and final transaction.
lock=c.execute('SELECT pg_try_advisory_lock(hashtextextended(%s,0)) AS ok',(str(j['id']),)).fetchone()['ok']
if not lock: return False
try:
with c.transaction():
row=c.execute('SELECT j.*,a.status,a.content_type,a.sha256,a.size_bytes FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=%s FOR UPDATE OF j',(j['id'],)).fetchone()
if not row or row['status'] in ('ready','failed') or row['attempt']!=j['attempt']: return True
if row['status']!='queued': return False
c.execute("UPDATE attachment_jobs SET lease_until=now()+%s*interval '1 second' WHERE id=%s",(LEASE,j['id']))
c.execute("UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s",(row['attachment_id'],))
aid=str(row['attachment_id']); original='originals/'+aid
try:
body=t.call('s3.get',storage.get_object,Bucket=BUCKET,Key=row['staging_key'])['Body']
try: data=body.read(10*1024*1024+1)
finally: body.close()
if len(data)!=row['size_bytes'] or hashlib.sha256(data).hexdigest()!=row['sha256']: raise ValueError('invalid_image')
t.call('s3.put',storage.put_object,Bucket=BUCKET,Key=original,Body=data,ContentType=row['content_type'])
metadata=[]
for v,raw in variants(data):
t.call('s3.put',storage.put_object,Bucket=BUCKET,Key=f"variants/{aid}/1/{v['name']}",Body=raw,ContentType=v['content_type']); metadata.append(v)
fault('after-object')
with c.transaction():
current=c.execute('SELECT attempt FROM attachment_jobs WHERE id=%s FOR UPDATE',(j['id'],)).fetchone()
if current['attempt']!=row['attempt']: return True
t.call("postgres.ready",c.execute,"UPDATE attachments SET status='ready',object_key=%s,variants=%s,error_code=NULL,updated_at=now() WHERE id=%s AND status='processing'",(original,Jsonb(metadata),aid))
c.execute('UPDATE attachment_jobs SET lease_until=NULL WHERE id=%s',(j['id'],))
t.ready.record((datetime.now(timezone.utc)-row['created_at']).total_seconds()); t.event('ready')
fault('after-commit')
except (ValueError,UnidentifiedImageError,Image.DecompressionBombError) as e:
with c.transaction():
c.execute('SELECT id FROM attachment_jobs WHERE id=%s FOR UPDATE',(j['id'],)); retry(c,row,'invalid_image',True)
except Exception as e:
print('worker transient:',type(e).__name__,flush=True)
with c.transaction():
c.execute('SELECT id FROM attachment_jobs WHERE id=%s FOR UPDATE',(j['id'],)); retry(c,row,'retry_exhausted',False)
return True
finally: c.execute('SELECT pg_advisory_unlock(hashtextextended(%s,0))',(str(j['id']),))
def cleanup(c,storage):
rows=c.execute("SELECT j.id,j.staging_key FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.status='ready' AND NOT j.cleaned LIMIT 20").fetchall()
for j in rows:
storage.delete_object(Bucket=BUCKET,Key=j['staging_key']); c.execute('UPDATE attachment_jobs SET cleaned=true WHERE id=%s',(j['id'],))
# Orphan uploads only, older than one day; failed jobs retained for replay.
cutoff=time.time()-86400
for page in storage.get_paginator('list_objects_v2').paginate(Bucket=BUCKET,Prefix='staging/'):
for obj in page.get('Contents',[]):
if obj['LastModified'].timestamp()<cutoff and not c.execute('SELECT 1 FROM attachment_jobs WHERE staging_key=%s',(obj['Key'],)).fetchone(): storage.delete_object(Bucket=BUCKET,Key=obj['Key'])
def worker():
t.capacity.set(1); t.busy.set(0)
read_settings = settings()
r = broker()
storage = None
storage_credentials = None
consumer = str(uuid.uuid4())
last = 0
group_ready = False
while True:
try:
values = read_settings()
credentials = (values['S3_ACCESS_KEY'], values['S3_SECRET_KEY'])
if credentials != storage_credentials:
replacement = s3(values)
if storage is not None:
storage.close()
storage = replacement
storage_credentials = credentials
if not group_ready:
try:
r.xgroup_create(STREAM, GROUP, id='0', mkstream=True)
except redis.ResponseError as e:
if 'BUSYGROUP' not in str(e):
raise
group_ready = True
with db(values) as c:
if time.monotonic()-last>30: cleanup(c,storage); last=time.monotonic()
claimed=r.xautoclaim(STREAM,GROUP,consumer,LEASE*1000,'0-0',count=1)[1]
batch=claimed or [m for _,msgs in r.xreadgroup(GROUP,consumer,{STREAM:'>'},count=1,block=1000) for m in msgs]
for mid,fields in batch:
j=json.loads(fields['job']); jid=uuid.UUID(j['job_id'])
with t.tr.start_as_current_span('attachments.consume',context=t.prop.extract(fields),kind=t.SpanKind.CONSUMER,record_exception=False,set_status_on_exception=False) as sp:
start=time.monotonic(); t.busy.set(1); sp.set_attribute("job.attempt",j["attempt"]); t.event('consume'); outcome='error'
try:
signal.alarm(TIMEOUT)
if process(c,storage,dict(id=jid,attempt=j['attempt'])):
r.xack(STREAM,GROUP,mid); r.xdel(STREAM,mid)
row=t.call('postgres.result',c.execute,'SELECT status FROM attachments WHERE id=%s',(j['attachment_id'],)).fetchone(); outcome=row['status'] if row else 'missing'
else: outcome='deferred'
finally:
signal.alarm(0)
if outcome in ('error','failed','queued'): sp.set_status(t.Status(t.StatusCode.ERROR,outcome))
attrs={'job_type':'attachment.process.v1','outcome':outcome}; t.count.add(1,attrs); t.duration.record(time.monotonic()-start,attrs); t.event('job_'+outcome); t.busy.set(0); t.process_stats()
except Exception as e:
print('worker loop:',type(e).__name__,flush=True); time.sleep(2)
def replay(aid):
with db(settings()()) as c, c.transaction():
j=c.execute("SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id=%s AND a.status='failed' FOR UPDATE OF j",(uuid.UUID(aid),)).fetchone()
if not j: raise SystemExit('Only failed jobs can be replayed')
# Keep logical job ID; reset budget using monotonically increasing attempt via new max threshold below.
c.execute('INSERT INTO attachment_replays(job_id) VALUES(%s)',(j['id'],))
c.execute('UPDATE attachment_jobs SET attempt=attempt+1,available_at=now(),published_at=NULL,lease_until=NULL WHERE id=%s',(j['id'],))
c.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s",(aid,))
if __name__=='__main__':
mode=sys.argv[1]
if mode=='publisher': publisher()
elif mode=='worker':
signal.signal(signal.SIGALRM, signal.SIG_DFL)
worker()
elif mode=='replay':
try:
replay(sys.argv[2])
except SecretsUnavailable:
raise SystemExit('OpenBao credentials unavailable') from None
else: raise SystemExit('unknown mode')