Files
mtusi2026lab6-fork/worker/main.py
T
2026-11-27 14:03:46 +03:00

259 lines
11 KiB
Python

import asyncio
import io
import json
import logging
import hashlib
import random
import time
import aio_pika
from PIL import Image
from psycopg.rows import dict_row
from opentelemetry import trace, context as otel_context
from opentelemetry.propagate import extract
# Импорты для метрик
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry import metrics as otel_metrics
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
from worker.metrics import worker_duration, worker_processed, worker_in_flight
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")
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, headers: dict):
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, headers=headers)
await channel.default_exchange.publish(msg, routing_key=settings.broker_queue)
async def _send_to_dlq(body: bytes, headers: dict):
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, headers=headers)
await channel.default_exchange.publish(msg, routing_key="dead_letters")
async def process_message(message: aio_pika.IncomingMessage):
headers = message.headers or {}
ctx = extract(headers)
token = otel_context.attach(ctx)
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"]
with tracer.start_as_current_span("worker.process_attachment") as span:
span.set_attribute("attachment.id", att_id)
worker_in_flight.add(1)
start_time = time.time()
result = "error"
attempts = 0
logger.info("Processing attachment %s", att_id)
try:
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("Max retries (5) reached for %s. Sending to DLQ.", att_id)
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, headers)
span.set_attribute("worker.result", "max_retries")
result = "error_max_retries"
worker_duration.record(time.time() - start_time)
worker_processed.add(1, {"result": result})
worker_in_flight.add(-1)
otel_context.detach(token)
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,),
)
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)
result = "success"
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")
result = "error_permanent"
except Exception as e:
logger.error("Error processing %s: %s", att_id, e)
span.set_attribute("worker.result", "error")
result = "error"
if not isinstance(e, PermanentError):
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, headers)
finally:
duration = time.time() - start_time
worker_duration.record(duration, {"result": result})
worker_processed.add(1, {"result": result})
worker_in_flight.add(-1)
otel_context.detach(token)
async def main():
setup_logging(get_settings().log_level)
setup_otel("messenger-worker")
# --- ЭКСПОРТ МЕТРИК ИЗ ВОРКЕРА ---
s = get_settings()
resource = Resource.create({"service.name": "messenger-worker"})
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=s.otel_exporter_otlp_endpoint, insecure=True),
export_interval_millis=5000,
)
meter_provider = MeterProvider(resource=resource, metric_readers=[reader])
otel_metrics.set_meter_provider(meter_provider)
# ---------------------------------
init_pool()
settings = get_settings()
asyncio.create_task(publish_loop())
while True:
try:
connection = await aio_pika.connect_robust(settings.broker_url)
break
except Exception as 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)
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())