Files
mtusi2026lab7/app/worker.py
T
2026-12-04 13:41:59 +03:00

81 lines
2.9 KiB
Python

import os
import hashlib
import io
import logging
import time
from PIL import Image, ImageOps
from redis import Redis
from psycopg.types.json import Jsonb
from media import bucket, s3
from store import db, stamp
queue = Redis.from_url(os.environ["REDIS_URL"],decode_responses=True)
log = logging.getLogger("worker")
def update(c,doc):
doc["updated_at"] = stamp()
c.execute("update attachments set doc=%s where id=%s",(Jsonb(doc),doc["id"]))
def process(att):
with db() as c:
row = c.execute("select doc,attempts from attachments where id=%s for update",(att,)).fetchone()
if not row or row[0]["status"] in ("failed","ready"):
return
doc, attempts = row
try:
source = s3.get_object(Bucket=bucket,Key=att)["Body"].read()
with Image.open(io.BytesIO(source)) as img:
oriented = ImageOps.exif_transpose(img).convert("RGBA")
bg = Image.new("RGB",oriented.size,"white")
bg.paste(oriented,mask=oriented.getchannel("A"))
scale = min(1,256/bg.width,256/bg.height)
thumb = bg.resize((max(1,int(bg.width*scale)),max(1,int(bg.height*scale))),Image.Resampling.LANCZOS)
output = io.BytesIO()
thumb.save(output,"JPEG",quality=85)
data = output.getvalue()
s3.put_object(Bucket=bucket,Key=att+"/thumbnail",Body=data,ContentType="image/jpeg")
doc["variants"] = [dict(name="thumbnail",width=thumb.width,height=thumb.height,size_bytes=len(data),
content_type="image/jpeg",sha256=hashlib.sha256(data).hexdigest())]
doc["status"] = "ready"
except Exception:
c.execute("update attachments set attempts=attempts+1 where id=%s",(att,))
doc["status"] = "failed" if attempts>=4 else "queued"
if doc["status"]=="failed":
doc["error_code"]="retry_exhausted"
update(c,doc)
return doc["status"]
def dispatch():
with db() as c:
rows = c.execute("select id,doc from attachments where doc->>'status' in ('queued','processing') order by attempts,id limit 100 for update skip locked")
for att,doc in rows.fetchall():
queue.zadd("jobs",{att:time.time()},nx=True)
doc["status"]="processing"
update(c,doc)
from observability import instrument
observe = instrument('worker')
def run():
while True:
try:
dispatch()
job = queue.zrange("jobs",0,0)
if job:
with observe('thumbnail') as attrs:
attrs['outcome'] = process(job[0]) or 'duplicate'
queue.zrem("jobs",job[0])
else:
time.sleep(.3)
except Exception:
log.warning("worker dependency unavailable")
time.sleep(2)
if __name__=="__main__":
run()