forked from mtusi2026/mtusi2026lab5
397 lines
13 KiB
Python
397 lines
13 KiB
Python
import asyncio
|
|
import hashlib
|
|
import io
|
|
import os
|
|
import json
|
|
import logging
|
|
import time
|
|
import random
|
|
from uuid import UUID
|
|
|
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
|
from sqlalchemy import text
|
|
|
|
from src.database import SessionFactory
|
|
from src.queue import QUEUE, connect
|
|
from src.storage import get_object, put_object
|
|
from src.images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
MAX_PROCESSING_SECONDS = float(
|
|
os.getenv("MAX_PROCESSING_SECONDS", "30")
|
|
)
|
|
|
|
|
|
class PermanentProcessingError(Exception):
|
|
pass
|
|
|
|
|
|
def retry_delay(attempt: int) -> float:
|
|
base = min(60.0, 2.0 ** attempt)
|
|
return base * random.uniform(0.75, 1.25)
|
|
|
|
|
|
def validate_worker_image(body: bytes):
|
|
if not body or len(body) > MAX_UPLOAD_BYTES:
|
|
raise PermanentProcessingError("invalid_image_size")
|
|
|
|
try:
|
|
with Image.open(io.BytesIO(body)) as image:
|
|
if image.format not in {"PNG", "JPEG"}:
|
|
raise PermanentProcessingError("unsupported_image_format")
|
|
|
|
if image.width * image.height > MAX_IMAGE_PIXELS:
|
|
raise PermanentProcessingError("image_pixel_limit")
|
|
|
|
image.verify()
|
|
|
|
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError) as exc:
|
|
raise PermanentProcessingError("invalid_image") from exc
|
|
|
|
|
|
def make_thumbnail(body: bytes):
|
|
with Image.open(io.BytesIO(body)) as source:
|
|
source.load()
|
|
image = ImageOps.exif_transpose(source)
|
|
image.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
|
|
|
if image.mode != "RGB":
|
|
rgba = image.convert("RGBA")
|
|
background = Image.new("RGBA", rgba.size, "white")
|
|
background.alpha_composite(rgba)
|
|
image = background.convert("RGB")
|
|
|
|
output = io.BytesIO()
|
|
image.save(output, format="JPEG", quality=85, optimize=True)
|
|
|
|
return output.getvalue(), image.width, image.height
|
|
|
|
|
|
def make_crop(body: bytes):
|
|
with Image.open(io.BytesIO(body)) as source:
|
|
source.load()
|
|
image = ImageOps.exif_transpose(source).convert("RGB")
|
|
image = ImageOps.fit(
|
|
image,
|
|
(128, 128),
|
|
method=Image.Resampling.LANCZOS,
|
|
centering=(0.5, 0.5),
|
|
)
|
|
|
|
output = io.BytesIO()
|
|
image.save(output, format="JPEG", quality=85, optimize=True)
|
|
|
|
return output.getvalue(), image.width, image.height
|
|
|
|
|
|
def make_optimized(body: bytes):
|
|
with Image.open(io.BytesIO(body)) as source:
|
|
source.load()
|
|
image = ImageOps.exif_transpose(source).convert("RGB")
|
|
|
|
output = io.BytesIO()
|
|
image.save(output, format="WEBP", quality=80, method=4)
|
|
|
|
return output.getvalue(), image.width, image.height
|
|
|
|
|
|
async def process(payload: dict):
|
|
job_id = UUID(payload["job_id"])
|
|
attachment_id = UUID(payload["attachment_id"])
|
|
generation = payload.get("generation", 1)
|
|
|
|
async with SessionFactory() as session:
|
|
async with session.begin():
|
|
result = await session.execute(
|
|
text("""
|
|
SELECT j.status, j.attempt, j.generation,
|
|
a.s3_key, a.content_type, a.chat_id
|
|
FROM attachment_jobs j
|
|
JOIN attachments a ON a.id = j.attachment_id
|
|
WHERE j.id = :job_id
|
|
AND j.attachment_id = :attachment_id
|
|
FOR UPDATE OF j
|
|
"""),
|
|
{"job_id": job_id, "attachment_id": attachment_id},
|
|
)
|
|
|
|
row = result.one_or_none()
|
|
|
|
if row is None or row.status in ("ready", "failed"):
|
|
return
|
|
|
|
if row.attempt != payload["attempt"]:
|
|
return
|
|
|
|
if row.generation != generation:
|
|
return
|
|
|
|
if row.status == "processing":
|
|
return
|
|
|
|
await session.execute(
|
|
text("""
|
|
UPDATE attachment_jobs
|
|
SET status = 'processing', started_at = now()
|
|
WHERE id = :id
|
|
"""),
|
|
{"id": job_id},
|
|
)
|
|
|
|
await session.execute(
|
|
text("""
|
|
UPDATE attachments
|
|
SET status = 'processing', updated_at = now()
|
|
WHERE id = :id
|
|
"""),
|
|
{"id": attachment_id},
|
|
)
|
|
|
|
try:
|
|
body = await get_object(row.s3_key)
|
|
validate_worker_image(body)
|
|
thumbnail, width, height = await asyncio.to_thread(
|
|
make_thumbnail, body
|
|
)
|
|
|
|
crop, crop_width, crop_height = await asyncio.to_thread(
|
|
make_crop, body
|
|
)
|
|
|
|
optimized, optimized_width, optimized_height = await asyncio.to_thread(
|
|
make_optimized, body
|
|
)
|
|
|
|
original_key = (
|
|
f"attachments/{row.chat_id}/{attachment_id}/g{generation}/original"
|
|
)
|
|
thumbnail_key = (
|
|
f"variants/{row.chat_id}/{attachment_id}/g{generation}/thumbnail.jpg"
|
|
)
|
|
|
|
await put_object(original_key, body, row.content_type)
|
|
await put_object(thumbnail_key, thumbnail, "image/jpeg")
|
|
crop_key = (
|
|
f"variants/{row.chat_id}/{attachment_id}/g{generation}/crop.jpg"
|
|
)
|
|
optimized_key = (
|
|
f"variants/{row.chat_id}/{attachment_id}/g{generation}/optimized.webp"
|
|
)
|
|
|
|
await put_object(crop_key, crop, "image/jpeg")
|
|
await put_object(optimized_key, optimized, "image/webp")
|
|
|
|
variant = {
|
|
"name": "thumbnail",
|
|
"s3_key": thumbnail_key,
|
|
"content_type": "image/jpeg",
|
|
"size_bytes": len(thumbnail),
|
|
"width": width,
|
|
"height": height,
|
|
"sha256": hashlib.sha256(thumbnail).hexdigest(),
|
|
}
|
|
|
|
async with SessionFactory() as session:
|
|
async with session.begin():
|
|
result = await session.execute(
|
|
text("""
|
|
SELECT status, attempt, generation
|
|
FROM attachment_jobs
|
|
WHERE id = :id
|
|
FOR UPDATE
|
|
"""),
|
|
{"id": job_id},
|
|
)
|
|
|
|
current = result.one_or_none()
|
|
|
|
if (
|
|
current is None
|
|
or current.status != "processing"
|
|
or current.attempt != row.attempt
|
|
or current.generation != generation
|
|
):
|
|
return
|
|
await session.execute(
|
|
text("""
|
|
UPDATE attachments
|
|
SET status = 'ready',
|
|
s3_key = :key,
|
|
variants = CAST(:variants AS json),
|
|
error_code = NULL,
|
|
updated_at = now()
|
|
WHERE id = :id
|
|
"""),
|
|
{
|
|
"id": attachment_id,
|
|
"key": original_key,
|
|
"variants": json.dumps([
|
|
variant,
|
|
{
|
|
"name": "crop",
|
|
"s3_key": crop_key,
|
|
"content_type": "image/jpeg",
|
|
"size_bytes": len(crop),
|
|
"width": crop_width,
|
|
"height": crop_height,
|
|
"sha256": hashlib.sha256(crop).hexdigest(),
|
|
},
|
|
{
|
|
"name": "optimized",
|
|
"s3_key": optimized_key,
|
|
"content_type": "image/webp",
|
|
"size_bytes": len(optimized),
|
|
"width": optimized_width,
|
|
"height": optimized_height,
|
|
"sha256": hashlib.sha256(optimized).hexdigest(),
|
|
},
|
|
]),
|
|
},
|
|
)
|
|
|
|
await session.execute(
|
|
text("""
|
|
UPDATE attachment_jobs
|
|
SET status = 'ready',
|
|
next_attempt_at = NULL,
|
|
last_error_code = NULL,
|
|
finished_at = now()
|
|
WHERE id = :id
|
|
"""),
|
|
{"id": job_id},
|
|
)
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
logging.exception("Processing failed: %s", attachment_id)
|
|
|
|
permanent = isinstance(exc, PermanentProcessingError)
|
|
|
|
error_code = (
|
|
|
|
str(exc)[:64]
|
|
|
|
if permanent
|
|
|
|
else "temporary_processing_error"
|
|
|
|
)
|
|
|
|
async with SessionFactory() as session:
|
|
async with session.begin():
|
|
result = await session.execute(
|
|
text("""
|
|
SELECT status, attempt, generation
|
|
FROM attachment_jobs
|
|
WHERE id = :id
|
|
FOR UPDATE
|
|
"""),
|
|
{"id": job_id},
|
|
)
|
|
|
|
current = result.one_or_none()
|
|
|
|
if (
|
|
current is None
|
|
or current.status != "processing"
|
|
or current.attempt != row.attempt
|
|
or current.generation != generation
|
|
):
|
|
return
|
|
if permanent or row.attempt >= 5:
|
|
await session.execute(
|
|
text("""
|
|
UPDATE attachment_jobs
|
|
SET status = 'failed',
|
|
next_attempt_at = NULL,
|
|
last_error_code = :error_code,
|
|
finished_at = now()
|
|
WHERE id = :id
|
|
"""),
|
|
{"id": job_id, "error_code": error_code},
|
|
)
|
|
|
|
await session.execute(
|
|
text("""
|
|
UPDATE attachments
|
|
SET status = 'failed',
|
|
error_code = :error_code,
|
|
updated_at = now()
|
|
WHERE id = :id
|
|
"""),
|
|
{
|
|
"id": attachment_id,
|
|
"error_code": error_code,
|
|
},
|
|
)
|
|
else:
|
|
await session.execute(
|
|
text("""
|
|
UPDATE attachment_jobs
|
|
SET status = 'queued',
|
|
attempt = attempt + 1,
|
|
published_at = NULL,
|
|
started_at = NULL,
|
|
next_attempt_at = now() + (:delay * interval '1 second'),
|
|
last_error_code = :error_code
|
|
WHERE id = :id
|
|
"""),
|
|
{
|
|
"id": job_id,
|
|
"delay": retry_delay(row.attempt),
|
|
"error_code": error_code,
|
|
}
|
|
)
|
|
|
|
await session.execute(
|
|
text("""
|
|
UPDATE attachments
|
|
SET status = 'queued', updated_at = now()
|
|
WHERE id = :id
|
|
"""),
|
|
{"id": attachment_id},
|
|
)
|
|
|
|
|
|
def main():
|
|
while True:
|
|
connection = None
|
|
|
|
try:
|
|
connection, channel = connect()
|
|
channel.basic_qos(prefetch_count=1)
|
|
|
|
loop = asyncio.new_event_loop()
|
|
asyncio.set_event_loop(loop)
|
|
|
|
def callback(ch, method, properties, body):
|
|
try:
|
|
loop.run_until_complete(process(json.loads(body)))
|
|
ch.basic_ack(delivery_tag=method.delivery_tag)
|
|
except Exception:
|
|
logging.exception("Worker processing error")
|
|
ch.basic_nack(
|
|
delivery_tag=method.delivery_tag,
|
|
requeue=True,
|
|
)
|
|
time.sleep(2)
|
|
|
|
channel.basic_consume(
|
|
queue=QUEUE,
|
|
on_message_callback=callback,
|
|
)
|
|
channel.start_consuming()
|
|
|
|
except Exception:
|
|
logging.exception("Worker reconnect")
|
|
time.sleep(3)
|
|
|
|
finally:
|
|
if connection and connection.is_open:
|
|
connection.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |