forked from mtusi2026/mtusi2026lab5
Compare commits
5
Commits
1637e30dba
...
0393ef16dd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0393ef16dd | ||
|
|
aa9ca145b7 | ||
|
|
429eaef5e2 | ||
|
|
8030c8821a | ||
|
|
7d39c2dab6 |
@@ -34,3 +34,7 @@ MAX_IMAGE_PIXELS=40000000
|
||||
CLEANUP_INTERVAL_SECONDS=300
|
||||
# Grace period: объекты моложе N секунд не удаляются (защита in-flight uploads).
|
||||
ORPHAN_GRACE_SECONDS=3600
|
||||
|
||||
RABBITMQ_USER=messenger
|
||||
RABBITMQ_PASSWORD=messenger-rabbit-change-me
|
||||
RABBITMQ_URL=amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F
|
||||
+83
-7
@@ -142,7 +142,7 @@ services:
|
||||
|
||||
migrate:
|
||||
build: .
|
||||
image: mtuci-messenger:lab4
|
||||
image: mtuci-messenger:lab5
|
||||
command: ["python", "-m", "app.storage.db"]
|
||||
# Явный whitelist переменных: без MINIO_ROOT_USER/PASSWORD.
|
||||
environment:
|
||||
@@ -165,9 +165,83 @@ services:
|
||||
cpus: "0.1"
|
||||
memory: 64M
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:3.13.7-management-alpine
|
||||
container_name: mtuci-rabbitmq
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-messenger}
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-messenger-rabbit-change-me}
|
||||
volumes:
|
||||
- rabbitmq-data:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
start_period: 20s
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 128M
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
command: ["python", "-m", "app.worker"]
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://minio:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_APP_KEY_ID: ${S3_APP_KEY_ID}
|
||||
S3_APP_SECRET_KEY: ${S3_APP_SECRET_KEY}
|
||||
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
minio-init:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
|
||||
outbox:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
command: ["python", "-m", "app.outbox_worker"]
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.3"
|
||||
memory: 128M
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtuci-messenger:lab4
|
||||
image: mtuci-messenger:lab5
|
||||
# Явный whitelist переменных: приложение не получает административные
|
||||
# credentials MinIO (MINIO_ROOT_USER/PASSWORD). Для S3 — только
|
||||
# прикладные S3_APP_KEY_ID/S3_APP_SECRET_KEY с ограниченной политикой.
|
||||
@@ -219,7 +293,7 @@ services:
|
||||
# Запускается как долгоживущий сервис, спит CLEANUP_INTERVAL_SECONDS.
|
||||
s3_cleanup:
|
||||
build: .
|
||||
image: mtuci-messenger:lab4
|
||||
image: mtuci-messenger:lab5
|
||||
command: ["python", "-m", "app.storage.s3_cleanup"]
|
||||
# Явный whitelist переменных: без административных кредов MinIO.
|
||||
environment:
|
||||
@@ -269,12 +343,14 @@ services:
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
name: mtuci2026lab4_postgres-data
|
||||
name: mtuci2026lab5_postgres-data
|
||||
redis-data:
|
||||
name: mtuci2026lab4_redis-data
|
||||
name: mtuci2026lab5_redis-data
|
||||
minio-data:
|
||||
name: mtuci2026lab4_minio-data
|
||||
name: mtuci2026lab5_minio-data
|
||||
rabbitmq-data:
|
||||
name: mtuci2026lab5_rabbitmq-data
|
||||
|
||||
networks:
|
||||
default:
|
||||
name: mtuci2026lab4_default
|
||||
name: mtuci2026lab5_default
|
||||
+2
-1
@@ -5,4 +5,5 @@ psycopg_pool==3.2.3
|
||||
redis==5.2.0
|
||||
openapi-spec-validator==0.7.2
|
||||
boto3==1.35.74
|
||||
Pillow==11.0.0
|
||||
Pillow==11.0.0
|
||||
pika==1.3.2
|
||||
+48
-32
@@ -1,4 +1,4 @@
|
||||
"""Вложения (lab4): синхронный binary upload PNG/JPEG, авторизованный download."""
|
||||
"""Вложения (lab5): upload → 202 queued, async worker, download вариантов."""
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
@@ -11,6 +11,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from ..models.schemas import Attachment, User
|
||||
from ..storage import s3
|
||||
@@ -22,6 +23,7 @@ router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
||||
|
||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
PIPELINE_VERSION = 1
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
@@ -52,11 +54,7 @@ def _detect_content_type(data: bytes) -> Optional[str]:
|
||||
|
||||
|
||||
def _validate_image(data: bytes) -> str:
|
||||
"""MIME по содержимому + лимит пикселей + полная проверка декодирования.
|
||||
|
||||
Полное декодирование (load) выполняется через Pillow, чтобы отвергнуть
|
||||
повреждённые/обрезанные файлы, которые open() принимает по заголовку.
|
||||
"""
|
||||
"""MIME по содержимому + лимит пикселей + полная проверка декодирования."""
|
||||
ctype = _detect_content_type(data)
|
||||
if ctype is None:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
@@ -67,14 +65,10 @@ def _validate_image(data: bytes) -> str:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
if width * height > MAX_IMAGE_PIXELS:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
# Полное декодирование всех данных: битый IDAT / обрезанный файл
|
||||
# поднимут OSError/ValueError и будут отвергнуты как 415.
|
||||
img.load()
|
||||
except HTTPException:
|
||||
raise
|
||||
except Image.DecompressionBombError:
|
||||
# Pillow защищается от «бомб» по собственному порогу: для нас
|
||||
# это превышение лимита пикселей → 413.
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
except Exception:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
@@ -83,9 +77,9 @@ def _validate_image(data: bytes) -> str:
|
||||
|
||||
@router.post(
|
||||
path="/chats/{chat_id}/attachments",
|
||||
summary="Принять один PNG/JPEG, до 10 MiB",
|
||||
summary="Принять один PNG/JPEG, до 10 MiB (lab5: 202 queued)",
|
||||
response_model=Attachment,
|
||||
status_code=201,
|
||||
status_code=202,
|
||||
)
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
@@ -96,7 +90,6 @@ async def upload_attachment(
|
||||
_require_member(chat_id, user.id)
|
||||
safe_name = _validate_filename(filename)
|
||||
|
||||
# Content-Length — быстрая отсечка; не доверяем полностью.
|
||||
cl = request.headers.get("content-length")
|
||||
if cl is not None:
|
||||
try:
|
||||
@@ -105,7 +98,6 @@ async def upload_attachment(
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
# Потоковое чтение с жёстким лимитом.
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
async for chunk in request.stream():
|
||||
@@ -119,16 +111,15 @@ async def upload_attachment(
|
||||
if not body:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
# Pillow — в threadpool, чтобы не блокировать event loop.
|
||||
content_type = await run_in_threadpool(_validate_image, body)
|
||||
sha256 = hashlib.sha256(body).hexdigest()
|
||||
|
||||
attachment_id = uuid4()
|
||||
object_key = s3.original_key(chat_id, attachment_id)
|
||||
staging_key = s3.staging_key(chat_id, attachment_id)
|
||||
|
||||
# 1) Сначала сохраняем в S3. Если следующий шаг упадёт — компенсируем.
|
||||
# 1) Durable staging в S3 (приватный prefix).
|
||||
try:
|
||||
await run_in_threadpool(s3.put_bytes, object_key, body, content_type)
|
||||
await run_in_threadpool(s3.put_bytes, staging_key, body, content_type)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
@@ -141,19 +132,31 @@ async def upload_attachment(
|
||||
content_type=content_type,
|
||||
size_bytes=len(body),
|
||||
sha256=sha256,
|
||||
status="ready",
|
||||
status="queued",
|
||||
variants=[],
|
||||
error_code=None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
# 2) INSERT в БД. При ЛЮБОМ исключении удаляем S3-объект (компенсация).
|
||||
job_id = uuid4()
|
||||
outbox_payload = {
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": PIPELINE_VERSION,
|
||||
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
# 2) INSERT attachment + outbox в ОДНОЙ транзакции.
|
||||
# При сбое — компенсация: удаляем staging.
|
||||
try:
|
||||
await run_in_threadpool(storage.create_attachment, att, object_key)
|
||||
await run_in_threadpool(
|
||||
storage.create_attachment_queued, att, staging_key, outbox_payload
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
await run_in_threadpool(s3.delete_object, object_key)
|
||||
await run_in_threadpool(s3.delete_object, staging_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
@@ -180,15 +183,16 @@ def get_attachment(
|
||||
|
||||
@router.get(
|
||||
path="/attachments/{attachment_id}/content",
|
||||
summary="Скачать байты через авторизованный API",
|
||||
summary="Скачать байты (original или variant) через авторизованный API",
|
||||
)
|
||||
def download_attachment(
|
||||
attachment_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
variant: str = Query("original"),
|
||||
):
|
||||
if variant != "original":
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
if variant not in ("original", "thumbnail", "crop", "optimized"):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
@@ -197,16 +201,28 @@ def download_attachment(
|
||||
if att.status != "ready":
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
try:
|
||||
data, ctype = s3.get_object(object_key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Объект отсутствует при готовых метаданных: 404.
|
||||
if exc.__class__.__name__ == "NoSuchKey":
|
||||
if variant == "original":
|
||||
key = object_key
|
||||
ctype_expected = att.content_type
|
||||
else:
|
||||
vs = [v for v in att.variants if v.name == variant]
|
||||
if not vs:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
v = vs[0]
|
||||
key = s3.variant_key(att.chat_id, att.id, variant)
|
||||
ctype_expected = v.content_type
|
||||
|
||||
try:
|
||||
data, ctype = s3.get_object(key)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code in ("404", "NoSuchKey", "NotFound"):
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=ctype,
|
||||
headers={"Content-Length": str(len(data))},
|
||||
media_type=ctype or ctype_expected,
|
||||
)
|
||||
+2
-2
@@ -44,8 +44,8 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab4",
|
||||
version="1.4.0",
|
||||
title="MTUCI Messenger — lab5",
|
||||
version="1.5.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Outbox worker lab5 level 4: publish неопубликованных job в RabbitMQ.
|
||||
|
||||
Закрывает разрыв COMMIT → publish: если API упал после COMMIT, outbox
|
||||
осталась в БД; этот процесс опубликует её после рестарта. Publisher
|
||||
confirm гарантирует приём брокером перед mark published.
|
||||
"""
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .storage.postgres import storage
|
||||
from .storage.rabbit import publish_job
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
log = logging.getLogger("outbox")
|
||||
|
||||
_stop = False
|
||||
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
global _stop
|
||||
log.info("event=sigterm_received signal=%s", signum)
|
||||
_stop = True
|
||||
|
||||
|
||||
def main() -> None:
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
init_pool()
|
||||
log.info("event=outbox_start")
|
||||
|
||||
while not _stop:
|
||||
try:
|
||||
rows = storage.list_unpublished_outbox(limit=50)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=outbox_select_failed type=%s msg=%s",
|
||||
type(exc).__name__, str(exc)[:300])
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
for outbox_id, payload in rows:
|
||||
if _stop:
|
||||
break
|
||||
try:
|
||||
publish_job(payload)
|
||||
storage.mark_outbox_published(outbox_id)
|
||||
log.info("event=outbox_published id=%s job_id=%s",
|
||||
outbox_id, payload.get("job_id"))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning(
|
||||
"event=outbox_publish_failed id=%s type=%s msg=%s",
|
||||
outbox_id, type(exc).__name__, str(exc)[:300],
|
||||
)
|
||||
# не выходим, попробуем в следующем цикле
|
||||
time.sleep(2)
|
||||
break
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
close_pool()
|
||||
log.info("event=outbox_stop")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception:
|
||||
log.error("event=outbox_fatal\n%s", traceback.format_exc())
|
||||
sys.exit(1)
|
||||
+28
-1
@@ -115,8 +115,9 @@ CREATE TABLE IF NOT EXISTS attachments (
|
||||
size_bytes BIGINT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL, -- ready (lab4), queued/processing/failed (lab5)
|
||||
status TEXT NOT NULL, -- queued/processing/ready/failed
|
||||
error_code TEXT,
|
||||
processing_until TIMESTAMPTZ, -- lease для worker (lab5)
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
@@ -132,6 +133,32 @@ CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_msg_att_message
|
||||
ON message_attachments (message_id, position);
|
||||
|
||||
-- lab5: варианты обработки (идемпотентность по (attachment_id, pipeline_version, variant))
|
||||
CREATE TABLE IF NOT EXISTS attachment_variants (
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
pipeline_version INT NOT NULL,
|
||||
variant TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
width INT NOT NULL,
|
||||
height INT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (attachment_id, pipeline_version, variant)
|
||||
);
|
||||
|
||||
-- lab5 level 4: transactional outbox (разрыв COMMIT → publish)
|
||||
CREATE TABLE IF NOT EXISTS outbox (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
job_id UUID NOT NULL UNIQUE,
|
||||
payload JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
published_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_outbox_unpublished
|
||||
ON outbox (id) WHERE published_at IS NULL;
|
||||
"""
|
||||
|
||||
|
||||
|
||||
+180
-74
@@ -1,8 +1,9 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import json as _json
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
@@ -70,13 +71,14 @@ def _row_to_message(row, attachment_ids: List[UUID]) -> Message:
|
||||
)
|
||||
|
||||
|
||||
def _row_to_attachment(row) -> Attachment:
|
||||
def _row_to_attachment(row, variants: Optional[list] = None) -> Attachment:
|
||||
# row: id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
# status, error_code, created_at, updated_at
|
||||
return Attachment(
|
||||
id=row[0], chat_id=row[1], owner_id=row[2],
|
||||
filename=row[3], content_type=row[4], size_bytes=row[5],
|
||||
sha256=row[6], status=row[7], variants=[], error_code=row[8],
|
||||
sha256=row[6], status=row[7], variants=variants or [],
|
||||
error_code=row[8],
|
||||
created_at=row[9], updated_at=row[10],
|
||||
)
|
||||
|
||||
@@ -91,8 +93,6 @@ class PostgresStorage:
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# SELECT-проверка + INSERT в одной транзакции; уникальный индекс
|
||||
# users.username отсекает гонку на уровне БД (UniqueViolation).
|
||||
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
||||
if cur.fetchone() is not None:
|
||||
raise ValueError("username_taken")
|
||||
@@ -108,8 +108,6 @@ class PostgresStorage:
|
||||
_hash_password(password), user.created_at),
|
||||
)
|
||||
except Exception as exc:
|
||||
# Параллельная регистрация того же username: уникальный индекс
|
||||
# выбросил UniqueViolation — превращаем в доменную ошибку.
|
||||
if exc.__class__.__name__ == "UniqueViolation":
|
||||
raise ValueError("username_taken")
|
||||
raise
|
||||
@@ -148,9 +146,7 @@ class PostgresStorage:
|
||||
return None
|
||||
return _row_to_user(row[:4])
|
||||
|
||||
# ---------- Сессии (Redis или PostgreSQL — см. storage/sessions.py) ----------
|
||||
# Тонкие делегаты: роутеры продолжают вызывать storage.create_session(...),
|
||||
# storage.get_session_user(...), storage.revoke_session(...) без изменений.
|
||||
# ---------- Сессии ----------
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
return _sess_create(user_id, ttl_seconds)
|
||||
|
||||
@@ -221,10 +217,7 @@ class PostgresStorage:
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def _load_message_attachments(
|
||||
self, cur, message_ids: List[UUID]
|
||||
) -> dict[UUID, List[UUID]]:
|
||||
"""Одним запросом достаём attachment_ids для набора сообщений."""
|
||||
def _load_message_attachments(self, cur, message_ids: List[UUID]) -> dict[UUID, List[UUID]]:
|
||||
if not message_ids:
|
||||
return {}
|
||||
cur.execute(
|
||||
@@ -238,17 +231,8 @@ class PostgresStorage:
|
||||
return result
|
||||
|
||||
def list_messages_page(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
after: Optional[tuple] = None,
|
||||
self, chat_id: UUID, limit: int, after: Optional[tuple] = None,
|
||||
) -> List[Message]:
|
||||
"""Keyset-пагинация в SQL
|
||||
|
||||
after = (created_at, id) последней записи предыдущей страницы или None.
|
||||
Запрос использует индекс idx_messages_chat_created (chat_id, created_at, id)
|
||||
и не делает полный scan всей истории на каждую страницу.
|
||||
"""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
if after is None:
|
||||
cur.execute(
|
||||
@@ -282,25 +266,8 @@ class PostgresStorage:
|
||||
key: str,
|
||||
body_hash: str,
|
||||
) -> tuple[str, Optional[Message], Optional[dict]]:
|
||||
"""Атомарная отправка сообщения с идемпотентностью.
|
||||
|
||||
Возвращает одно из:
|
||||
('created', message, None) — мы выиграли гонку и создали сообщение;
|
||||
('replay', None, info) — ключ уже занят; info = {body_hash,
|
||||
response_status, response_body}
|
||||
('retry', None, None) — конфликт при INSERT, но строки нет
|
||||
(крайне редко); вызывающий может
|
||||
повторить запрос.
|
||||
|
||||
ВСЁ делается в ОДНОЙ транзакции: либо строка idempotency_keys
|
||||
и строка messages фиксируются вместе, либо не фиксируется ничего.
|
||||
Это устраняет блокер, когда сообщение сохранено, а ключ остался
|
||||
с response_status=0 и повтор зависал.
|
||||
"""
|
||||
import json as _json
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# 1) Пытаемся занять ключ. ON CONFLICT DO NOTHING — атомарно.
|
||||
cur.execute(
|
||||
"INSERT INTO idempotency_keys"
|
||||
" (user_id, method, path, key, body_hash, response_status, response_body)"
|
||||
@@ -312,7 +279,6 @@ class PostgresStorage:
|
||||
won = cur.fetchone() is not None
|
||||
|
||||
if won:
|
||||
# 2) Мы выиграли: создаём сообщение в ТОЙ ЖЕ транзакции.
|
||||
message = Message(
|
||||
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
||||
text=text, created_at=now_utc(),
|
||||
@@ -332,7 +298,6 @@ class PostgresStorage:
|
||||
[(message.id, aid, idx)
|
||||
for idx, aid in enumerate(attachment_ids)],
|
||||
)
|
||||
# 3) Пишем финальный ответ в ту же строку ключа.
|
||||
body_json = _json.loads(message.model_dump_json())
|
||||
cur.execute(
|
||||
"UPDATE idempotency_keys"
|
||||
@@ -341,11 +306,9 @@ class PostgresStorage:
|
||||
(201, _json.dumps(body_json),
|
||||
user_id, method, path, key),
|
||||
)
|
||||
# Один commit — либо всё, либо ничего.
|
||||
conn.commit()
|
||||
return ("created", message, None)
|
||||
|
||||
# Ключ уже занят. Читаем строку в этой же транзакции.
|
||||
cur.execute(
|
||||
"SELECT body_hash, response_status, response_body"
|
||||
" FROM idempotency_keys"
|
||||
@@ -356,7 +319,6 @@ class PostgresStorage:
|
||||
conn.commit()
|
||||
|
||||
if row is None:
|
||||
# Только что был конфликт, а строки нет — редкий случай; повтор.
|
||||
return ("retry", None, None)
|
||||
return (
|
||||
"replay",
|
||||
@@ -369,11 +331,8 @@ class PostgresStorage:
|
||||
)
|
||||
|
||||
# ---------- Вложения ----------
|
||||
def create_attachment(
|
||||
self,
|
||||
attachment: Attachment,
|
||||
object_key: str,
|
||||
) -> Attachment:
|
||||
def create_attachment(self, attachment: Attachment, object_key: str) -> Attachment:
|
||||
"""lab4 fallback (синхронный ready). Не используется в lab5."""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments"
|
||||
@@ -391,27 +350,112 @@ class PostgresStorage:
|
||||
conn.commit()
|
||||
return attachment
|
||||
|
||||
def create_attachment_queued(
|
||||
self,
|
||||
attachment: Attachment,
|
||||
staging_key: str,
|
||||
outbox_payload: dict,
|
||||
) -> Attachment:
|
||||
"""lab5: attachment в queued + строка outbox в ОДНОЙ транзакции."""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments"
|
||||
" (id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, object_key, status, error_code, processing_until,"
|
||||
" created_at, updated_at)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(
|
||||
attachment.id, attachment.chat_id, attachment.owner_id,
|
||||
attachment.filename, attachment.content_type,
|
||||
attachment.size_bytes, attachment.sha256, staging_key,
|
||||
"queued", None, None,
|
||||
attachment.created_at, attachment.updated_at,
|
||||
),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||
(outbox_payload["job_id"], _json.dumps(outbox_payload)),
|
||||
)
|
||||
conn.commit()
|
||||
return attachment
|
||||
|
||||
def claim_processing(self, attachment_id: UUID, lease_seconds: int = 60) -> bool:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
now = now_utc()
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='processing',"
|
||||
" processing_until=%s, updated_at=%s"
|
||||
" WHERE id=%s AND status IN ('queued','processing')"
|
||||
" RETURNING id",
|
||||
(now + timedelta(seconds=lease_seconds), now, attachment_id),
|
||||
)
|
||||
won = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
return won
|
||||
|
||||
def recover_stuck_processing(self) -> int:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
now = now_utc()
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='queued', processing_until=NULL,"
|
||||
" updated_at=%s"
|
||||
" WHERE status='processing' AND processing_until IS NOT NULL"
|
||||
" AND processing_until < %s",
|
||||
(now, now),
|
||||
)
|
||||
count = cur.rowcount
|
||||
conn.commit()
|
||||
return count
|
||||
|
||||
def finalize_ready(
|
||||
self,
|
||||
attachment_id: UUID,
|
||||
pipeline_version: int,
|
||||
variants: list[dict],
|
||||
) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
original = next(v for v in variants if v["name"] == "original")
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='ready', error_code=NULL,"
|
||||
" object_key=%s, processing_until=NULL, updated_at=%s"
|
||||
" WHERE id=%s",
|
||||
(original["object_key"], now_utc(), attachment_id),
|
||||
)
|
||||
for v in variants:
|
||||
if v["name"] == "original":
|
||||
continue
|
||||
cur.execute(
|
||||
"INSERT INTO attachment_variants"
|
||||
" (attachment_id, pipeline_version, variant, object_key,"
|
||||
" content_type, size_bytes, width, height, sha256)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
|
||||
" ON CONFLICT (attachment_id, pipeline_version, variant)"
|
||||
" DO NOTHING",
|
||||
(
|
||||
attachment_id, pipeline_version, v["name"],
|
||||
v["object_key"], v["content_type"],
|
||||
v["size_bytes"], v["width"], v["height"], v["sha256"],
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def finalize_failed(self, attachment_id: UUID, error_code: str) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='failed', error_code=%s,"
|
||||
" processing_until=NULL, updated_at=%s WHERE id=%s",
|
||||
(error_code, now_utc(), attachment_id),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def get_attachment(self, attachment_id: UUID) -> Optional[Attachment]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at"
|
||||
" FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT object_key FROM attachments WHERE id = %s", (attachment_id,),
|
||||
)
|
||||
obj_row = cur.fetchone()
|
||||
att = _row_to_attachment(row)
|
||||
att_variants: List[Variant] = [] # lab4: вариантов нет
|
||||
att.variants = att_variants
|
||||
# object_key нужен вызывающему для чтения из S3; отдаём через
|
||||
# отдельный метод get_attachment_with_key.
|
||||
return att
|
||||
pair = self.get_attachment_with_key(attachment_id)
|
||||
return pair[0] if pair else None
|
||||
|
||||
def get_attachment_with_key(
|
||||
self, attachment_id: UUID
|
||||
@@ -426,13 +470,12 @@ class PostgresStorage:
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
att = _row_to_attachment(row[:11])
|
||||
att = _row_to_attachment(row[:11], self.get_attachment_variants(attachment_id))
|
||||
return att, row[11]
|
||||
|
||||
def list_attachments_by_ids(
|
||||
self, ids: List[UUID], chat_id: UUID
|
||||
) -> dict[UUID, tuple[Attachment, str]]:
|
||||
"""Достаём вложения этого чата. Возвращает {id: (Attachment, object_key)}."""
|
||||
if not ids:
|
||||
return {}
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
@@ -445,7 +488,6 @@ class PostgresStorage:
|
||||
result: dict[UUID, tuple[Attachment, str]] = {}
|
||||
for row in cur.fetchall():
|
||||
att = _row_to_attachment(row[:11])
|
||||
att.variants = []
|
||||
result[row[0]] = (att, row[11])
|
||||
return result
|
||||
|
||||
@@ -454,5 +496,69 @@ class PostgresStorage:
|
||||
cur.execute("DELETE FROM attachments WHERE id = %s", (attachment_id,))
|
||||
conn.commit()
|
||||
|
||||
def get_attachment_variants(self, attachment_id: UUID) -> list[dict]:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT variant, content_type, size_bytes, width, height, sha256"
|
||||
" FROM attachment_variants WHERE attachment_id=%s"
|
||||
" ORDER BY variant",
|
||||
(attachment_id,),
|
||||
)
|
||||
return [
|
||||
{
|
||||
"name": r[0], "content_type": r[1], "size_bytes": r[2],
|
||||
"width": r[3], "height": r[4], "sha256": r[5],
|
||||
}
|
||||
for r in cur.fetchall()
|
||||
]
|
||||
|
||||
def get_staging_key(self, attachment_id: UUID) -> Optional[str]:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT object_key FROM attachments WHERE id=%s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
# ---------- Outbox (lab5 level 4) ----------
|
||||
def list_unpublished_outbox(self, limit: int = 100) -> list[tuple[int, dict]]:
|
||||
"""Возвращает [(outbox_id, payload_dict), ...].
|
||||
|
||||
Всегда dict; если payload в БД пришёл строкой (например, из старой
|
||||
версии), распаковываем через json.loads.
|
||||
"""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, payload FROM outbox WHERE published_at IS NULL"
|
||||
" ORDER BY id LIMIT %s",
|
||||
(limit,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
result: list[tuple[int, dict]] = []
|
||||
for r in rows:
|
||||
raw = r[1]
|
||||
if isinstance(raw, dict):
|
||||
payload = raw
|
||||
else:
|
||||
payload = _json.loads(raw)
|
||||
if not isinstance(payload, dict):
|
||||
# защита от мусора — пропустить
|
||||
continue
|
||||
result.append((int(r[0]), payload))
|
||||
return result
|
||||
|
||||
def mark_outbox_published(self, outbox_id: int) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE outbox SET published_at=now() WHERE id=%s",
|
||||
(outbox_id,),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||
@@ -0,0 +1,156 @@
|
||||
"""RabbitMQ: topology, publisher with confirms, consumer с manual ack.
|
||||
|
||||
- Основная очередь: durable quorum queue.
|
||||
- Retry: TTL-очереди с dead-letter обратно в основную; x-retry-count.
|
||||
- DLQ: финальные ошибки и исчерпанные retry.
|
||||
- Publisher confirms: publish() ждёт подтверждения брокера.
|
||||
|
||||
ВАЖНО: setup_topology вызывается в worker при старте и в outbox
|
||||
однократно при первом publish. Не декларируем топологию на каждый
|
||||
publish — иначе гонка с параллельными декларациями.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from typing import Optional
|
||||
|
||||
import pika
|
||||
|
||||
log = logging.getLogger("rabbit")
|
||||
|
||||
EXCHANGE = "messenger.attachments"
|
||||
QUEUE = "attachment.process.v1"
|
||||
RETRY_EXCHANGE = "messenger.attachments.retry"
|
||||
DLX = "messenger.attachments.dlx"
|
||||
DLQ = "attachment.process.v1.dlq"
|
||||
|
||||
RETRY_DELAYS = [5, 15, 60]
|
||||
MAX_ATTEMPTS = len(RETRY_DELAYS) + 1
|
||||
|
||||
_topology_ready = False
|
||||
_topology_lock = threading.Lock()
|
||||
|
||||
|
||||
def _url() -> str:
|
||||
return os.environ.get("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/%2F")
|
||||
|
||||
|
||||
def connection_params() -> pika.ConnectionParameters:
|
||||
return pika.URLParameters(_url())
|
||||
|
||||
|
||||
def connect() -> pika.BlockingConnection:
|
||||
return pika.BlockingConnection(connection_params())
|
||||
|
||||
|
||||
def setup_topology(channel: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||
channel.exchange_declare(EXCHANGE, exchange_type="direct", durable=True)
|
||||
channel.exchange_declare(RETRY_EXCHANGE, exchange_type="direct", durable=True)
|
||||
channel.exchange_declare(DLX, exchange_type="direct", durable=True)
|
||||
|
||||
channel.queue_declare(DLQ, durable=True, arguments={"x-queue-type": "quorum"})
|
||||
channel.queue_bind(DLQ, DLX, routing_key=DLQ)
|
||||
|
||||
channel.queue_declare(
|
||||
QUEUE,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-queue-type": "quorum",
|
||||
"x-dead-letter-exchange": DLX,
|
||||
"x-dead-letter-routing-key": DLQ,
|
||||
},
|
||||
)
|
||||
channel.queue_bind(QUEUE, EXCHANGE, routing_key=QUEUE)
|
||||
|
||||
for delay in RETRY_DELAYS:
|
||||
qname = f"attachment.retry.{delay}s"
|
||||
channel.queue_declare(
|
||||
qname,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-message-ttl": delay * 1000,
|
||||
"x-dead-letter-exchange": EXCHANGE,
|
||||
"x-dead-letter-routing-key": QUEUE,
|
||||
},
|
||||
)
|
||||
channel.queue_bind(qname, RETRY_EXCHANGE, routing_key=qname)
|
||||
|
||||
|
||||
def _ensure_topology(ch: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||
global _topology_ready
|
||||
if _topology_ready:
|
||||
return
|
||||
with _topology_lock:
|
||||
if _topology_ready:
|
||||
return
|
||||
setup_topology(ch)
|
||||
_topology_ready = True
|
||||
|
||||
|
||||
def publish_job(payload: dict) -> None:
|
||||
"""Публикация job с publisher confirm. Бросает при неудаче."""
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
ch.basic_publish(
|
||||
exchange=EXCHANGE,
|
||||
routing_key=QUEUE,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def publish_retry(payload: dict, retry_count: int) -> None:
|
||||
idx = min(retry_count - 1, len(RETRY_DELAYS) - 1)
|
||||
delay = RETRY_DELAYS[idx]
|
||||
qname = f"attachment.retry.{delay}s"
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
headers = dict(payload.get("_headers") or {})
|
||||
headers["x-retry-count"] = retry_count
|
||||
clean = {k: v for k, v in payload.items() if k != "_headers"}
|
||||
body = json.dumps(clean, ensure_ascii=False, separators=(",", ":"))
|
||||
ch.basic_publish(
|
||||
exchange=RETRY_EXCHANGE,
|
||||
routing_key=qname,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
headers=headers,
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def publish_dlq(payload: dict) -> None:
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
ch.basic_publish(
|
||||
exchange=DLX,
|
||||
routing_key=DLQ,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=2, content_type="application/json"),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
+15
-3
@@ -1,6 +1,9 @@
|
||||
"""S3-клиент (MinIO) для lab4.
|
||||
"""S3-клиент (MinIO) для lab4/lab5.
|
||||
|
||||
Object key генерирует сервер: attachments/<chat_id>/<attachment_id>/original.
|
||||
Object key генерирует сервер:
|
||||
staging: staging/<chat_id>/<attachment_id>/original
|
||||
final: attachments/<chat_id>/<attachment_id>/original
|
||||
variant: attachments/<chat_id>/<attachment_id>/<variant>
|
||||
filename используется только для отображения, не в ключе.
|
||||
"""
|
||||
import os
|
||||
@@ -42,11 +45,20 @@ def client():
|
||||
)
|
||||
|
||||
|
||||
def staging_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||
"""Staging — приватный prefix, worker читает отсюда."""
|
||||
return "staging/%s/%s/original" % (chat_id, attachment_id)
|
||||
|
||||
|
||||
def original_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||
"""Единственный ключ оригинала. Не зависит от filename."""
|
||||
"""Финальный ключ оригинала. Не зависит от filename."""
|
||||
return "attachments/%s/%s/original" % (chat_id, attachment_id)
|
||||
|
||||
|
||||
def variant_key(chat_id: UUID, attachment_id: UUID, variant: str) -> str:
|
||||
return "attachments/%s/%s/%s" % (chat_id, attachment_id, variant)
|
||||
|
||||
|
||||
def put_bytes(key: str, data: bytes, content_type: str) -> None:
|
||||
client().put_object(
|
||||
Bucket=_bucket(),
|
||||
|
||||
@@ -1,22 +1,20 @@
|
||||
"""Фоновая сверка S3 и PostgreSQL (уровень 4).
|
||||
"""Фоновая сверка S3 и PostgreSQL (уровень 4 lab4/lab5).
|
||||
|
||||
- Orphan: объект в S3 есть, а метаданных в attachments нет.
|
||||
- Orphan: объект в S3 есть, а метаданных/вариантов в БД нет.
|
||||
Удаляем только если объект старше ORPHAN_GRACE_SECONDS.
|
||||
- Missing: метаданные есть, объекта в S3 нет.
|
||||
Пишем warning в лог (не удаляем метаданные — учебная политика).
|
||||
- Object key кодирует chat_id и attachment_id, поэтому сверка по метаданным
|
||||
attachments.
|
||||
- Каждый цикл независим; падение логируется и не роняет процесс.
|
||||
- Missing: метаданные есть, объекта в S3 нет — warning.
|
||||
- Staging: объекты staging/ старше grace удаляются (не привязаны к текущей работе).
|
||||
- Также периодически возвращает зависшие processing в queued.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID
|
||||
|
||||
from . import s3
|
||||
from .db import connection, init_pool, close_pool
|
||||
from .postgres import storage
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
@@ -42,12 +40,23 @@ def _grace() -> int:
|
||||
|
||||
|
||||
def _known_keys() -> set[str]:
|
||||
"""Все ожидаемые object key из таблицы attachments."""
|
||||
"""Все ожидаемые object key: оригиналы + варианты."""
|
||||
keys: set[str] = set()
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id, chat_id FROM attachments")
|
||||
for aid, cid in cur.fetchall():
|
||||
cur.execute("SELECT id, chat_id, object_key FROM attachments")
|
||||
for aid, cid, okey in cur.fetchall():
|
||||
keys.add(okey)
|
||||
keys.add(s3.original_key(cid, aid))
|
||||
cur.execute("SELECT attachment_id, variant FROM attachment_variants")
|
||||
# нужен chat_id для variant_key
|
||||
# variants: отдельным запросом с join
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT a.chat_id, v.attachment_id, v.variant"
|
||||
" FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id"
|
||||
)
|
||||
for cid, aid, variant in cur.fetchall():
|
||||
keys.add(s3.variant_key(cid, aid, variant))
|
||||
return keys
|
||||
|
||||
|
||||
@@ -59,7 +68,9 @@ def _run_once() -> dict:
|
||||
orphan_deleted = 0
|
||||
missing = 0
|
||||
scanned = 0
|
||||
staging_deleted = 0
|
||||
|
||||
# attachments/ — orphan по known
|
||||
for obj in s3.list_objects("attachments/"):
|
||||
scanned += 1
|
||||
key = obj["Key"]
|
||||
@@ -79,19 +90,44 @@ def _run_once() -> dict:
|
||||
orphan_deleted += 1
|
||||
log.info("event=orphan_deleted key=%s", key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=orphan_delete_failed key=%s type=%s", key, type(exc).__name__)
|
||||
log.error("event=orphan_delete_failed key=%s type=%s",
|
||||
key, type(exc).__name__)
|
||||
|
||||
# Проверяем обратную сторону: метаданные без объекта.
|
||||
# staging/ — удаляем только старое (не in-flight).
|
||||
for obj in s3.list_objects("staging/"):
|
||||
lm = obj.get("LastModified")
|
||||
if lm is None:
|
||||
continue
|
||||
if lm.tzinfo is None:
|
||||
lm = lm.replace(tzinfo=timezone.utc)
|
||||
if lm > grace_cutoff:
|
||||
continue
|
||||
try:
|
||||
s3.delete_object(obj["Key"])
|
||||
staging_deleted += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# missing
|
||||
for key in known:
|
||||
if s3.head_object(key) is None:
|
||||
missing += 1
|
||||
log.warning("event=missing_object key=%s", key)
|
||||
|
||||
# зависшие processing → queued
|
||||
try:
|
||||
recovered = storage.recover_stuck_processing()
|
||||
if recovered:
|
||||
log.info("event=stuck_processing_recovered count=%s", recovered)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=recover_stuck_failed type=%s", type(exc).__name__)
|
||||
|
||||
return {
|
||||
"scanned": scanned,
|
||||
"orphan_deleted": orphan_deleted,
|
||||
"missing": missing,
|
||||
"known": len(known),
|
||||
"staging_deleted": staging_deleted,
|
||||
}
|
||||
|
||||
|
||||
@@ -104,9 +140,10 @@ def main() -> None:
|
||||
try:
|
||||
stats = _run_once()
|
||||
log.info(
|
||||
"event=cleanup_pass scanned=%s known=%s orphan_deleted=%s missing=%s",
|
||||
stats["scanned"], stats["known"],
|
||||
stats["orphan_deleted"], stats["missing"],
|
||||
"event=cleanup_pass scanned=%s known=%s orphan_deleted=%s"
|
||||
" missing=%s staging_deleted=%s",
|
||||
stats["scanned"], stats["known"], stats["orphan_deleted"],
|
||||
stats["missing"], stats["staging_deleted"],
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=cleanup_failed type=%s", type(exc).__name__)
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Worker lab5: обработка вложений из RabbitMQ.
|
||||
|
||||
- at-least-once: manual ack после durable эффекта.
|
||||
- идемпотентность: ключ (attachment_id, pipeline_version, variant).
|
||||
- retry с backoff через TTL retry-очереди, затем DLQ.
|
||||
- lease: processing_until, зависшие возвращаются в queued.
|
||||
- thumbnail 256×256 (JPEG), crop 128×128 (JPEG), optimized WebP 1280×1280.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pika
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .storage import s3
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .storage.postgres import storage
|
||||
from .storage.rabbit import (
|
||||
QUEUE, EXCHANGE, MAX_ATTEMPTS, connect, setup_topology,
|
||||
publish_retry, publish_dlq,
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
log = logging.getLogger("worker")
|
||||
|
||||
PIPELINE_VERSION = 1
|
||||
LEASE_SECONDS = 60
|
||||
THUMB_SIZE = (256, 256)
|
||||
CROP_SIZE = (128, 128)
|
||||
OPT_SIZE = (1280, 1280)
|
||||
OPT_QUALITY = 82
|
||||
|
||||
_stop = False
|
||||
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
global _stop
|
||||
log.info("event=sigterm_received signal=%s", signum)
|
||||
_stop = True
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _to_rgb_white(img: Image.Image) -> Image.Image:
|
||||
"""Alpha компонуется на белый; EXIF orientation применяется."""
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
img = img.convert("RGBA")
|
||||
bg = Image.new("RGB", img.size, (255, 255, 255))
|
||||
bg.paste(img, mask=img.split()[-1])
|
||||
return bg
|
||||
if img.mode != "RGB":
|
||||
return img.convert("RGB")
|
||||
return img
|
||||
|
||||
|
||||
def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""Вписать в 256×256 без увеличения. Округление вниз, минимум 1 px."""
|
||||
w, h = img.size
|
||||
scale = min(THUMB_SIZE[0] / w, THUMB_SIZE[1] / h, 1.0)
|
||||
nw = max(1, int(w * scale))
|
||||
nh = max(1, int(h * scale))
|
||||
thumb = img.resize((nw, nh), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
thumb.save(buf, format="JPEG", quality=88, optimize=True)
|
||||
return thumb, buf.getvalue()
|
||||
|
||||
|
||||
def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""Центрированный квадрат 128×128 (маленькие допускают увеличение)."""
|
||||
w, h = img.size
|
||||
side = min(w, h)
|
||||
left = (w - side) // 2
|
||||
top = (h - side) // 2
|
||||
sq = img.crop((left, top, left + side, top + side))
|
||||
crop = sq.resize(CROP_SIZE, Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
crop.save(buf, format="JPEG", quality=88, optimize=True)
|
||||
return crop, buf.getvalue()
|
||||
|
||||
|
||||
def _make_optimized(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""WebP, вписан в 1280×1280 без увеличения, EXIF удалён."""
|
||||
w, h = img.size
|
||||
scale = min(OPT_SIZE[0] / w, OPT_SIZE[1] / h, 1.0)
|
||||
nw = max(1, int(w * scale))
|
||||
nh = max(1, int(h * scale))
|
||||
opt = img.resize((nw, nh), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
opt.save(buf, format="WEBP", quality=OPT_QUALITY, method=4)
|
||||
return opt, buf.getvalue()
|
||||
|
||||
|
||||
def _sha256(data: bytes) -> str:
|
||||
import hashlib
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def process_job(payload: dict) -> None:
|
||||
"""Обработка одного job. Идемпотентна: finalize_ready использует ON CONFLICT."""
|
||||
attachment_id = payload["attachment_id"]
|
||||
pipeline_version = payload.get("pipeline_version", 1)
|
||||
job_id = payload["job_id"]
|
||||
|
||||
log.info("event=job_received job_id=%s attachment_id=%s attempt=%s",
|
||||
job_id, attachment_id, payload.get("attempt", 1))
|
||||
|
||||
# 1) Захватить lease. Если уже ready/failed — no-op (дубль).
|
||||
if not storage.claim_processing(attachment_id, LEASE_SECONDS):
|
||||
log.info("event=job_skipped_already_done attachment_id=%s", attachment_id)
|
||||
return
|
||||
|
||||
# 2) Получить staging key и метаданные.
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
log.warning("event=attachment_missing attachment_id=%s", attachment_id)
|
||||
return
|
||||
att, staging_key = pair
|
||||
if att.status == "ready":
|
||||
log.info("event=already_ready attachment_id=%s", attachment_id)
|
||||
return
|
||||
|
||||
# 3) Скачать staging из S3.
|
||||
try:
|
||||
raw, ctype = s3.get_object(staging_key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Временная ошибка S3 — retry.
|
||||
raise RuntimeError("staging_unavailable") from exc
|
||||
|
||||
# 4) Проверить, что файл всё ещё валиден (worker defense-in-depth).
|
||||
try:
|
||||
img = Image.open(io.BytesIO(raw))
|
||||
img.load()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
storage.finalize_failed(attachment_id, "invalid_image")
|
||||
log.warning("event=invalid_image attachment_id=%s type=%s",
|
||||
attachment_id, type(exc).__name__)
|
||||
return
|
||||
|
||||
img_rgb = _to_rgb_white(img)
|
||||
|
||||
# 5) Записать финальный оригинал.
|
||||
final_key = s3.original_key(att.chat_id, att.id)
|
||||
s3.put_bytes(final_key, raw, att.content_type)
|
||||
|
||||
variants = [{
|
||||
"name": "original",
|
||||
"object_key": final_key,
|
||||
"content_type": att.content_type,
|
||||
"size_bytes": len(raw),
|
||||
"width": img.width,
|
||||
"height": img.height,
|
||||
"sha256": _sha256(raw),
|
||||
}]
|
||||
|
||||
# 6) Thumbnail (обязателен).
|
||||
_, thumb_bytes = _make_thumbnail(img_rgb)
|
||||
thumb_key = s3.variant_key(att.chat_id, att.id, "thumbnail")
|
||||
s3.put_bytes(thumb_key, thumb_bytes, "image/jpeg")
|
||||
tw, th = Image.open(io.BytesIO(thumb_bytes)).size
|
||||
variants.append({
|
||||
"name": "thumbnail",
|
||||
"object_key": thumb_key,
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(thumb_bytes),
|
||||
"width": tw,
|
||||
"height": th,
|
||||
"sha256": _sha256(thumb_bytes),
|
||||
})
|
||||
|
||||
# 7) Crop (level 4).
|
||||
_, crop_bytes = _make_crop(img_rgb)
|
||||
crop_key = s3.variant_key(att.chat_id, att.id, "crop")
|
||||
s3.put_bytes(crop_key, crop_bytes, "image/jpeg")
|
||||
cw, ch = Image.open(io.BytesIO(crop_bytes)).size
|
||||
variants.append({
|
||||
"name": "crop",
|
||||
"object_key": crop_key,
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(crop_bytes),
|
||||
"width": cw,
|
||||
"height": ch,
|
||||
"sha256": _sha256(crop_bytes),
|
||||
})
|
||||
|
||||
# 8) Optimized WebP (level 4).
|
||||
_, opt_bytes = _make_optimized(img_rgb)
|
||||
opt_key = s3.variant_key(att.chat_id, att.id, "optimized")
|
||||
s3.put_bytes(opt_key, opt_bytes, "image/webp")
|
||||
ow, oh = Image.open(io.BytesIO(opt_bytes)).size
|
||||
variants.append({
|
||||
"name": "optimized",
|
||||
"object_key": opt_key,
|
||||
"content_type": "image/webp",
|
||||
"size_bytes": len(opt_bytes),
|
||||
"width": ow,
|
||||
"height": oh,
|
||||
"sha256": _sha256(opt_bytes),
|
||||
})
|
||||
|
||||
# 9) Атомарно: variants + status=ready.
|
||||
storage.finalize_ready(attachment_id, pipeline_version, variants)
|
||||
|
||||
# 10) Удалить staging после безопасной фиксации.
|
||||
try:
|
||||
s3.delete_object(staging_key)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
log.info("event=job_ready attachment_id=%s job_id=%s variants=%d",
|
||||
attachment_id, job_id, len(variants))
|
||||
|
||||
|
||||
def _on_message(ch, method, properties, body):
|
||||
"""Callback consumer. ack/nack — явно."""
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except Exception:
|
||||
# Битый JSON — постоянная ошибка.
|
||||
log.error("event=invalid_job_json")
|
||||
ch.basic_nack(method.delivery_tag, requeue=False)
|
||||
return
|
||||
|
||||
headers = dict(properties.headers or {})
|
||||
retry_count = int(headers.get("x-retry-count", 0))
|
||||
payload["attempt"] = retry_count + 1
|
||||
payload["_headers"] = headers
|
||||
|
||||
try:
|
||||
process_job(payload)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
||||
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
||||
if retry_count + 1 >= MAX_ATTEMPTS:
|
||||
# Исчерпаны попытки — failed + DLQ.
|
||||
try:
|
||||
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
||||
except Exception:
|
||||
pass
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
return
|
||||
# Retry через TTL-очередь, затем ack текущей.
|
||||
try:
|
||||
publish_retry(payload, retry_count + 1)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception:
|
||||
# Не смогли опубликовать retry — вернуть в очередь.
|
||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
init_pool()
|
||||
log.info("event=worker_start queue=%s max_attempts=%s", QUEUE, MAX_ATTEMPTS)
|
||||
|
||||
while not _stop:
|
||||
try:
|
||||
conn = connect()
|
||||
ch = conn.channel()
|
||||
setup_topology(ch)
|
||||
ch.basic_qos(prefetch_count=1)
|
||||
ch.basic_consume(queue=QUEUE, on_message_callback=_on_message)
|
||||
log.info("event=consumer_started")
|
||||
|
||||
while not _stop and conn.is_open:
|
||||
conn.process_data_events(time_limit=1)
|
||||
|
||||
ch.stop_consuming()
|
||||
conn.close()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=worker_loop_error type=%s", type(exc).__name__)
|
||||
time.sleep(3)
|
||||
|
||||
close_pool()
|
||||
log.info("event=worker_stop")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user