Files
mtusi2026lab5/src/worker.py
T
2026-10-26 10:19:05 +03:00

96 lines
3.6 KiB
Python

"""RabbitMQ consumer for the version-1 attachment pipeline."""
import asyncio
from hashlib import sha256
from io import BytesIO
import json
import logging
import os
from uuid import UUID
from PIL import Image, ImageOps
from .broker import QUEUE, _connection
from .config import load_settings
from .storage.postgres import PostgresStore
from .storage.s3 import S3Settings, S3Store
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
image = ImageOps.exif_transpose(source)
if image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info):
background = Image.new("RGBA", image.size, "white")
background.alpha_composite(image.convert("RGBA"))
image = background.convert("RGB")
else:
image = image.convert("RGB")
image.thumbnail((256, 256), Image.Resampling.LANCZOS)
output = BytesIO()
image.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue(), image.width, image.height
async def process(store: PostgresStore, s3: S3Store, payload: dict) -> None:
attachment_id = UUID(payload["attachment_id"])
attachment = await store.claim_attachment_job(attachment_id)
if attachment is None:
return
original_key = f"originals/{attachment_id}"
variant_key = f"variants/{attachment_id}/thumbnail.jpg"
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
rendered, width, height = await asyncio.to_thread(thumbnail, original)
await s3.put(variant_key, BytesIO(rendered), len(rendered), "image/jpeg")
await store.complete_attachment_job(attachment_id, original_key, {
"object_key": variant_key, "content_type": "image/jpeg", "size_bytes": len(rendered),
"width": width, "height": height, "sha256": sha256(rendered).hexdigest(),
})
await s3.delete(attachment["staging_key"])
def main() -> None:
settings = load_settings()
store = PostgresStore(settings.database_url)
asyncio.run(store.connect())
s3 = S3Store(S3Settings.load())
connection = _connection()
channel = connection.channel()
channel.basic_qos(prefetch_count=max(1, int(os.environ.get("WORKER_CONCURRENCY", "2"))))
def consume(ch, method, properties, body):
del properties
try:
payload = json.loads(body)
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
raise ValueError("unexpected broker payload")
asyncio.run(process(store, s3, payload))
except Exception:
logging.exception("job failed")
try:
attachment_id = UUID(payload["attachment_id"])
retry = asyncio.run(store.retry_attachment_job(
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5")))
))
except Exception:
retry = False
if retry:
ch.basic_nack(method.delivery_tag, requeue=True)
else:
ch.basic_ack(method.delivery_tag)
else:
ch.basic_ack(method.delivery_tag)
try:
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
channel.start_consuming()
finally:
connection.close()
s3.client.close()
asyncio.run(store.close())
if __name__ == "__main__":
main()