4grade_and_report
This commit is contained in:
+90
-30
@@ -3,6 +3,7 @@ import io
|
||||
import json
|
||||
import logging
|
||||
import hashlib
|
||||
import random
|
||||
|
||||
import aio_pika
|
||||
from PIL import Image
|
||||
@@ -12,22 +13,29 @@ 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 = {}
|
||||
|
||||
# 1. Thumbnail (макс 256x256, сохраняем пропорции)
|
||||
thumb = img.copy()
|
||||
# Если картинка имеет прозрачность (RGBA), конвертируем в RGB для JPEG
|
||||
if thumb.mode in ("RGBA", "P"):
|
||||
thumb = thumb.convert("RGB")
|
||||
thumb.thumbnail((256, 256))
|
||||
variants["thumbnail"] = thumb
|
||||
variants["thumbnail"] = (thumb, "image/jpeg", "JPEG", {"quality": 85})
|
||||
|
||||
# 2. Crop (квадрат 512x512 по центру)
|
||||
crop = img.copy()
|
||||
if crop.mode in ("RGBA", "P"):
|
||||
crop = crop.convert("RGB")
|
||||
@@ -35,46 +43,84 @@ def generate_variants(img: Image.Image):
|
||||
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((512, 512), Image.Resampling.LANCZOS)
|
||||
variants["crop"] = crop
|
||||
crop = crop.resize((128, 128), Image.Resampling.LANCZOS)
|
||||
variants["crop"] = (crop, "image/jpeg", "JPEG", {"quality": 85})
|
||||
|
||||
# 3. Optimized (просто оригинал в JPEG)
|
||||
opt = img.convert("RGB")
|
||||
variants["optimized"] = opt
|
||||
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():
|
||||
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}")
|
||||
|
||||
try:
|
||||
# 1. Обновляем статус на processing
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s", (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
|
||||
|
||||
# 2. Качаем из S3
|
||||
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)
|
||||
img.load() # принудительная загрузка в память для обнаружения битых файлов
|
||||
|
||||
width, height = img.size
|
||||
if width * height > MAX_PIXELS:
|
||||
raise PermanentError(f"Image too large: {width}x{height} pixels")
|
||||
|
||||
img.load()
|
||||
|
||||
# 3. Генерируем варианты
|
||||
variants = generate_variants(img)
|
||||
|
||||
# 4. Сохраняем в S3 и БД
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
for name, var_img in variants.items():
|
||||
for name, (var_img, ct, fmt, save_args) in variants.items():
|
||||
buf = io.BytesIO()
|
||||
# Всегда сохраняем как JPEG (так требует контракт)
|
||||
ct = "image/jpeg"
|
||||
var_img.save(buf, format="JPEG", quality=85)
|
||||
var_img.save(buf, format=fmt, **save_args)
|
||||
|
||||
var_bytes = buf.getvalue()
|
||||
sha256 = hashlib.sha256(var_bytes).hexdigest()
|
||||
@@ -98,25 +144,39 @@ async def process_message(message: aio_pika.IncomingMessage):
|
||||
)
|
||||
|
||||
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 Exception as e:
|
||||
logger.error(f"Error processing {att_id}: {e}")
|
||||
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", ("processing_error", att_id))
|
||||
raise e
|
||||
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 # если подключились - выходим из цикла
|
||||
break
|
||||
except Exception as e:
|
||||
logger.warning(f"Broker not ready, waiting 5 seconds... ({e})")
|
||||
await asyncio.sleep(5)
|
||||
@@ -129,6 +189,6 @@ async def main():
|
||||
await queue.consume(process_message)
|
||||
await asyncio.Future()
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,52 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import aio_pika
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import transaction
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
logger = logging.getLogger("outbox")
|
||||
|
||||
async def publish_loop():
|
||||
settings = get_settings()
|
||||
|
||||
# Ждем брокер
|
||||
while True:
|
||||
try:
|
||||
connection = await aio_pika.connect_robust(settings.broker_url)
|
||||
break
|
||||
except Exception:
|
||||
await asyncio.sleep(5)
|
||||
|
||||
async with connection:
|
||||
channel = await connection.channel()
|
||||
await channel.declare_queue(settings.broker_queue, durable=True)
|
||||
|
||||
while True:
|
||||
try:
|
||||
# Забираем необработанные сообщения
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"SELECT id, payload FROM outbox_messages WHERE processed_at IS NULL ORDER BY created_at LIMIT 10 FOR UPDATE SKIP LOCKED"
|
||||
)
|
||||
messages = cur.fetchall()
|
||||
|
||||
for msg in messages:
|
||||
payload = msg["payload"]
|
||||
# Отправляем в RabbitMQ
|
||||
message = aio_pika.Message(
|
||||
body=json.dumps(payload).encode(),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT
|
||||
)
|
||||
await channel.default_exchange.publish(message, routing_key=settings.broker_queue)
|
||||
|
||||
# Помечаем как обработанное
|
||||
cur.execute("UPDATE outbox_messages SET processed_at = now() WHERE id = %s", (msg["id"],))
|
||||
|
||||
if not messages:
|
||||
await asyncio.sleep(1) # Если пусто, ждем секунду
|
||||
except Exception as e:
|
||||
logger.error(f"Outbox error: {e}")
|
||||
await asyncio.sleep(2)
|
||||
Reference in New Issue
Block a user