forked from mtusi2026/mtusi2026lab7
Выполнение лабораторной работы номер 7
This commit is contained in:
@@ -0,0 +1,151 @@
|
||||
"""Single-concurrency durable image worker; deterministic object keys."""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import socket
|
||||
import time
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
import db
|
||||
import telemetry as ot
|
||||
from opentelemetry import propagate
|
||||
from opentelemetry.trace import SpanKind
|
||||
from attachments import BUCKET, S3, MAX_BYTES, MAX_PIXELS
|
||||
from pipeline import BROKER, STREAM, GROUP, ensure_group, claim, fail
|
||||
|
||||
|
||||
def bounded_image(data):
|
||||
if len(data)>MAX_BYTES:
|
||||
raise ValueError('oversized image')
|
||||
with Image.open(io.BytesIO(data)) as source:
|
||||
if source.width*source.height>MAX_PIXELS:
|
||||
raise ValueError('oversized image')
|
||||
image=ImageOps.exif_transpose(source)
|
||||
image.load()
|
||||
if image.mode in ('RGBA','LA') or 'transparency' in image.info:
|
||||
rgba=image.convert('RGBA')
|
||||
rgb=Image.new('RGB',rgba.size,'white')
|
||||
rgb.paste(rgba,mask=rgba.getchannel('A'))
|
||||
return rgb
|
||||
return image.convert('RGB')
|
||||
|
||||
|
||||
def fit(image,limit):
|
||||
w,h=image.size
|
||||
factor=min(1,limit/max(w,h))
|
||||
return image.resize((max(1,int(w*factor)),max(1,int(h*factor))),Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def variant(job_id,name,image,fmt,mime,quality):
|
||||
buffer=io.BytesIO()
|
||||
image.save(buffer,format=fmt,quality=quality)
|
||||
data=buffer.getvalue()
|
||||
S3.put_object(Bucket=BUCKET,Key=f'variants/{job_id}/{name}',Body=data,ContentType=mime)
|
||||
return {'name':name,'content_type':mime,'size_bytes':len(data),'width':image.width,'height':image.height,
|
||||
'sha256':hashlib.sha256(data).hexdigest()}
|
||||
|
||||
|
||||
def process(job_id):
|
||||
with db.pool.connection() as conn:
|
||||
row=conn.execute("SELECT * FROM attachments WHERE id=%s AND status='processing' FOR UPDATE",(job_id,)).fetchone()
|
||||
if not row:
|
||||
return
|
||||
with ot.tracer.start_as_current_span('s3 read staging'):
|
||||
body=S3.get_object(Bucket=BUCKET,Key=f'staging/{job_id}')['Body']
|
||||
try:
|
||||
data=body.read(MAX_BYTES+1)
|
||||
finally:
|
||||
body.close()
|
||||
if hashlib.sha256(data).hexdigest()!=row['sha256']:
|
||||
raise ValueError('invalid staging checksum')
|
||||
image=bounded_image(data)
|
||||
original=f'original/{job_id}'
|
||||
with ot.tracer.start_as_current_span('s3 write original'):
|
||||
S3.put_object(Bucket=BUCKET,Key=original,Body=data,ContentType=row['content_type'])
|
||||
variants=[variant(job_id,'thumbnail',fit(image,256),'JPEG','image/jpeg',85),
|
||||
variant(job_id,'crop',ImageOps.fit(image,(128,128),Image.Resampling.LANCZOS),'JPEG','image/jpeg',85),
|
||||
variant(job_id,'optimized',fit(image,1280),'WEBP','image/webp',80)]
|
||||
# Explicit local test hook, only armed by operator inside worker container.
|
||||
marker=Path('/tmp/lab-crash-once')
|
||||
if marker.exists():
|
||||
marker.unlink()
|
||||
os._exit(77)
|
||||
with ot.tracer.start_as_current_span('db publish attachment result'):
|
||||
conn.execute("UPDATE attachments SET status='ready',object_key=%s,variants=%s,error_code=NULL,updated_at=now() WHERE id=%s",
|
||||
(original,Jsonb(variants),job_id))
|
||||
conn.execute('UPDATE attachment_jobs SET lease_until=NULL WHERE id=%s',(job_id,))
|
||||
try:
|
||||
S3.delete_object(Bucket=BUCKET,Key=f'staging/{job_id}')
|
||||
with db.pool.connection() as conn:
|
||||
conn.execute("UPDATE attachments SET staging_cleaned=TRUE WHERE id=%s AND status='ready'",(job_id,))
|
||||
except Exception:
|
||||
pass # periodic cleanup retries ready staging deletion
|
||||
|
||||
|
||||
def timeout(*_):
|
||||
raise TimeoutError('worker deadline')
|
||||
|
||||
|
||||
def handle(message_id,fields):
|
||||
job=json.loads(fields['job'])
|
||||
job_id=job['attachment_id']
|
||||
with ot.tracer.start_as_current_span('attachment process',context=propagate.extract(job),kind=SpanKind.CONSUMER):
|
||||
handle_job(message_id,job_id)
|
||||
|
||||
|
||||
def handle_job(message_id,job_id):
|
||||
if claim(job_id):
|
||||
started=time.monotonic()
|
||||
outcome='success'
|
||||
ot.state['worker_busy']=1
|
||||
signal.alarm(90)
|
||||
try:
|
||||
process(job_id)
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError, ValueError):
|
||||
outcome='failed'
|
||||
fail(job_id,permanent=True)
|
||||
except Exception:
|
||||
outcome='retry'
|
||||
fail(job_id)
|
||||
finally:
|
||||
signal.alarm(0)
|
||||
ot.state['worker_busy']=0
|
||||
ot.job_count.add(1,{'outcome':outcome,'job_type':'attachment'})
|
||||
ot.job_duration.record(time.monotonic()-started,{'outcome':outcome,'job_type':'attachment'})
|
||||
ot.logger.info('job_processed',extra={'outcome':outcome})
|
||||
if outcome=='success':
|
||||
with db.pool.connection() as conn:
|
||||
age=conn.execute('SELECT extract(epoch FROM now()-created_at) AS age FROM attachment_jobs WHERE id=%s',(job_id,)).fetchone()
|
||||
ot.ready_duration.record(float(age['age']))
|
||||
# Durable DB result/retry intent precedes acknowledgment.
|
||||
BROKER.xack(STREAM,GROUP,message_id)
|
||||
BROKER.xdel(STREAM,message_id)
|
||||
|
||||
|
||||
def main():
|
||||
db.pool.open(wait=True,timeout=30)
|
||||
signal.signal(signal.SIGALRM,timeout)
|
||||
consumer=socket.gethostname()
|
||||
while True:
|
||||
try:
|
||||
ensure_group()
|
||||
stale=BROKER.xautoclaim(STREAM,GROUP,consumer,120000,'0-0',count=1)[1]
|
||||
if stale:
|
||||
for mid,fields in stale:
|
||||
handle(mid,fields)
|
||||
continue
|
||||
for _,messages in BROKER.xreadgroup(GROUP,consumer,{STREAM:'>'},count=1,block=1000):
|
||||
for mid,fields in messages:
|
||||
handle(mid,fields)
|
||||
except Exception:
|
||||
print('worker will retry',flush=True)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user