forked from mtusi2026/mtusi2026lab5
feat: ЛР5 - асинхронная обработка вложений, RabbitMQ и transactional outbox
This commit is contained in:
+107
@@ -0,0 +1,107 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import aio_pika
|
||||
from aio_pika import DeliveryMode, ExchangeType
|
||||
|
||||
from app.config import BROKER_URL
|
||||
|
||||
logger = logging.getLogger("messenger.broker")
|
||||
|
||||
EXCHANGE_NAME = "messenger.attachments"
|
||||
QUEUE_NAME = "messenger.attachments.jobs"
|
||||
ROUTING_KEY = "attachment.process"
|
||||
|
||||
DLX_NAME = "messenger.attachments.dlx"
|
||||
DLQ_NAME = "messenger.attachments.dlq"
|
||||
DL_ROUTING_KEY = "attachment.dead"
|
||||
|
||||
|
||||
async def setup_broker_topology(channel: aio_pika.abc.AbstractChannel) -> tuple[aio_pika.abc.AbstractExchange, aio_pika.abc.AbstractQueue]:
|
||||
"""Настраивает durable exchange, durable очереди и связку с Dead Letter Exchange."""
|
||||
# 1. Dead Letter Exchange и Dead Letter Queue
|
||||
dlx = await channel.declare_exchange(
|
||||
DLX_NAME,
|
||||
type=ExchangeType.DIRECT,
|
||||
durable=True,
|
||||
)
|
||||
dlq = await channel.declare_queue(
|
||||
DLQ_NAME,
|
||||
durable=True,
|
||||
)
|
||||
await dlq.bind(dlx, routing_key=DL_ROUTING_KEY)
|
||||
|
||||
# 2. Основной Exchange и Queue с dead-lettering
|
||||
exchange = await channel.declare_exchange(
|
||||
EXCHANGE_NAME,
|
||||
type=ExchangeType.DIRECT,
|
||||
durable=True,
|
||||
)
|
||||
queue = await channel.declare_queue(
|
||||
QUEUE_NAME,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-dead-letter-exchange": DLX_NAME,
|
||||
"x-dead-letter-routing-key": DL_ROUTING_KEY,
|
||||
},
|
||||
)
|
||||
await queue.bind(exchange, routing_key=ROUTING_KEY)
|
||||
return exchange, queue
|
||||
|
||||
|
||||
class BrokerPublisher:
|
||||
"""Отказоустойчивый издатель сообщений в RabbitMQ с поддержкой Publisher Confirms."""
|
||||
|
||||
def __init__(self, broker_url: str = BROKER_URL) -> None:
|
||||
self.broker_url = broker_url
|
||||
self._connection: aio_pika.abc.AbstractRobustConnection | None = None
|
||||
self._channel: aio_pika.abc.AbstractChannel | None = None
|
||||
self._exchange: aio_pika.abc.AbstractExchange | None = None
|
||||
|
||||
async def get_exchange(self) -> aio_pika.abc.AbstractExchange:
|
||||
if self._exchange is None or self._channel is None or self._channel.is_closed:
|
||||
if self._connection is None or self._connection.is_closed:
|
||||
self._connection = await aio_pika.connect_robust(self.broker_url)
|
||||
self._channel = await self._connection.channel(publisher_confirms=True)
|
||||
self._exchange, _ = await setup_broker_topology(self._channel)
|
||||
return self._exchange
|
||||
|
||||
async def publish_job(self, job_dict: dict[str, Any]) -> bool:
|
||||
try:
|
||||
exchange = await self.get_exchange()
|
||||
payload = json.dumps(job_dict, ensure_ascii=False).encode("utf-8")
|
||||
message = aio_pika.Message(
|
||||
body=payload,
|
||||
delivery_mode=DeliveryMode.PERSISTENT,
|
||||
content_type="application/json",
|
||||
message_id=str(job_dict.get("job_id", "")),
|
||||
)
|
||||
await exchange.publish(
|
||||
message,
|
||||
routing_key=ROUTING_KEY,
|
||||
mandatory=True,
|
||||
)
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.error("Failed to publish job to broker: %s", exc)
|
||||
self._exchange = None
|
||||
self._channel = None
|
||||
return False
|
||||
|
||||
async def close(self) -> None:
|
||||
try:
|
||||
if self._channel and not self._channel.is_closed:
|
||||
await self._channel.close()
|
||||
if self._connection and not self._connection.is_closed:
|
||||
await self._connection.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._exchange = None
|
||||
self._channel = None
|
||||
self._connection = None
|
||||
|
||||
|
||||
publisher = BrokerPublisher()
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app.broker import publisher
|
||||
from app.config import DATABASE_URL
|
||||
from app.schemas import now_utc_iso
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
||||
logger = logging.getLogger("messenger.cli")
|
||||
|
||||
|
||||
async def replay_attachment(attachment_id_str: str) -> None:
|
||||
"""Безопасный операторский replay задачи из failed в queued."""
|
||||
try:
|
||||
att_id = uuid.UUID(attachment_id_str)
|
||||
except ValueError:
|
||||
logger.error("Invalid UUID: %s", attachment_id_str)
|
||||
sys.exit(1)
|
||||
|
||||
pool = await asyncpg.create_pool(dsn=DATABASE_URL)
|
||||
assert pool is not None
|
||||
|
||||
async with pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT id, status, chat_id, filename FROM attachments WHERE id = $1",
|
||||
att_id,
|
||||
)
|
||||
if not row:
|
||||
logger.error("Attachment %s not found in DB", att_id)
|
||||
await pool.close()
|
||||
sys.exit(1)
|
||||
|
||||
if row["status"] == "ready":
|
||||
logger.warning(
|
||||
"Attachment %s is already 'ready'. Replay will not re-execute successful job.",
|
||||
att_id,
|
||||
)
|
||||
await pool.close()
|
||||
return
|
||||
|
||||
# Переводим в queued и создаем новое задание
|
||||
new_job_id = uuid.uuid4()
|
||||
now_iso = now_utc_iso()
|
||||
job_payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(new_job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(att_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": now_iso,
|
||||
}
|
||||
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
error_code = NULL,
|
||||
processing_started_at = NULL,
|
||||
processing_worker_id = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
""",
|
||||
att_id,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO outbox_jobs (
|
||||
job_id, attachment_id, event_type, payload, status, attempt, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, 'attachment.process.v1', $3::jsonb, 'pending', 1, NOW(), NOW())
|
||||
""",
|
||||
new_job_id,
|
||||
att_id,
|
||||
json.dumps(job_payload),
|
||||
)
|
||||
|
||||
# Публикуем напрямую в брокер
|
||||
published = await publisher.publish_job(job_payload)
|
||||
if published:
|
||||
await conn.execute(
|
||||
"UPDATE outbox_jobs SET status = 'published' WHERE job_id = $1",
|
||||
new_job_id,
|
||||
)
|
||||
logger.info("Attachment %s successfully replayed with new job %s", att_id, new_job_id)
|
||||
else:
|
||||
logger.warning(
|
||||
"Attachment %s queued in outbox_jobs, will be dispatched by outbox relay",
|
||||
att_id,
|
||||
)
|
||||
|
||||
await publisher.close()
|
||||
await pool.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Operator CLI for messenger")
|
||||
subparsers = parser.add_subparsers(dest="command")
|
||||
|
||||
replay_parser = subparsers.add_parser("replay", help="Replay a failed attachment")
|
||||
replay_parser.add_argument("attachment_id", help="UUID of the attachment to replay")
|
||||
|
||||
args = parser.parse_args()
|
||||
if args.command == "replay":
|
||||
asyncio.run(replay_attachment(args.attachment_id))
|
||||
else:
|
||||
parser.print_help()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -42,3 +42,12 @@ S3_ACCESS_KEY_ID: str = _get_val("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE", "m
|
||||
S3_SECRET_ACCESS_KEY: str = _get_val("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE", "minioadmin")
|
||||
MAX_UPLOAD_BYTES: int = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS: int = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||
|
||||
BROKER_URL: str = _get_val(
|
||||
"BROKER_URL",
|
||||
"BROKER_URL_FILE",
|
||||
"amqp://messenger:messenger_broker_pass@broker:5672/",
|
||||
)
|
||||
WORKER_CONCURRENCY: int = int(os.getenv("WORKER_CONCURRENCY", "4"))
|
||||
WORKER_LEASE_SECONDS: int = int(os.getenv("WORKER_LEASE_SECONDS", "60"))
|
||||
MAX_JOB_RETRIES: int = int(os.getenv("MAX_JOB_RETRIES", "5"))
|
||||
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import math
|
||||
from typing import TypedDict
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
MAX_IMAGE_PIXELS = 40_000_000
|
||||
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
|
||||
|
||||
|
||||
class GeneratedVariant(TypedDict):
|
||||
name: str
|
||||
content_type: str
|
||||
data: bytes
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
def _calculate_contained_dimensions(orig_w: int, orig_h: int, max_w: int, max_h: int) -> tuple[int, int]:
|
||||
"""Вычисляет размеры, вписанные в max_w x max_h с сохранением пропорций,
|
||||
без увеличения маленьких исходников, с округлением вниз (floor) и минимумом 1px."""
|
||||
if orig_w <= max_w and orig_h <= max_h:
|
||||
return orig_w, orig_h
|
||||
scale = min(max_w / orig_w, max_h / orig_h)
|
||||
new_w = max(1, math.floor(orig_w * scale))
|
||||
new_h = max(1, math.floor(orig_h * scale))
|
||||
return new_w, new_h
|
||||
|
||||
|
||||
def _flatten_to_rgb(img: Image.Image) -> Image.Image:
|
||||
"""Накладывает альфа-канал на белый фон для форматов без поддержки прозрачности (JPEG)."""
|
||||
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
||||
rgba = img.convert("RGBA")
|
||||
background = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||
background.paste(rgba, mask=rgba.split()[3])
|
||||
return background
|
||||
if img.mode != "RGB":
|
||||
return img.convert("RGB")
|
||||
return img
|
||||
|
||||
|
||||
def generate_thumbnail(img: Image.Image) -> tuple[bytes, int, int]:
|
||||
"""Генерирует thumbnail: вписан в 256x256 без апскейла, JPEG, alpha на белый фон.
|
||||
|
||||
Размеры рассчитываются строго с округлением вниз (floor) и минимумом 1px.
|
||||
Возвращает (jpeg_bytes, width, height).
|
||||
"""
|
||||
target_w, target_h = _calculate_contained_dimensions(img.width, img.height, 256, 256)
|
||||
if (img.width, img.height) != (target_w, target_h):
|
||||
thumb = img.resize((target_w, target_h), Image.Resampling.LANCZOS)
|
||||
else:
|
||||
thumb = img.copy()
|
||||
rgb = _flatten_to_rgb(thumb)
|
||||
|
||||
buf = io.BytesIO()
|
||||
rgb.save(buf, format="JPEG", quality=85, optimize=True)
|
||||
data = buf.getvalue()
|
||||
return data, rgb.width, rgb.height
|
||||
|
||||
|
||||
def generate_crop(img: Image.Image) -> tuple[bytes, int, int]:
|
||||
"""Генерирует crop: центрированный квадрат 128x128 (с апскейлом для меньших), JPEG.
|
||||
|
||||
Возвращает (jpeg_bytes, width, height).
|
||||
"""
|
||||
cropped = ImageOps.fit(img, (128, 128), method=Image.Resampling.LANCZOS)
|
||||
rgb = _flatten_to_rgb(cropped)
|
||||
|
||||
buf = io.BytesIO()
|
||||
rgb.save(buf, format="JPEG", quality=85, optimize=True)
|
||||
data = buf.getvalue()
|
||||
return data, rgb.width, rgb.height
|
||||
|
||||
|
||||
def generate_optimized(img: Image.Image) -> tuple[bytes, int, int]:
|
||||
"""Генерирует optimized: WebP, вписан в 1280x1280 без апскейла, удаление EXIF.
|
||||
|
||||
Размеры рассчитываются строго с округлением вниз (floor) и минимумом 1px.
|
||||
Возвращает (webp_bytes, width, height).
|
||||
"""
|
||||
target_w, target_h = _calculate_contained_dimensions(img.width, img.height, 1280, 1280)
|
||||
if (img.width, img.height) != (target_w, target_h):
|
||||
opt = img.resize((target_w, target_h), Image.Resampling.LANCZOS)
|
||||
else:
|
||||
opt = img.copy()
|
||||
|
||||
if opt.mode not in ("RGB", "RGBA"):
|
||||
opt = opt.convert("RGBA" if "transparency" in opt.info else "RGB")
|
||||
|
||||
buf = io.BytesIO()
|
||||
opt.save(buf, format="WEBP", quality=80, method=4)
|
||||
data = buf.getvalue()
|
||||
return data, opt.width, opt.height
|
||||
|
||||
|
||||
def process_image_variants(raw_bytes: bytes) -> list[GeneratedVariant]:
|
||||
"""Безопасно декодирует сырые байты оригинала и генерирует thumbnail, crop, optimized.
|
||||
|
||||
Применяет EXIF orientation к базовому изображению.
|
||||
"""
|
||||
with Image.open(io.BytesIO(raw_bytes)) as img:
|
||||
w, h = img.size
|
||||
if w * h > MAX_IMAGE_PIXELS:
|
||||
raise ValueError("decompression bomb: image exceeds pixel limit")
|
||||
img.load()
|
||||
transposed = ImageOps.exif_transpose(img) or img
|
||||
|
||||
thumb_bytes, thumb_w, thumb_h = generate_thumbnail(transposed)
|
||||
crop_bytes, crop_w, crop_h = generate_crop(transposed)
|
||||
opt_bytes, opt_w, opt_h = generate_optimized(transposed)
|
||||
|
||||
def make_entry(name: str, ctype: str, data: bytes, w: int, h: int) -> GeneratedVariant:
|
||||
return {
|
||||
"name": name,
|
||||
"content_type": ctype,
|
||||
"data": data,
|
||||
"size_bytes": len(data),
|
||||
"width": w,
|
||||
"height": h,
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
}
|
||||
|
||||
return [
|
||||
make_entry("thumbnail", "image/jpeg", thumb_bytes, thumb_w, thumb_h),
|
||||
make_entry("crop", "image/jpeg", crop_bytes, crop_w, crop_h),
|
||||
make_entry("optimized", "image/webp", opt_bytes, opt_w, opt_h),
|
||||
]
|
||||
+7
-1
@@ -15,6 +15,8 @@ from app.routes.chats import router as chats_router
|
||||
from app.routes.health import router as health_router
|
||||
from app.routes.messages import router as messages_router
|
||||
from app.routes.users import router as users_router
|
||||
from app.broker import publisher
|
||||
from app.outbox import outbox_relay
|
||||
from app.storage import storage
|
||||
|
||||
logger = logging.getLogger("app.lifecycle")
|
||||
@@ -26,14 +28,18 @@ async def lifespan(app: FastAPI):
|
||||
"Starting messenger server on %s:%d (env: %s)", APP_HOST, APP_PORT, LOG_LEVEL
|
||||
)
|
||||
await storage.connect()
|
||||
if storage.pg_pool:
|
||||
await outbox_relay.start(storage.pg_pool)
|
||||
yield
|
||||
logger.info("Graceful shutdown: closing connections...")
|
||||
await outbox_relay.stop()
|
||||
await publisher.close()
|
||||
await storage.disconnect()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="highload-messenger",
|
||||
version="1.4.0",
|
||||
version="1.5.0",
|
||||
docs_url="/docs",
|
||||
redoc_url=None,
|
||||
lifespan=lifespan,
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app.broker import publisher
|
||||
|
||||
logger = logging.getLogger("messenger.outbox")
|
||||
|
||||
|
||||
class OutboxRelay:
|
||||
"""Фоновый диспетчер Transactional Outbox.
|
||||
|
||||
Вычитывает сохранённые задачи из PostgreSQL и надёжно публикует их в RabbitMQ.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._notify_event = asyncio.Event()
|
||||
self._running = False
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
|
||||
def notify(self) -> None:
|
||||
"""Сигнализирует о появлении новой записи для немедленной отправки без ожидания тика."""
|
||||
self._notify_event.set()
|
||||
|
||||
async def start(self, pool: asyncpg.Pool) -> None:
|
||||
if self._running:
|
||||
return
|
||||
self._running = True
|
||||
self._task = asyncio.create_task(self._loop(pool))
|
||||
logger.info("OutboxRelay started")
|
||||
|
||||
async def stop(self) -> None:
|
||||
self._running = False
|
||||
self._notify_event.set()
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self._task = None
|
||||
logger.info("OutboxRelay stopped")
|
||||
|
||||
async def process_pending(self, pool: asyncpg.Pool, limit: int = 50) -> int:
|
||||
"""Выбирает и публикует порцию pending-задач с FOR UPDATE SKIP LOCKED."""
|
||||
dispatched_count = 0
|
||||
async with pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT job_id, payload
|
||||
FROM outbox_jobs
|
||||
WHERE status = 'pending'
|
||||
ORDER BY created_at ASC
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""",
|
||||
limit,
|
||||
)
|
||||
if not rows:
|
||||
return 0
|
||||
|
||||
for row in rows:
|
||||
job_id = row["job_id"]
|
||||
payload_raw = row["payload"]
|
||||
payload_dict = json.loads(payload_raw) if isinstance(payload_raw, str) else dict(payload_raw)
|
||||
|
||||
success = await publisher.publish_job(payload_dict)
|
||||
if success:
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE outbox_jobs
|
||||
SET status = 'published', updated_at = NOW()
|
||||
WHERE job_id = $1
|
||||
""",
|
||||
job_id,
|
||||
)
|
||||
dispatched_count += 1
|
||||
else:
|
||||
logger.warning("Broker reject for job %s, will retry", job_id)
|
||||
break
|
||||
return dispatched_count
|
||||
|
||||
async def _loop(self, pool: asyncpg.Pool) -> None:
|
||||
while self._running:
|
||||
try:
|
||||
dispatched = await self.process_pending(pool)
|
||||
# Если были отправлены задачи, проверяем сразу следующую порцию
|
||||
if dispatched > 0:
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as exc:
|
||||
logger.error("Error in OutboxRelay loop: %s", exc)
|
||||
|
||||
# Ждём уведомления о новой задаче или таймаута 1.0 с
|
||||
try:
|
||||
await asyncio.wait_for(self._notify_event.wait(), timeout=1.0)
|
||||
self._notify_event.clear()
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
|
||||
outbox_relay = OutboxRelay()
|
||||
@@ -21,7 +21,7 @@ def validate_uuid(value: str, field_name: str = "id") -> str:
|
||||
@router.post(
|
||||
"/api/v1/chats/{chat_id}/attachments",
|
||||
response_model=AttachmentResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
status_code=status.HTTP_202_ACCEPTED,
|
||||
)
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
@@ -66,7 +66,7 @@ async def get_attachment_metadata(
|
||||
)
|
||||
async def download_attachment_content(
|
||||
attachment_id: str,
|
||||
variant: str | None = Query(default=None),
|
||||
variant: str = Query(default="original"),
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> Response:
|
||||
"""Скачивание бинарного содержимого вложения."""
|
||||
|
||||
+21
-7
@@ -5,6 +5,8 @@ import re
|
||||
from enum import Enum
|
||||
from uuid import UUID
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
@@ -137,12 +139,12 @@ class ChatPageResponse(BaseModel):
|
||||
class VariantResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
name: Literal["thumbnail", "crop", "optimized"]
|
||||
content_type: Literal["image/jpeg", "image/png", "image/webp"]
|
||||
size_bytes: int = Field(ge=1)
|
||||
width: int = Field(ge=1)
|
||||
height: int = Field(ge=1)
|
||||
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
|
||||
|
||||
class AttachmentResponse(BaseModel):
|
||||
@@ -155,13 +157,25 @@ class AttachmentResponse(BaseModel):
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str = "ready"
|
||||
status: Literal["queued", "processing", "ready", "failed"] = "queued"
|
||||
variants: list[VariantResponse] = Field(default_factory=list)
|
||||
error_code: str | None = None
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class AttachmentJobMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
schema_version: Literal[1] = 1
|
||||
job_id: str
|
||||
type: Literal["attachment.process.v1"] = "attachment.process.v1"
|
||||
attachment_id: str
|
||||
pipeline_version: int = 1
|
||||
attempt: int = 1
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateMessageRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
|
||||
+90
-38
@@ -37,6 +37,7 @@ from app.errors import (
|
||||
UnauthorizedError,
|
||||
UnsupportedMediaTypeError,
|
||||
)
|
||||
from app.outbox import outbox_relay
|
||||
from app.schemas import (
|
||||
AttachmentResponse,
|
||||
ChatResponse,
|
||||
@@ -89,6 +90,10 @@ class PostgresStorage:
|
||||
self.redis_client: redis.Redis | None = None
|
||||
self.s3_client: Any = None
|
||||
|
||||
@property
|
||||
def pool(self) -> asyncpg.Pool | None:
|
||||
return self.pg_pool
|
||||
|
||||
@asynccontextmanager
|
||||
async def acquire_conn(self, timeout: float = 2.0):
|
||||
if self.pg_pool is None:
|
||||
@@ -505,8 +510,8 @@ class PostgresStorage:
|
||||
for r in rows:
|
||||
if r["chat_id"] != cid:
|
||||
raise NotFoundError("Вложение принадлежит другому чату")
|
||||
if r["status"] != "ready":
|
||||
raise ConflictError("Вложение еще не готово или повреждено")
|
||||
if r["status"] == "failed":
|
||||
raise ConflictError("Нельзя прикреплять вложение со статусом failed")
|
||||
|
||||
# 1. Проверяем, обрабатывался ли уже этот idempotency_key
|
||||
existing = await conn.fetchrow(
|
||||
@@ -787,53 +792,81 @@ class PostgresStorage:
|
||||
|
||||
# 7. Генерация идентификаторов
|
||||
att_id = uuid.uuid4()
|
||||
s3_key = f"chats/{chat_id}/{att_id}/{filename}"
|
||||
job_id = uuid.uuid4()
|
||||
staging_key = f"staging/{att_id}/{filename}"
|
||||
sha256_hash = hashlib.sha256(data).hexdigest()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
now_iso = _format_dt(now)
|
||||
|
||||
# 8. Загрузка файла в S3
|
||||
# 8. Загрузка файла в устойчивый staging в S3
|
||||
def _put_to_s3():
|
||||
self.s3_client.put_object(
|
||||
Bucket=S3_BUCKET,
|
||||
Key=s3_key,
|
||||
Key=staging_key,
|
||||
Body=data,
|
||||
ContentType=ct_clean,
|
||||
)
|
||||
|
||||
await asyncio.to_thread(_put_to_s3)
|
||||
|
||||
# 9. Сохранение метаданных в PostgreSQL (с компенсацией удаления из S3 при ошибке)
|
||||
# 9. Атомарное сохранение в PostgreSQL: attachments + outbox_jobs
|
||||
job_payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(att_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": now_iso,
|
||||
}
|
||||
|
||||
try:
|
||||
async with self.acquire_conn() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, s3_key, status, error_code,
|
||||
created_at, updated_at
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, s3_key, status, error_code, variants,
|
||||
created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'queued', NULL, '[]'::jsonb, $9, $9)
|
||||
""",
|
||||
att_id,
|
||||
cid,
|
||||
c_caller,
|
||||
filename,
|
||||
ct_clean,
|
||||
size_bytes,
|
||||
sha256_hash,
|
||||
staging_key,
|
||||
now,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO outbox_jobs (
|
||||
job_id, attachment_id, event_type, payload, status, attempt, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, 'attachment.process.v1', $3::jsonb, 'pending', 1, $4, $4)
|
||||
""",
|
||||
job_id,
|
||||
att_id,
|
||||
json.dumps(job_payload),
|
||||
now,
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'ready', NULL, $9, $9)
|
||||
""",
|
||||
att_id,
|
||||
cid,
|
||||
c_caller,
|
||||
filename,
|
||||
ct_clean,
|
||||
size_bytes,
|
||||
sha256_hash,
|
||||
s3_key,
|
||||
now,
|
||||
)
|
||||
except Exception as db_err:
|
||||
logger.error("Ошибка записи метаданных в БД, компенсация S3: %s", db_err)
|
||||
logger.error("Ошибка записи метаданных/outbox в БД, компенсация staging S3: %s", db_err)
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
self.s3_client.delete_object, Bucket=S3_BUCKET, Key=s3_key
|
||||
self.s3_client.delete_object, Bucket=S3_BUCKET, Key=staging_key
|
||||
)
|
||||
except Exception as del_err:
|
||||
logger.error("Ошибка удаления S3 объекта при компенсации: %s", del_err)
|
||||
logger.error("Ошибка удаления staging S3 объекта при компенсации: %s", del_err)
|
||||
raise
|
||||
|
||||
# 10. Уведомляем outbox relay для немедленной публикации
|
||||
outbox_relay.notify()
|
||||
|
||||
return AttachmentResponse(
|
||||
id=str(att_id),
|
||||
chat_id=str(cid),
|
||||
@@ -842,11 +875,11 @@ class PostgresStorage:
|
||||
content_type=ct_clean,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256_hash,
|
||||
status="ready",
|
||||
status="queued",
|
||||
variants=[],
|
||||
error_code=None,
|
||||
created_at=_format_dt(now),
|
||||
updated_at=_format_dt(now),
|
||||
created_at=now_iso,
|
||||
updated_at=now_iso,
|
||||
)
|
||||
|
||||
async def get_attachment(
|
||||
@@ -862,7 +895,8 @@ class PostgresStorage:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.variants,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
WHERE a.id = $1
|
||||
""",
|
||||
@@ -879,6 +913,11 @@ class PostgresStorage:
|
||||
if not is_member:
|
||||
raise NotFoundError("Вложение не найдено")
|
||||
|
||||
raw_variants = row["variants"]
|
||||
if isinstance(raw_variants, str):
|
||||
raw_variants = json.loads(raw_variants)
|
||||
variants_list = [VariantResponse(**v) for v in (raw_variants or [])]
|
||||
|
||||
return AttachmentResponse(
|
||||
id=str(row["id"]),
|
||||
chat_id=str(row["chat_id"]),
|
||||
@@ -888,7 +927,7 @@ class PostgresStorage:
|
||||
size_bytes=row["size_bytes"],
|
||||
sha256=row["sha256"],
|
||||
status=row["status"],
|
||||
variants=[],
|
||||
variants=variants_list,
|
||||
error_code=row["error_code"],
|
||||
created_at=_format_dt(row["created_at"]),
|
||||
updated_at=_format_dt(row["updated_at"]),
|
||||
@@ -903,13 +942,14 @@ class PostgresStorage:
|
||||
except ValueError:
|
||||
raise NotFoundError("Вложение не найдено")
|
||||
|
||||
if variant not in (None, "", "original"):
|
||||
raise NotFoundError("Вариант не найден")
|
||||
variant_clean = (variant or "original").strip().lower()
|
||||
if variant_clean not in ("original", "thumbnail", "crop", "optimized"):
|
||||
raise InvalidRequestError("Неизвестный вариант изображения")
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT a.chat_id, a.content_type, a.s3_key, a.status
|
||||
SELECT a.chat_id, a.content_type, a.s3_key, a.status, a.variants
|
||||
FROM attachments a
|
||||
WHERE a.id = $1
|
||||
""",
|
||||
@@ -926,11 +966,23 @@ class PostgresStorage:
|
||||
if not is_member:
|
||||
raise NotFoundError("Вложение не найдено")
|
||||
|
||||
# По контракту: для queued/processing/failed возвращается 409 Conflict
|
||||
if row["status"] != "ready":
|
||||
raise ConflictError("Вложение повреждено или еще не готово")
|
||||
raise ConflictError("Вложение еще не готово или завершилось с ошибкой")
|
||||
|
||||
s3_key = row["s3_key"]
|
||||
content_type = row["content_type"]
|
||||
if variant_clean == "original":
|
||||
s3_key = row["s3_key"]
|
||||
content_type = row["content_type"]
|
||||
else:
|
||||
raw_variants = row["variants"]
|
||||
if isinstance(raw_variants, str):
|
||||
raw_variants = json.loads(raw_variants)
|
||||
variants_list = raw_variants or []
|
||||
matched = next((v for v in variants_list if v.get("name") == variant_clean), None)
|
||||
if not matched:
|
||||
raise NotFoundError("Запрошенный вариант не найден")
|
||||
s3_key = f"chats/{row['chat_id']}/{aid}/{variant_clean}"
|
||||
content_type = matched["content_type"]
|
||||
|
||||
def _get_from_s3():
|
||||
resp = self.s3_client.get_object(Bucket=S3_BUCKET, Key=s3_key)
|
||||
|
||||
+436
@@ -0,0 +1,436 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
import signal
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import aio_pika
|
||||
import asyncpg
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from PIL import UnidentifiedImageError
|
||||
|
||||
from app.broker import (
|
||||
DL_ROUTING_KEY,
|
||||
DLX_NAME,
|
||||
EXCHANGE_NAME,
|
||||
QUEUE_NAME,
|
||||
ROUTING_KEY,
|
||||
setup_broker_topology,
|
||||
)
|
||||
from app.config import (
|
||||
BROKER_URL,
|
||||
DATABASE_URL,
|
||||
MAX_JOB_RETRIES,
|
||||
S3_ACCESS_KEY_ID,
|
||||
S3_BUCKET,
|
||||
S3_ENDPOINT,
|
||||
S3_REGION,
|
||||
S3_SECRET_ACCESS_KEY,
|
||||
WORKER_CONCURRENCY,
|
||||
WORKER_LEASE_SECONDS,
|
||||
)
|
||||
from app.imaging import process_image_variants
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("messenger.worker")
|
||||
|
||||
|
||||
class AttachmentWorker:
|
||||
def __init__(self) -> None:
|
||||
self.worker_id = f"worker-{uuid.uuid4().hex[:8]}"
|
||||
self.pool: asyncpg.Pool | None = None
|
||||
self.s3_client: Any = None
|
||||
self._connection: aio_pika.abc.AbstractRobustConnection | None = None
|
||||
self._channel: aio_pika.abc.AbstractChannel | None = None
|
||||
self._running = False
|
||||
self._watchdog_task: asyncio.Task[None] | None = None
|
||||
|
||||
async def init_resources(self) -> None:
|
||||
logger.info("Initializing worker resources (%s)...", self.worker_id)
|
||||
# 1. PostgreSQL pool
|
||||
self.pool = await asyncpg.create_pool(
|
||||
dsn=DATABASE_URL,
|
||||
min_size=2,
|
||||
max_size=WORKER_CONCURRENCY + 2,
|
||||
command_timeout=10.0,
|
||||
)
|
||||
|
||||
# 2. S3 client
|
||||
s3_cfg = Config(
|
||||
signature_version="s3v4",
|
||||
connect_timeout=3,
|
||||
read_timeout=10,
|
||||
retries={"max_attempts": 3, "mode": "standard"},
|
||||
)
|
||||
self.s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=S3_ENDPOINT,
|
||||
region_name=S3_REGION,
|
||||
aws_access_key_id=S3_ACCESS_KEY_ID,
|
||||
aws_secret_access_key=S3_SECRET_ACCESS_KEY,
|
||||
config=s3_cfg,
|
||||
)
|
||||
|
||||
async def _lease_watchdog(self) -> None:
|
||||
while self._running:
|
||||
try:
|
||||
await asyncio.sleep(15.0)
|
||||
if not self.pool:
|
||||
continue
|
||||
async with self.pool.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
processing_started_at = NULL,
|
||||
processing_worker_id = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE status = 'processing'
|
||||
AND processing_started_at < NOW() - ($1 || ' seconds')::interval
|
||||
RETURNING id
|
||||
""",
|
||||
str(WORKER_LEASE_SECONDS),
|
||||
)
|
||||
for r in rows:
|
||||
logger.warning(
|
||||
"Lease expired for attachment %s, reverting to queued and republishing", r["id"]
|
||||
)
|
||||
if self._channel and not self._channel.is_closed:
|
||||
try:
|
||||
exchange = await self._channel.get_exchange(EXCHANGE_NAME)
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(uuid.uuid4()),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(r["id"]),
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
}
|
||||
msg = aio_pika.Message(
|
||||
body=json.dumps(payload).encode("utf-8"),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
content_type="application/json",
|
||||
)
|
||||
await exchange.publish(msg, routing_key=ROUTING_KEY)
|
||||
except Exception as pub_err:
|
||||
logger.error("Failed republish on lease expiration for %s: %s", r["id"], pub_err)
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as exc:
|
||||
logger.error("Error in lease watchdog: %s", exc)
|
||||
|
||||
async def process_job_message(self, message: aio_pika.abc.AbstractIncomingMessage) -> None:
|
||||
"""Обрабатывает одно задание на генерацию вариантов изображения."""
|
||||
async with message.process(requeue=False):
|
||||
try:
|
||||
payload = json.loads(message.body.decode("utf-8"))
|
||||
except Exception as parse_err:
|
||||
logger.error("Failed to parse job JSON: %s. Acking.", parse_err)
|
||||
return
|
||||
|
||||
att_id_str = payload.get("attachment_id")
|
||||
if not att_id_str:
|
||||
logger.error("Job payload missing attachment_id: %s", payload)
|
||||
return
|
||||
|
||||
try:
|
||||
att_id = uuid.UUID(att_id_str)
|
||||
except ValueError:
|
||||
logger.error("Invalid attachment_id UUID: %s", att_id_str)
|
||||
return
|
||||
|
||||
attempt = int(payload.get("attempt", 1))
|
||||
|
||||
if not self.pool:
|
||||
logger.error("DB pool not initialized")
|
||||
return
|
||||
|
||||
async with self.pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'processing',
|
||||
processing_started_at = NOW(),
|
||||
processing_worker_id = $1,
|
||||
updated_at = NOW()
|
||||
WHERE id = $2 AND status IN ('queued', 'failed')
|
||||
RETURNING id, chat_id, filename, content_type, size_bytes, sha256, s3_key, status
|
||||
""",
|
||||
self.worker_id,
|
||||
att_id,
|
||||
)
|
||||
if not row:
|
||||
current_status = await conn.fetchval(
|
||||
"SELECT status FROM attachments WHERE id = $1", att_id
|
||||
)
|
||||
logger.info(
|
||||
"Attachment %s is in state '%s', skipping processing (idempotent no-op).",
|
||||
att_id,
|
||||
current_status,
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
async with asyncio.timeout(30.0):
|
||||
staging_key = row["s3_key"]
|
||||
try:
|
||||
s3_resp = await asyncio.to_thread(
|
||||
self.s3_client.get_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=staging_key,
|
||||
)
|
||||
raw_bytes = s3_resp["Body"].read()
|
||||
except Exception as s3_err:
|
||||
logger.error("Failed to read staging S3 key %s: %s", staging_key, s3_err)
|
||||
await self._handle_retryable_error(payload, attempt, str(s3_err))
|
||||
return
|
||||
|
||||
# 3. Генерируем варианты через Pillow
|
||||
try:
|
||||
variants = await asyncio.to_thread(process_image_variants, raw_bytes)
|
||||
except (UnidentifiedImageError, ValueError) as img_err:
|
||||
logger.warning(
|
||||
"Permanent image processing error for %s: %s", att_id, img_err
|
||||
)
|
||||
await self._fail_attachment(att_id, "invalid_image")
|
||||
await self._send_to_dlq(payload, f"permanent_image_error: {img_err}")
|
||||
return
|
||||
except Exception as unk_err:
|
||||
logger.error(
|
||||
"Unexpected processing error for %s: %s", att_id, unk_err
|
||||
)
|
||||
await self._handle_retryable_error(payload, attempt, str(unk_err))
|
||||
return
|
||||
|
||||
# 4. Сохраняем оригинал и варианты в постоянные S3-ключи
|
||||
chat_id = str(row["chat_id"])
|
||||
final_original_key = f"chats/{chat_id}/{att_id}/original"
|
||||
|
||||
try:
|
||||
# Оригинал
|
||||
await asyncio.to_thread(
|
||||
self.s3_client.put_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=final_original_key,
|
||||
Body=raw_bytes,
|
||||
ContentType=row["content_type"],
|
||||
)
|
||||
# Варианты
|
||||
for var in variants:
|
||||
var_key = f"chats/{chat_id}/{att_id}/{var['name']}"
|
||||
await asyncio.to_thread(
|
||||
self.s3_client.put_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=var_key,
|
||||
Body=var["data"],
|
||||
ContentType=var["content_type"],
|
||||
)
|
||||
except Exception as upload_err:
|
||||
logger.error("Failed uploading variants to S3 for %s: %s", att_id, upload_err)
|
||||
await self._handle_retryable_error(payload, attempt, str(upload_err))
|
||||
return
|
||||
|
||||
# 5. Атомарно обновляем PostgreSQL в 'ready'
|
||||
variants_metadata = [
|
||||
{
|
||||
"name": v["name"],
|
||||
"content_type": v["content_type"],
|
||||
"size_bytes": v["size_bytes"],
|
||||
"width": v["width"],
|
||||
"height": v["height"],
|
||||
"sha256": v["sha256"],
|
||||
}
|
||||
for v in variants
|
||||
]
|
||||
|
||||
async with self.pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'ready',
|
||||
s3_key = $1,
|
||||
variants = $2::jsonb,
|
||||
error_code = NULL,
|
||||
processing_started_at = NULL,
|
||||
processing_worker_id = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $3
|
||||
""",
|
||||
final_original_key,
|
||||
json.dumps(variants_metadata),
|
||||
att_id,
|
||||
)
|
||||
|
||||
# 6. Очистка staging-файла в MinIO
|
||||
if staging_key != final_original_key:
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
self.s3_client.delete_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=staging_key,
|
||||
)
|
||||
except Exception as del_err:
|
||||
logger.warning("Failed to delete staging key %s: %s", staging_key, del_err)
|
||||
|
||||
logger.info("Attachment %s successfully processed into ready with 3 variants.", att_id)
|
||||
except TimeoutError:
|
||||
logger.error("Job processing timed out (>30s) for %s. Aborting hung worker task.", att_id)
|
||||
await self._handle_retryable_error(payload, attempt, "job_deadline_exceeded_30s")
|
||||
return
|
||||
|
||||
async def _fail_attachment(self, att_id: uuid.UUID, error_code: str) -> None:
|
||||
"""Переводит вложение в статус failed с безопасным машинным кодом."""
|
||||
if not self.pool:
|
||||
return
|
||||
async with self.pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'failed',
|
||||
error_code = $1,
|
||||
processing_started_at = NULL,
|
||||
processing_worker_id = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $2
|
||||
""",
|
||||
error_code,
|
||||
att_id,
|
||||
)
|
||||
|
||||
async def _send_to_dlq(self, payload: dict[str, Any], reason: str) -> None:
|
||||
try:
|
||||
if self._channel and not self._channel.is_closed:
|
||||
dlx = await self._channel.get_exchange(DLX_NAME)
|
||||
dlq_payload = dict(payload, error="permanent_or_exhausted", last_reason=reason)
|
||||
dlq_msg = aio_pika.Message(
|
||||
body=json.dumps(dlq_payload).encode("utf-8"),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
content_type="application/json",
|
||||
)
|
||||
await dlx.publish(dlq_msg, routing_key=DL_ROUTING_KEY)
|
||||
except Exception as dlx_err:
|
||||
logger.error("Failed publishing to DLQ: %s", dlx_err)
|
||||
|
||||
async def _handle_retryable_error(self, payload: dict[str, Any], attempt: int, reason: str) -> None:
|
||||
att_id_str = payload.get("attachment_id")
|
||||
att_id = uuid.UUID(att_id_str)
|
||||
|
||||
if attempt < MAX_JOB_RETRIES:
|
||||
next_attempt = attempt + 1
|
||||
delay = 0.5 * (2 ** attempt) + random.uniform(0.1, 0.5)
|
||||
logger.warning(
|
||||
"Retryable error for %s (attempt %d/%d). Retrying in %.2fs: %s",
|
||||
att_id, attempt, MAX_JOB_RETRIES, delay, reason
|
||||
)
|
||||
if self.pool:
|
||||
async with self.pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
processing_started_at = NULL,
|
||||
processing_worker_id = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
""",
|
||||
att_id,
|
||||
)
|
||||
|
||||
async def _delayed_republish() -> None:
|
||||
await asyncio.sleep(delay)
|
||||
try:
|
||||
if self._channel and not self._channel.is_closed:
|
||||
exchange = await self._channel.get_exchange(EXCHANGE_NAME)
|
||||
new_payload = dict(payload, attempt=next_attempt)
|
||||
msg = aio_pika.Message(
|
||||
body=json.dumps(new_payload).encode("utf-8"),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
content_type="application/json",
|
||||
)
|
||||
await exchange.publish(msg, routing_key=ROUTING_KEY)
|
||||
except Exception as pub_err:
|
||||
logger.error("Failed delayed republish for %s: %s", att_id, pub_err)
|
||||
|
||||
asyncio.create_task(_delayed_republish())
|
||||
else:
|
||||
logger.error(
|
||||
"Max retries (%d) exhausted for attachment %s. Moving to DLQ.",
|
||||
MAX_JOB_RETRIES, att_id
|
||||
)
|
||||
await self._fail_attachment(att_id, "retry_exhausted")
|
||||
await self._send_to_dlq(payload, f"retry_exhausted: {reason}")
|
||||
|
||||
async def start(self) -> None:
|
||||
self._running = True
|
||||
await self.init_resources()
|
||||
|
||||
# Подключение к RabbitMQ с автоматическим reconnect
|
||||
logger.info("Connecting to RabbitMQ at %s...", BROKER_URL.split("@")[-1])
|
||||
while self._running:
|
||||
try:
|
||||
self._connection = await aio_pika.connect_robust(BROKER_URL)
|
||||
break
|
||||
except Exception as conn_err:
|
||||
logger.warning("RabbitMQ not ready yet (%s). Retrying in 2s...", conn_err)
|
||||
await asyncio.sleep(2.0)
|
||||
|
||||
assert self._connection is not None
|
||||
self._channel = await self._connection.channel()
|
||||
await self._channel.set_qos(prefetch_count=WORKER_CONCURRENCY)
|
||||
|
||||
_, queue = await setup_broker_topology(self._channel)
|
||||
|
||||
self._watchdog_task = asyncio.create_task(self._lease_watchdog())
|
||||
logger.info(
|
||||
"Worker %s started consuming queue '%s' (prefetch=%d)...",
|
||||
self.worker_id, QUEUE_NAME, WORKER_CONCURRENCY
|
||||
)
|
||||
|
||||
await queue.consume(self.process_job_message)
|
||||
|
||||
async def stop(self) -> None:
|
||||
logger.info("Stopping worker %s...", self.worker_id)
|
||||
self._running = False
|
||||
if self._watchdog_task:
|
||||
self._watchdog_task.cancel()
|
||||
if self._channel and not self._channel.is_closed:
|
||||
await self._channel.close()
|
||||
if self._connection and not self._connection.is_closed:
|
||||
await self._connection.close()
|
||||
if self.pool:
|
||||
await self.pool.close()
|
||||
logger.info("Worker stopped.")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
worker = AttachmentWorker()
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
stop_event = asyncio.Event()
|
||||
|
||||
def _sig_handler() -> None:
|
||||
logger.info("Received termination signal")
|
||||
stop_event.set()
|
||||
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
try:
|
||||
loop.add_signal_handler(sig, _sig_handler)
|
||||
except NotImplementedError:
|
||||
pass
|
||||
|
||||
await worker.start()
|
||||
await stop_event.wait()
|
||||
await worker.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user