diff --git a/Dockerfile b/Dockerfile index 4f150402..3c897133 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,32 +1,21 @@ FROM python:3.11-slim -ENV PYTHONDONTWRITEBYTECODE=1 \ - PYTHONUNBUFFERED=1 \ - PIP_NO_CACHE_DIR=1 \ - PIP_DISABLE_PIP_VERSION_CHECK=1 - -RUN apt-get update \ - && apt-get install -y --no-install-recommends curl ca-certificates \ - && rm -rf /var/lib/apt/lists/* - WORKDIR /app +# libpq-dev для psycopg, gcc для сборки некоторых python-пакетов, +# libjpeg-dev и zlib1g-dev нужны для работы Pillow (обработка картинок) +RUN apt-get update && apt-get install -y --no-install-recommends \ + libpq-dev gcc libjpeg-dev zlib1g-dev \ + && rm -rf /var/lib/apt/lists/* + COPY requirements.txt . -RUN pip install -r requirements.txt +RUN pip install --no-cache-dir -r requirements.txt -# Копируем код приложения, миграции и скрипты -COPY src/app ./app -COPY src/migrations ./migrations -COPY scripts ./scripts +# Копируем код API и Воркера +COPY src/ ./src/ +COPY worker/ ./worker/ -# не root -RUN useradd --create-home --shell /bin/bash appuser \ - && chown -R appuser:appuser /app -USER appuser +ENV PYTHONPATH=/app -EXPOSE 8080 - -HEALTHCHECK --interval=5s --timeout=2s --start-period=10s --retries=6 \ - CMD curl -fsS http://127.0.0.1:8080/health/live || exit 1 - -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080", "--proxy-headers", "--forwarded-allow-ips", "*"] \ No newline at end of file +# По умолчанию запускаем API (воркер переопределит эту команду в compose) +CMD ["uvicorn", "src.app.main:app", "--host", "0.0.0.0", "--port", "8080"] \ No newline at end of file diff --git a/Dockerfile.worker b/Dockerfile.worker new file mode 100644 index 00000000..1e5291b9 --- /dev/null +++ b/Dockerfile.worker @@ -0,0 +1,15 @@ +FROM python:3.11-slim + +WORKDIR /app + +RUN apt-get update && apt-get install -y --no-install-recommends \ + libpq-dev gcc && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY src/ ./src/ +COPY worker/ ./worker/ + +ENV PYTHONPATH=/app +CMD ["python", "-m", "worker.main"] \ No newline at end of file diff --git a/compose.yaml b/compose.yaml index a43fc3ea..1de6c84f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,14 +1,13 @@ -name: mtusi-messenger - -x-api-base: &api-base +x-api-common: &api-common build: . environment: - DATABASE_URL_FILE=/run/secrets/database_url - - SESSION_TTL_SECONDS=3600 - S3_ENDPOINT=http://minio:9000 - - S3_ACCESS_KEY=api-user - - S3_SECRET_KEY=api-secret-key-12345 + - S3_ACCESS_KEY=minioadmin + - S3_SECRET_KEY=minioadmin - S3_BUCKET=messenger-attachments + - BROKER_URL=amqp://guest:guest@broker:5672/ + - APP_ENV=lab5 secrets: - database_url depends_on: @@ -16,93 +15,14 @@ x-api-base: &api-base condition: service_healthy minio: condition: service_healthy - migrate: + broker: + condition: service_healthy + minio-init: condition: service_completed_successfully services: - postgres: - image: postgres:16-alpine - environment: - POSTGRES_USER: messenger - POSTGRES_PASSWORD: messenger - POSTGRES_DB: messenger - healthcheck: - test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] - interval: 5s - timeout: 3s - retries: 5 - volumes: - - pgdata:/var/lib/postgresql/data - - minio: - image: pgsty/silo:latest - command: server /data --console-address ":9001" - environment: - MINIO_ROOT_USER: minioadmin - MINIO_ROOT_PASSWORD: minioadmin - volumes: - - miniodata:/data - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"] - interval: 5s - timeout: 3s - retries: 5 - # Порт 9000 (API) и 9001 (Консоль) НЕ пробрасываем наружу, чтобы админка была закрыта. - # Контейнеры общаются по внутренней сети Docker. - - minio-init: - image: pgsty/silo:latest - depends_on: - minio: - condition: service_healthy - volumes: - - ./infra/minio-policy.json:/tmp/minio-policy.json:ro - entrypoint: > - /bin/sh -c " - mc alias set myminio http://minio:9000 minioadmin minioadmin; - mc mb myminio/messenger-attachments --ignore-existing; - mc anonymous set none myminio/messenger-attachments; - mc admin user add myminio api-user api-secret-key-12345 || true; - mc admin policy create myminio api-policy /tmp/minio-policy.json || true; - mc admin policy attach myminio api-policy --user api-user || true; - exit 0; - " - - migrate: - build: . - command: ["python", "scripts/migrate.py"] - environment: - - DATABASE_URL_FILE=/run/secrets/database_url - secrets: - - database_url - depends_on: - postgres: - condition: service_healthy - - api1: - <<: *api-base - environment: - - INSTANCE_ID=api-1 - - DATABASE_URL_FILE=/run/secrets/database_url - - SESSION_TTL_SECONDS=3600 - - S3_ENDPOINT=http://minio:9000 - - S3_ACCESS_KEY=api-user - - S3_SECRET_KEY=api-secret-key-12345 - - S3_BUCKET=messenger-attachments - - api2: - <<: *api-base - environment: - - INSTANCE_ID=api-2 - - DATABASE_URL_FILE=/run/secrets/database_url - - SESSION_TTL_SECONDS=3600 - - S3_ENDPOINT=http://minio:9000 - - S3_ACCESS_KEY=api-user - - S3_SECRET_KEY=api-secret-key-12345 - - S3_BUCKET=messenger-attachments - - load_balancer: - image: nginx:1.27-alpine + lb: + image: nginx:1.25-alpine ports: - "8080:8080" volumes: @@ -111,10 +31,110 @@ services: - api1 - api2 + api1: + <<: *api-common + expose: + - "8080" + + api2: + <<: *api-common + expose: + - "8080" + + worker: + build: . + command: python -m worker.main + environment: + - DATABASE_URL_FILE=/run/secrets/database_url + - S3_ENDPOINT=http://minio:9000 + - S3_ACCESS_KEY=minioadmin + - S3_SECRET_KEY=minioadmin + - S3_BUCKET=messenger-attachments + - BROKER_URL=amqp://guest:guest@broker:5672/ + secrets: + - database_url + depends_on: + postgres: + condition: service_healthy + minio: + condition: service_healthy + broker: + condition: service_healthy + minio-init: + condition: service_completed_successfully + + migrate: + build: . + command: python scripts/migrate.py + environment: + - DATABASE_URL_FILE=/run/secrets/database_url + secrets: + - database_url + depends_on: + postgres: + condition: service_healthy + + postgres: + image: postgres:16-alpine + environment: + - POSTGRES_USER=messenger + - POSTGRES_PASSWORD=messenger_password + - POSTGRES_DB=messenger + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 5s + retries: 5 + + minio: + image: quay.io/minio/minio:RELEASE.2024-02-24T06-42-55Z + command: server /data --console-address ":9001" + environment: + - MINIO_ROOT_USER=minioadmin + - MINIO_ROOT_PASSWORD=minioadmin + volumes: + - s3data:/data + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"] + interval: 5s + timeout: 5s + retries: 5 + + minio-init: + image: quay.io/minio/mc:latest + depends_on: + minio: + condition: service_healthy + volumes: + - ./infra/minio-policy.json:/minio-policy.json + entrypoint: > + /bin/sh -c " + /usr/bin/mc alias set myminio http://minio:9000 minioadmin minioadmin; + /usr/bin/mc mb myminio/messenger-attachments --ignore-existing; + /usr/bin/mc anonymous set-json /minio-policy.json myminio/messenger-attachments; + exit 0; + " + + broker: + image: rabbitmq:3.13-alpine + environment: + - RABBITMQ_DEFAULT_USER=guest + - RABBITMQ_DEFAULT_PASS=guest + volumes: + - brokerdata:/var/lib/rabbitmq + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 5s + timeout: 5s + retries: 5 + secrets: database_url: file: ./secrets/database_url volumes: pgdata: - miniodata: \ No newline at end of file + s3data: + brokerdata: \ No newline at end of file diff --git a/infra/minio-policy.json b/infra/minio-policy.json new file mode 100644 index 00000000..e757ee44 --- /dev/null +++ b/infra/minio-policy.json @@ -0,0 +1,17 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:ListBucket" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments", + "arn:aws:s3:::messenger-attachments/*" + ] + } + ] +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..bf7f6e7e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +fastapi>=0.110.0 +uvicorn[standard]>=0.29.0 +psycopg[binary,pool]>=3.1.18 +pydantic-settings>=2.2.1 +argon2-cffi>=23.1.0 +boto3>=1.34.0 +python-multipart>=0.0.9 +Pillow>=10.2.0 +aio-pika>=9.4.0 \ No newline at end of file diff --git a/src/app/config.py b/src/app/config.py index 6d3f0dd4..45e446ae 100644 --- a/src/app/config.py +++ b/src/app/config.py @@ -31,13 +31,17 @@ class Settings(BaseSettings): database_url: str = "" database_url_file: str = "/run/secrets/database_url" - # S3 / MinIO (для 4-й лабы) + # S3 / MinIO s3_endpoint: str = "http://minio:9000" s3_access_key: str = "minioadmin" s3_secret_key: str = "minioadmin" s3_bucket: str = "messenger-attachments" s3_region: str = "us-east-1" + # Брокер (RabbitMQ) + broker_url: str = "amqp://guest:guest@broker:5672/" + broker_queue: str = "attachment_processing" + @property def db_dsn(self) -> str: from_file = _read_secret(self.database_url_file) diff --git a/src/app/routes/attachments.py b/src/app/routes/attachments.py index 458996b4..9564a9b6 100644 --- a/src/app/routes/attachments.py +++ b/src/app/routes/attachments.py @@ -2,11 +2,14 @@ import hashlib import io import tempfile import uuid +import json +import aio_pika from fastapi import APIRouter, Depends, Request, Query from fastapi.responses import StreamingResponse from psycopg.rows import dict_row +from ..config import get_settings from ..db import transaction, connection from ..errors import ApiError from ..s3 import upload_fileobj, download_fileobj, delete_file @@ -15,11 +18,27 @@ from ..serializers import iso_z from .sessions import require_actor router = APIRouter(prefix="/api/v1") - MAX_SIZE = 10 * 1024 * 1024 +async def _publish_task(attachment_id: str, object_key: str): + """Отправляет задачу в RabbitMQ.""" + settings = get_settings() + try: + 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) + message = aio_pika.Message( + body=json.dumps({"attachment_id": attachment_id, "object_key": object_key}).encode(), + delivery_mode=aio_pika.DeliveryMode.PERSISTENT + ) + await channel.default_exchange.publish(message, routing_key=settings.broker_queue) + except Exception as e: + print(f"Broker error: {e}") + # Если брокер упал, мы можем либо откатить загрузку, либо оставить статус queued + # Для лабы: логируем, воркер потом не найдет задачу, но health/ready покажет ошибку -@router.post("/chats/{chat_id}/attachments", status_code=201) +@router.post("/chats/{chat_id}/attachments", status_code=202) async def upload_attachment( chat_id: str, request: Request, @@ -34,7 +53,6 @@ async def upload_attachment( if "/" in filename or "\\" in filename or "\0" in filename: raise ApiError(400, "invalid_request", "Опасное имя файла") - # Проверяем доступ к чату with connection() as conn: with conn.cursor() as cur: cur.execute( @@ -48,34 +66,28 @@ async def upload_attachment( size = 0 first_chunk = b"" - # Читаем потоково во временный файл (чтобы не забивать RAM) with tempfile.SpooledTemporaryFile(max_size=MAX_SIZE, mode="w+b") as spooled: async for chunk in request.stream(): size += len(chunk) if size > MAX_SIZE: raise ApiError(413, "payload_too_large", "Файл слишком большой") if not first_chunk: - first_chunk = chunk[:16] # для детекта MIME + first_chunk = chunk[:16] sha256.update(chunk) spooled.write(chunk) if size == 0: raise ApiError(400, "invalid_request", "Пустой файл") - # Полная проверка картинки через Pillow + # Только быстрая проверка magic bytes, глубокий анализ оставляем воркеру try: - spooled.seek(0) - content = spooled.read() content_type, _, _ = check_image(first_chunk, ["image/png", "image/jpeg"]) - from PIL import Image - Image.open(io.BytesIO(content)).verify() - except Exception: - raise ApiError(415, "unsupported_media_type", "Неподдерживаемый или битый формат") + except ValueError: + raise ApiError(415, "unsupported_media_type", "Неподдерживаемый формат") sha256_hex = sha256.hexdigest() object_key = f"chats/{chat_id}/{uuid.uuid4().hex}" - # Загружаем в S3 try: spooled.seek(0) upload_fileobj(spooled, object_key, content_type) @@ -83,21 +95,19 @@ async def upload_attachment( print(f"S3 error: {e}") raise ApiError(503, "unavailable", "S3 недоступен") - # Сохраняем в БД (с компенсацией) try: with transaction() as conn: with conn.cursor(row_factory=dict_row) as cur: cur.execute( """ - INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) - VALUES (%s, %s, %s, %s, %s, %s, %s) - RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, created_at + INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status) + VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued') + RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at """, (chat_id, actor["user_id"], filename, content_type, size, sha256_hex, object_key), ) att = cur.fetchone() except Exception as e: - # КОМПЕНСАЦИЯ: удаляем из S3, если БД упала print(f"DB failed, compensating S3: {e}") try: delete_file(object_key) @@ -105,6 +115,9 @@ async def upload_attachment( print(f"Failed to compensate S3: {s3_e}") raise ApiError(500, "internal_error", "Ошибка сохранения") + # Публикуем задачу + await _publish_task(str(att["id"]), object_key) + return { "id": str(att["id"]), "chat_id": str(att["chat_id"]), @@ -113,14 +126,13 @@ async def upload_attachment( "content_type": att["content_type"], "size_bytes": att["size_bytes"], "sha256": att["sha256"], - "status": "ready", + "status": att["status"], "variants": [], "error_code": None, "created_at": iso_z(att["created_at"]), - "updated_at": iso_z(att["created_at"]), + "updated_at": iso_z(att["updated_at"]), } - @router.get("/attachments/{attachment_id}") def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)): try: @@ -140,6 +152,12 @@ def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)): (actor["user_id"], attachment_id), ) att = cur.fetchone() + + if att: + cur.execute("SELECT * FROM attachment_variants WHERE attachment_id = %s", (attachment_id,)) + variants = cur.fetchall() + else: + variants = [] if att is None: raise ApiError(404, "not_found", "Вложение не найдено") @@ -152,16 +170,28 @@ def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)): "content_type": att["content_type"], "size_bytes": att["size_bytes"], "sha256": att["sha256"], - "status": "ready", - "variants": [], - "error_code": None, + "status": att["status"], + "variants": [ + { + "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 + ], + "error_code": att["error_code"], "created_at": iso_z(att["created_at"]), - "updated_at": iso_z(att["created_at"]), + "updated_at": iso_z(att["updated_at"]), } - @router.get("/attachments/{attachment_id}/content") -def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)): +def download_attachment( + attachment_id: str, + variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"), + actor: dict = Depends(require_actor) +): try: uuid.UUID(attachment_id) except ValueError: @@ -171,7 +201,7 @@ def download_attachment(attachment_id: str, actor: dict = Depends(require_actor) with conn.cursor(row_factory=dict_row) as cur: cur.execute( """ - SELECT a.object_key, a.content_type, a.filename + SELECT a.object_key, a.content_type, a.filename, a.status FROM attachments a JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s WHERE a.id = %s @@ -180,11 +210,28 @@ def download_attachment(attachment_id: str, actor: dict = Depends(require_actor) ) att = cur.fetchone() - if att is None: - raise ApiError(404, "not_found", "Вложение не найдено") + if att is None: + raise ApiError(404, "not_found", "Вложение не найдено") + + if variant == "original": + if att["status"] == "failed": + raise ApiError(409, "conflict", "Обработка вложения завершилась ошибкой") + obj_key = att["object_key"] + content_type = att["content_type"] + else: + cur.execute( + "SELECT object_key, content_type FROM attachment_variants WHERE attachment_id = %s AND name = %s", + (attachment_id, variant) + ) + var = cur.fetchone() + if not var: + # Если вариант еще не готов, возвращаем 404 или 409 + raise ApiError(404, "not_found", "Вариант еще не готов или недоступен") + obj_key = var["object_key"] + content_type = var["content_type"] try: - body = download_fileobj(att["object_key"]) + body = download_fileobj(obj_key) except Exception: raise ApiError(503, "unavailable", "S3 недоступен") @@ -193,6 +240,6 @@ def download_attachment(attachment_id: str, actor: dict = Depends(require_actor) return StreamingResponse( iter_body(), - media_type=att["content_type"], + media_type=content_type, headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'}, ) \ No newline at end of file diff --git a/src/app/routes/health.py b/src/app/routes/health.py index 572ed6d0..b0567a08 100644 --- a/src/app/routes/health.py +++ b/src/app/routes/health.py @@ -1,25 +1,41 @@ from fastapi import APIRouter, Request from fastapi.responses import JSONResponse +import socket +from urllib.parse import urlparse +from ..config import get_settings from ..db import connection from ..errors import error_response +from ..s3 import get_s3_client router = APIRouter() - @router.get("/health/live") def live(): return {"status": "ok"} - @router.get("/health/ready") def ready(request: Request): try: + with connection() as conn: with conn.cursor() as cur: cur.execute("SELECT 1") cur.fetchone() - except Exception: + + + get_s3_client().head_bucket(Bucket=get_settings().s3_bucket) + + # 3. Broker (простая проверка TCP-порта) + settings = get_settings() + parsed = urlparse(settings.broker_url) + host = parsed.hostname or "broker" + port = parsed.port or 5672 + with socket.create_connection((host, port), timeout=2): + pass + + except Exception as e: + print(f"Readiness check failed: {e}") return error_response( request, 503, "unavailable", "Зависимость недоступна" ) diff --git a/src/migrations/002_attachments.sql b/src/migrations/002_attachments.sql index 5055da0a..64951308 100644 --- a/src/migrations/002_attachments.sql +++ b/src/migrations/002_attachments.sql @@ -1,4 +1,4 @@ --- 002_attachments.sql +-- src/migrations/002_attachments.sql CREATE TABLE IF NOT EXISTS attachments ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, @@ -8,7 +8,10 @@ CREATE TABLE IF NOT EXISTS attachments ( size_bytes bigint NOT NULL, sha256 text NOT NULL, object_key text NOT NULL, - created_at timestamptz NOT NULL DEFAULT now() + status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','processing','ready','failed')), + error_code text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments(chat_id); diff --git a/src/migrations/003_attachment_variants.sql b/src/migrations/003_attachment_variants.sql new file mode 100644 index 00000000..f08e2e25 --- /dev/null +++ b/src/migrations/003_attachment_variants.sql @@ -0,0 +1,13 @@ +-- src/migrations/003_attachment_variants.sql +CREATE TABLE IF NOT EXISTS attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + name text NOT NULL CHECK (name IN ('thumbnail','crop','optimized')), + content_type text NOT NULL CHECK (content_type IN ('image/jpeg','image/png','image/webp')), + size_bytes bigint NOT NULL CHECK (size_bytes > 0), + width int NOT NULL CHECK (width > 0), + height int NOT NULL CHECK (height > 0), + sha256 text NOT NULL, + object_key text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (attachment_id, name) +); \ No newline at end of file diff --git a/worker/__init__.py b/worker/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/worker/main.py b/worker/main.py new file mode 100644 index 00000000..21d41073 --- /dev/null +++ b/worker/main.py @@ -0,0 +1,123 @@ +import asyncio +import io +import json +import logging +from datetime import datetime, timezone + +import aio_pika +from PIL import Image +import psycopg +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 get_s3_client, download_fileobj, upload_fileobj + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger("worker") + +def generate_variants(img: Image.Image): + variants = {} + + # 1. Thumbnail (макс 256x256, сохраняем пропорции) + thumb = img.copy() + thumb.thumbnail((256, 256)) + variants["thumbnail"] = thumb + + # 2. Crop (квадрат 512x512 по центру) + crop = img.copy() + 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((512, 512), Image.Resampling.LANCZOS) + variants["crop"] = crop + + # 3. Optimized (просто оригинал в JPEG с качеством 85) + opt = img.convert("RGB") + buf = io.BytesIO() + opt.save(buf, format="JPEG", quality=85) + variants["optimized"] = Image.open(buf) + + return variants + +async def process_message(message: aio_pika.IncomingMessage): + async with message.process(): + 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,)) + + # 2. Качаем из S3 + body = download_fileobj(obj_key) + img = Image.open(body) + 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(): + buf = io.BytesIO() + ct = "image/jpeg" + if name == "thumbnail": + var_img.save(buf, format="PNG") + ct = "image/png" + else: + var_img.save(buf, format="JPEG", quality=85) + + var_bytes = buf.getvalue() + sha256 = __import__("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,)) + logger.info(f"Successfully processed {att_id}") + + except Exception as e: + logger.error(f"Error processing {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 # Пробрасываем ошибку, чтобы RabbitMQ не удалил сообщение (at-least-once) + +async def main(): + init_pool() + settings = get_settings() + + connection = await aio_pika.connect_robust(settings.broker_url) + 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()) \ No newline at end of file