194 lines
7.5 KiB
Python
194 lines
7.5 KiB
Python
import asyncio
|
|
import io
|
|
import json
|
|
import logging
|
|
import hashlib
|
|
import random
|
|
|
|
import aio_pika
|
|
from PIL import Image
|
|
from psycopg.rows import dict_row
|
|
|
|
from src.app.config import get_settings
|
|
from src.app.db import init_pool, transaction
|
|
from src.app.s3 import download_fileobj, upload_fileobj
|
|
|
|
# ИМПОРТ ФОНОВОГО ПРОЦЕССА OUTBOX
|
|
from worker.outbox_publisher import publish_loop
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger("worker")
|
|
|
|
MAX_PIXELS = 40_000_000
|
|
|
|
|
|
class PermanentError(Exception):
|
|
"""Ошибка, которую нет смысла повторять (битый файл)."""
|
|
pass
|
|
|
|
|
|
def generate_variants(img: Image.Image):
|
|
variants = {}
|
|
|
|
thumb = img.copy()
|
|
if thumb.mode in ("RGBA", "P"):
|
|
thumb = thumb.convert("RGB")
|
|
thumb.thumbnail((256, 256))
|
|
variants["thumbnail"] = (thumb, "image/jpeg", "JPEG", {"quality": 85})
|
|
|
|
crop = img.copy()
|
|
if crop.mode in ("RGBA", "P"):
|
|
crop = crop.convert("RGB")
|
|
min_dim = min(crop.size)
|
|
left = (crop.width - min_dim) // 2
|
|
top = (crop.height - min_dim) // 2
|
|
crop = crop.crop((left, top, left + min_dim, top + min_dim))
|
|
crop = crop.resize((128, 128), Image.Resampling.LANCZOS)
|
|
variants["crop"] = (crop, "image/jpeg", "JPEG", {"quality": 85})
|
|
|
|
opt = img.copy()
|
|
if opt.mode in ("RGBA", "P", "L"):
|
|
opt = opt.convert("RGB")
|
|
opt.info.clear()
|
|
variants["optimized"] = (opt, "image/webp", "WEBP", {"quality": 80, "method": 4})
|
|
|
|
return variants
|
|
|
|
|
|
async def _re_publish(body: bytes):
|
|
settings = get_settings()
|
|
connection = await aio_pika.connect_robust(settings.broker_url)
|
|
async with connection:
|
|
channel = await connection.channel()
|
|
await channel.declare_queue(settings.broker_queue, durable=True)
|
|
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT)
|
|
await channel.default_exchange.publish(msg, routing_key=settings.broker_queue)
|
|
|
|
|
|
async def _send_to_dlq(body: bytes):
|
|
settings = get_settings()
|
|
connection = await aio_pika.connect_robust(settings.broker_url)
|
|
async with connection:
|
|
channel = await connection.channel()
|
|
await channel.declare_queue("dead_letters", durable=True)
|
|
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT)
|
|
await channel.default_exchange.publish(msg, routing_key="dead_letters")
|
|
|
|
|
|
async def process_message(message: aio_pika.IncomingMessage):
|
|
async with message.process(requeue=False, reject_on_redelivered=False):
|
|
data = json.loads(message.body)
|
|
att_id = data["attachment_id"]
|
|
obj_key = data["object_key"]
|
|
|
|
logger.info(f"Processing attachment {att_id}")
|
|
|
|
with transaction() as conn:
|
|
with conn.cursor(row_factory=dict_row) as cur:
|
|
cur.execute("SELECT attempts FROM attachment_retries WHERE attachment_id = %s", (att_id,))
|
|
row = cur.fetchone()
|
|
attempts = row["attempts"] if row else 0
|
|
|
|
if attempts >= 5:
|
|
logger.error(f"Max retries (5) reached for {att_id}. Sending to DLQ.")
|
|
cur.execute("UPDATE attachments SET status='failed', error_code='max_retries_exceeded', updated_at=now() WHERE id=%s", (att_id,))
|
|
await _send_to_dlq(message.body)
|
|
return
|
|
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO attachment_retries (attachment_id, attempts)
|
|
VALUES (%s, 1)
|
|
ON CONFLICT (attachment_id) DO UPDATE SET attempts = attachment_retries.attempts + 1
|
|
""", (att_id,)
|
|
)
|
|
cur.execute("UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s", (att_id,))
|
|
|
|
try:
|
|
body = download_fileobj(obj_key)
|
|
img = Image.open(body)
|
|
|
|
width, height = img.size
|
|
if width * height > MAX_PIXELS:
|
|
raise PermanentError(f"Image too large: {width}x{height} pixels")
|
|
|
|
img.load()
|
|
|
|
variants = generate_variants(img)
|
|
|
|
with transaction() as conn:
|
|
with conn.cursor() as cur:
|
|
for name, (var_img, ct, fmt, save_args) in variants.items():
|
|
buf = io.BytesIO()
|
|
var_img.save(buf, format=fmt, **save_args)
|
|
|
|
var_bytes = buf.getvalue()
|
|
sha256 = hashlib.sha256(var_bytes).hexdigest()
|
|
var_key = f"chats/{att_id}/variants/{name}"
|
|
|
|
upload_fileobj(io.BytesIO(var_bytes), var_key, ct)
|
|
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO attachment_variants (attachment_id, name, content_type, size_bytes, width, height, sha256, object_key)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
|
ON CONFLICT (attachment_id, name) DO UPDATE SET
|
|
content_type = EXCLUDED.content_type,
|
|
size_bytes = EXCLUDED.size_bytes,
|
|
width = EXCLUDED.width,
|
|
height = EXCLUDED.height,
|
|
sha256 = EXCLUDED.sha256,
|
|
object_key = EXCLUDED.object_key
|
|
""",
|
|
(att_id, name, ct, len(var_bytes), var_img.width, var_img.height, sha256, var_key)
|
|
)
|
|
|
|
cur.execute("UPDATE attachments SET status='ready', error_code=NULL, updated_at=now() WHERE id=%s", (att_id,))
|
|
cur.execute("DELETE FROM attachment_retries WHERE attachment_id = %s", (att_id,))
|
|
|
|
logger.info(f"Successfully processed {att_id}")
|
|
|
|
except PermanentError as e:
|
|
logger.error(f"Permanent error for {att_id}: {e}")
|
|
with transaction() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", ("invalid_image", att_id))
|
|
|
|
except Exception as e:
|
|
logger.error(f"Temporary error for {att_id}: {e}")
|
|
|
|
delay = min(2 ** attempts, 60)
|
|
jitter = random.uniform(0, 3)
|
|
total_delay = delay + jitter
|
|
|
|
logger.info(f"Retrying {att_id} in {total_delay:.2f} seconds (attempt {attempts+1}/5)")
|
|
await asyncio.sleep(total_delay)
|
|
await _re_publish(message.body)
|
|
|
|
|
|
async def main():
|
|
init_pool()
|
|
settings = get_settings()
|
|
|
|
# ЗАПУСК ФОНОВОГО ПРОЦЕССА OUTBOX
|
|
asyncio.create_task(publish_loop())
|
|
|
|
while True:
|
|
try:
|
|
connection = await aio_pika.connect_robust(settings.broker_url)
|
|
break
|
|
except Exception as e:
|
|
logger.warning(f"Broker not ready, waiting 5 seconds... ({e})")
|
|
await asyncio.sleep(5)
|
|
|
|
async with connection:
|
|
channel = await connection.channel()
|
|
await channel.set_qos(prefetch_count=1)
|
|
queue = await channel.declare_queue(settings.broker_queue, durable=True)
|
|
logger.info("Worker started, waiting for messages...")
|
|
await queue.consume(process_message)
|
|
await asyncio.Future()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main()) |