forked from mtusi2026/mtusi2026lab6
3_grade
This commit is contained in:
+113
-91
@@ -8,34 +8,37 @@ import random
|
||||
import aio_pika
|
||||
from PIL import Image
|
||||
from psycopg.rows import dict_row
|
||||
from opentelemetry import trace
|
||||
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import init_pool, transaction
|
||||
from src.app.s3 import download_fileobj, upload_fileobj
|
||||
from src.app.otel import setup_otel
|
||||
from src.app.logging_config import setup_logging
|
||||
|
||||
# ИМПОРТ ФОНОВОГО ПРОЦЕССА OUTBOX
|
||||
from worker.outbox_publisher import publish_loop
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger("worker")
|
||||
|
||||
tracer = trace.get_tracer("messenger-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")
|
||||
@@ -45,13 +48,13 @@ def generate_variants(img: Image.Image):
|
||||
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
|
||||
|
||||
|
||||
@@ -76,111 +79,130 @@ async def _send_to_dlq(body: bytes):
|
||||
|
||||
|
||||
async def process_message(message: aio_pika.IncomingMessage):
|
||||
async with message.process(requeue=False, reject_on_redelivered=False):
|
||||
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 tracer.start_as_current_span("worker.process_attachment") as span:
|
||||
span.set_attribute("attachment.id", att_id)
|
||||
logger.info("Processing attachment %s", att_id)
|
||||
|
||||
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)
|
||||
|
||||
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("Max retries (5) reached for %s. Sending to DLQ.", att_id)
|
||||
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)
|
||||
"UPDATE attachments SET status='failed', error_code='max_retries_exceeded', updated_at=now() WHERE id=%s",
|
||||
(att_id,),
|
||||
)
|
||||
|
||||
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,))
|
||||
await _send_to_dlq(message.body)
|
||||
span.set_attribute("worker.result", "max_retries")
|
||||
return
|
||||
|
||||
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)
|
||||
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,))
|
||||
|
||||
span.set_attribute("worker.result", "ready")
|
||||
logger.info("Successfully processed %s", att_id)
|
||||
|
||||
except PermanentError as e:
|
||||
logger.error("Permanent error for %s: %s", 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),
|
||||
)
|
||||
span.set_attribute("worker.result", "permanent_error")
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Temporary error for %s: %s", att_id, e)
|
||||
span.set_attribute("worker.result", "retry")
|
||||
delay = min(2 ** attempts, 60)
|
||||
jitter = random.uniform(0, 3)
|
||||
total_delay = delay + jitter
|
||||
logger.info(
|
||||
"Retrying %s in %.2f seconds (attempt %s/5)", att_id, total_delay, attempts + 1
|
||||
)
|
||||
await asyncio.sleep(total_delay)
|
||||
await _re_publish(message.body)
|
||||
|
||||
|
||||
async def main():
|
||||
setup_logging(get_settings().log_level)
|
||||
setup_otel("messenger-worker")
|
||||
|
||||
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})")
|
||||
logger.warning("Broker not ready, waiting 5 seconds... (%s)", e)
|
||||
await asyncio.sleep(5)
|
||||
|
||||
|
||||
async with connection:
|
||||
channel = await connection.channel()
|
||||
await channel.set_qos(prefetch_count=1)
|
||||
@@ -189,6 +211,6 @@ async def main():
|
||||
await queue.consume(process_message)
|
||||
await asyncio.Future()
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+29
-20
@@ -2,51 +2,60 @@ import asyncio
|
||||
import json
|
||||
import logging
|
||||
import aio_pika
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import transaction
|
||||
from opentelemetry import trace
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import transaction
|
||||
from src.app.otel import setup_otel
|
||||
from src.app.logging_config import setup_logging
|
||||
|
||||
logger = logging.getLogger("outbox")
|
||||
tracer = trace.get_tracer("messenger-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"
|
||||
"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"],))
|
||||
|
||||
with tracer.start_as_current_span("outbox.publish") as span:
|
||||
span.set_attribute("outbox.message_id", str(msg["id"]))
|
||||
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) # Если пусто, ждем секунду
|
||||
await asyncio.sleep(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Outbox error: {e}")
|
||||
logger.error("Outbox error: %s", e)
|
||||
await asyncio.sleep(2)
|
||||
Reference in New Issue
Block a user