feat: implement transactional outbox, dlq and worker timeouts

This commit is contained in:
2026-11-12 21:35:48 +03:00
parent 067b2d866f
commit 479dacc934
7 changed files with 278 additions and 221 deletions
+35 -120
View File
@@ -1,170 +1,85 @@
from datetime import datetime, timezone from datetime import datetime, timezone
from uuid import UUID, uuid4 from uuid import UUID, uuid4
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PG_UUID, JSONB from sqlalchemy.dialects.postgresql import UUID as PG_UUID, JSONB
from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.orm import Mapped, mapped_column
from .base import Base from .base import Base
def _now() -> datetime: def _now() -> datetime:
return datetime.now(timezone.utc) return datetime.now(timezone.utc)
class User(Base): class User(Base):
__tablename__ = "users" __tablename__ = "users"
id: Mapped[UUID] = mapped_column( id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
PG_UUID(as_uuid=True), primary_key=True, default=uuid4 username: Mapped[str] = mapped_column(String(32), unique=True, nullable=False, index=True)
)
username: Mapped[str] = mapped_column(
String(32), unique=True, nullable=False, index=True
)
display_name: Mapped[str] = mapped_column(String(100), nullable=False) display_name: Mapped[str] = mapped_column(String(100), nullable=False)
password_hash: Mapped[str] = mapped_column(Text, nullable=False) password_hash: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column( created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
DateTime(timezone=True), default=_now, nullable=False
)
class Chat(Base): class Chat(Base):
__tablename__ = "chats" __tablename__ = "chats"
id: Mapped[UUID] = mapped_column( id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
PG_UUID(as_uuid=True), primary_key=True, default=uuid4
)
title: Mapped[str] = mapped_column(String(100), nullable=False) title: Mapped[str] = mapped_column(String(100), nullable=False)
created_at: Mapped[datetime] = mapped_column( created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
DateTime(timezone=True), default=_now, nullable=False
)
__table_args__ = (Index("idx_chats_created_id", "created_at", "id"),) __table_args__ = (Index("idx_chats_created_id", "created_at", "id"),)
class ChatMember(Base): class ChatMember(Base):
__tablename__ = "chat_members" __tablename__ = "chat_members"
chat_id: Mapped[UUID] = mapped_column( chat_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True)
PG_UUID(as_uuid=True), user_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
ForeignKey("chats.id", ondelete="CASCADE"),
primary_key=True,
)
user_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True,
)
__table_args__ = (Index("idx_chat_members_user", "user_id", "chat_id"),) __table_args__ = (Index("idx_chat_members_user", "user_id", "chat_id"),)
class Message(Base): class Message(Base):
__tablename__ = "messages" __tablename__ = "messages"
id: Mapped[UUID] = mapped_column( id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
PG_UUID(as_uuid=True), primary_key=True, default=uuid4 chat_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False)
) sender_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
chat_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey("chats.id", ondelete="CASCADE"),
nullable=False,
)
sender_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True), ForeignKey("users.id"), nullable=False
)
text: Mapped[str] = mapped_column(Text, nullable=False) text: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column( created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
DateTime(timezone=True), default=_now, nullable=False __table_args__ = (Index("idx_messages_chat_created_id", "chat_id", "created_at", "id"),)
)
__table_args__ = (
Index("idx_messages_chat_created_id", "chat_id", "created_at", "id"),
)
class SessionRow(Base): class SessionRow(Base):
__tablename__ = "sessions" __tablename__ = "sessions"
id: Mapped[UUID] = mapped_column( id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
PG_UUID(as_uuid=True), primary_key=True, default=uuid4 user_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
) token_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, index=True)
user_id: Mapped[UUID] = mapped_column( expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, index=True)
PG_UUID(as_uuid=True), created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
)
token_hash: Mapped[str] = mapped_column(
String(64), unique=True, nullable=False, index=True
)
expires_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, index=True
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, nullable=False
)
class IdempotencyRecord(Base): class IdempotencyRecord(Base):
__tablename__ = "idempotency_keys" __tablename__ = "idempotency_keys"
id: Mapped[UUID] = mapped_column( id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
PG_UUID(as_uuid=True), primary_key=True, default=uuid4 user_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
)
user_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey("users.id", ondelete="CASCADE"),
nullable=False
)
key: Mapped[str] = mapped_column(String(128), nullable=False) key: Mapped[str] = mapped_column(String(128), nullable=False)
request_hash: Mapped[str] = mapped_column(String(64), nullable=False) request_hash: Mapped[str] = mapped_column(String(64), nullable=False)
response_body: Mapped[str] = mapped_column(Text, nullable=False) response_body: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column( created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
DateTime(timezone=True), default=_now, nullable=False __table_args__ = (UniqueConstraint("user_id", "key", name="uq_idempotency_user_key"),)
)
__table_args__ = (
UniqueConstraint("user_id", "key", name="uq_idempotency_user_key"),
)
class Attachment(Base): class Attachment(Base):
__tablename__ = "attachments" __tablename__ = "attachments"
id: Mapped[UUID] = mapped_column( id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
PG_UUID(as_uuid=True), primary_key=True, default=uuid4 chat_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False)
) owner_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
chat_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey("chats.id", ondelete="CASCADE"),
nullable=False
)
owner_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True), ForeignKey("users.id"), nullable=False
)
filename: Mapped[str] = mapped_column(String(255), nullable=False) filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[str] = mapped_column(String(100), nullable=False) content_type: Mapped[str] = mapped_column(String(100), nullable=False)
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False) size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False) sha256: Mapped[str] = mapped_column(String(64), nullable=False)
# ИЗМЕНЕНО: по умолчанию "queued", так как теперь обработка асинхронная
status: Mapped[str] = mapped_column(String(20), default="queued", nullable=False) status: Mapped[str] = mapped_column(String(20), default="queued", nullable=False)
error_code: Mapped[str] = mapped_column(String(50), nullable=True) error_code: Mapped[str] = mapped_column(String(50), nullable=True)
s3_key: Mapped[str] = mapped_column(String(500), nullable=False) s3_key: Mapped[str] = mapped_column(String(500), nullable=False)
# ДОБАВЛЕНО: колонка для хранения метаданных миниатюр
variants: Mapped[list] = mapped_column(JSONB, default=list, nullable=False) variants: Mapped[list] = mapped_column(JSONB, default=list, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
created_at: Mapped[datetime] = mapped_column( updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now, nullable=False)
DateTime(timezone=True), default=_now, nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, onupdate=_now, nullable=False
)
class MessageAttachment(Base): class MessageAttachment(Base):
__tablename__ = "message_attachments" __tablename__ = "message_attachments"
message_id: Mapped[UUID] = mapped_column( message_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True)
PG_UUID(as_uuid=True), attachment_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("attachments.id", ondelete="CASCADE"), primary_key=True)
ForeignKey("messages.id", ondelete="CASCADE"),
primary_key=True class Outbox(Base):
) __tablename__ = "outbox"
attachment_id: Mapped[UUID] = mapped_column( id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
PG_UUID(as_uuid=True), payload: Mapped[str] = mapped_column(Text, nullable=False)
ForeignKey("attachments.id", ondelete="CASCADE"), status: Mapped[str] = mapped_column(String(20), default="pending", nullable=False, index=True)
primary_key=True created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
)
+56 -15
View File
@@ -3,6 +3,7 @@ import socket
import uuid import uuid
import hashlib import hashlib
import json import json
import asyncio
from contextvars import ContextVar from contextvars import ContextVar
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from typing import Optional from typing import Optional
@@ -16,13 +17,14 @@ from sqlalchemy import select, text
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.base import BaseHTTPMiddleware
from starlette.concurrency import run_in_threadpool
from .auth import ( from .auth import (
SESSION_TTL, create_session, get_current_user, hash_password, SESSION_TTL, create_session, get_current_user, hash_password,
revoke_current_session, verify_password, revoke_current_session, verify_password,
) )
from .db.models import IdempotencyRecord, User, Attachment, MessageAttachment from .db.models import IdempotencyRecord, User, Attachment, MessageAttachment, Outbox
from .db.session import get_db from .db.session import get_db, async_session
from .models import CreateChat, CreateMessage, CreateUser from .models import CreateChat, CreateMessage, CreateUser
from .repositories import chats as chats_repo from .repositories import chats as chats_repo
from .repositories import messages as messages_repo from .repositories import messages as messages_repo
@@ -40,6 +42,25 @@ _HTTP_CODES = {
429: "rate_limited", 503: "unavailable", 500: "internal_error", 429: "rate_limited", 503: "unavailable", 500: "internal_error",
} }
# --- ФОНОВЫЙ ПРОЦЕСС OUTBOX ---
# Каждые 5 секунд ищет в БД неотправленные задачи и кидает их в RabbitMQ
async def outbox_publisher():
while True:
await asyncio.sleep(5)
try:
async with async_session() as db:
jobs = (await db.execute(select(Outbox).where(Outbox.status == "pending").limit(10))).scalars().all()
for job in jobs:
try:
# публикуем в rabbitmq в отдельном потоке, чтобы не блокировать event loop
await run_in_threadpool(publish_task, json.loads(job.payload))
job.status = "sent"
await db.commit()
except Exception as e:
print(f"Outbox failed to publish {job.id}: {e}", flush=True)
except Exception:
pass
def err_json(status: int, code: str, message: str) -> JSONResponse: def err_json(status: int, code: str, message: str) -> JSONResponse:
resp = JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id_var.get()}}) resp = JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id_var.get()}})
resp.headers["X-Instance-Id"] = INSTANCE_ID resp.headers["X-Instance-Id"] = INSTANCE_ID
@@ -59,8 +80,10 @@ app.add_middleware(RequestIdMiddleware)
security = HTTPBasic(auto_error=False) security = HTTPBasic(auto_error=False)
@app.on_event("startup") @app.on_event("startup")
def startup_event(): async def startup_event():
ensure_bucket() ensure_bucket()
# Запускаем фоновую задачу для отправки сообщений из БД в RabbitMQ
asyncio.create_task(outbox_publisher())
@app.exception_handler(RequestValidationError) @app.exception_handler(RequestValidationError)
async def _validation(request: Request, exc: RequestValidationError): async def _validation(request: Request, exc: RequestValidationError):
@@ -244,6 +267,9 @@ async def upload_attachment(chat_id: UUID, request: Request, filename: str = Que
chat = await chats_repo.get_if_member(db, chat_id, user.id) chat = await chats_repo.get_if_member(db, chat_id, user.id)
if not chat: raise HTTPException(404, "Chat not found") if not chat: raise HTTPException(404, "Chat not found")
if "/" in filename or "\\" in filename or "\x00" in filename:
raise HTTPException(400, "Invalid filename")
content = await request.body() content = await request.body()
mime = validate_image(content) mime = validate_image(content)
@@ -251,20 +277,31 @@ async def upload_attachment(chat_id: UUID, request: Request, filename: str = Que
ext = ".png" if mime == "image/png" else ".jpg" ext = ".png" if mime == "image/png" else ".jpg"
s3_key = f"{chat_id}/{uuid.uuid4()}{ext}" s3_key = f"{chat_id}/{uuid.uuid4()}{ext}"
s3.put_object(Bucket=BUCKET, Key=s3_key, Body=content, ContentType=mime) # Загрузка в S3
try:
s3.put_object(Bucket=BUCKET, Key=s3_key, Body=content, ContentType=mime)
except Exception:
raise HTTPException(503, "S3 Storage unavailable")
att = Attachment(chat_id=chat_id, owner_id=user.id, filename=filename, content_type=mime, size_bytes=len(content), sha256=sha256, status="queued", s3_key=s3_key) att = Attachment(chat_id=chat_id, owner_id=user.id, filename=filename, content_type=mime, size_bytes=len(content), sha256=sha256, status="queued", s3_key=s3_key)
db.add(att) db.add(att)
await db.commit()
await db.refresh(att)
# отправляем задачу в rabbitmq try:
publish_task({ # Получаем ID вложения без коммита
"attachment_id": str(att.id), await db.flush()
"chat_id": str(chat_id),
"s3_key": s3_key, # Создаем задачу в Outbox
"mime": mime, task = {"attachment_id": str(att.id), "chat_id": str(chat_id), "s3_key": s3_key, "mime": mime}
}) db.add(Outbox(payload=json.dumps(task), status="pending"))
# Коммитим ОБЕ записи атомарно
await db.commit()
await db.refresh(att)
except Exception:
await db.rollback()
try: s3.delete_object(Bucket=BUCKET, Key=s3_key)
except Exception: pass
raise HTTPException(500, "Database error while saving attachment")
return _attachment_json(att) return _attachment_json(att)
@@ -299,8 +336,12 @@ async def download_attachment(attachment_id: UUID, variant: str = Query("origina
key = f"{att.s3_key}_opt.webp" key = f"{att.s3_key}_opt.webp"
mime = "image/webp" mime = "image/webp"
obj = s3.get_object(Bucket=BUCKET, Key=key) try:
content = obj["Body"].read() obj = s3.get_object(Bucket=BUCKET, Key=key)
content = obj["Body"].read()
except Exception:
raise HTTPException(503, "S3 Storage unavailable")
return Response(content=content, media_type=mime) return Response(content=content, media_type=mime)
if __name__ == "__main__": if __name__ == "__main__":
+18 -1
View File
@@ -4,11 +4,28 @@ import json
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/") RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/")
QUEUE_NAME = "attachment_tasks" QUEUE_NAME = "attachment_tasks"
DLQ_NAME = "attachment_tasks_dlq"
def setup_rabbitmq(channel):
# Создаем Dead Letter Exchange и Queue
channel.exchange_declare(exchange='dlx', exchange_type='direct', durable=True)
channel.queue_declare(queue=DLQ_NAME, durable=True)
channel.queue_bind(exchange='dlx', queue=DLQ_NAME, routing_key='dlq')
# Основная очередь, привязанная к DLX
channel.queue_declare(
queue=QUEUE_NAME,
durable=True,
arguments={
'x-dead-letter-exchange': 'dlx',
'x-dead-letter-routing-key': 'dlq'
}
)
def publish_task(task: dict): def publish_task(task: dict):
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL)) connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
channel = connection.channel() channel = connection.channel()
channel.queue_declare(queue=QUEUE_NAME, durable=True) setup_rabbitmq(channel)
channel.basic_publish( channel.basic_publish(
exchange="", exchange="",
routing_key=QUEUE_NAME, routing_key=QUEUE_NAME,
+59 -82
View File
@@ -4,127 +4,104 @@ import os
import io import io
import hashlib import hashlib
from datetime import datetime, timezone from datetime import datetime, timezone
import pika import pika
from PIL import Image, ImageOps from PIL import Image, ImageOps
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy.pool import NullPool from sqlalchemy.pool import NullPool
from .db.models import Attachment from .db.models import Attachment
from .s3_client import s3, BUCKET from .s3_client import s3, BUCKET
from .queue import RABBITMQ_URL, QUEUE_NAME, setup_rabbitmq
DATABASE_URL = os.getenv("DATABASE_URL") DATABASE_URL = os.getenv("DATABASE_URL")
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/")
QUEUE_NAME = "attachment_tasks"
async def process_attachment(task: dict): async def process_attachment(task: dict):
att_id = task["attachment_id"] att_id = task["attachment_id"]
s3_key = task["s3_key"] s3_key = task["s3_key"]
# ВАЖНО: создаем engine внутри функции с NullPool, чтобы избежать ошибки разных event loop
engine = create_async_engine(DATABASE_URL, poolclass=NullPool) engine = create_async_engine(DATABASE_URL, poolclass=NullPool)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False) AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
try: try:
async with AsyncSessionLocal() as session: async with AsyncSessionLocal() as session:
att = await session.get(Attachment, att_id) att = await session.get(Attachment, att_id)
if not att: if not att: return
return if att.status == "ready" and len(att.variants or []) == 3: return
# идемпотентность: если уже обработано, пропускаем obj = s3.get_object(Bucket=BUCKET, Key=s3_key)
if att.status == "ready" and len(att.variants or []) == 3: content = obj["Body"].read()
return img = Image.open(io.BytesIO(content))
try: img = ImageOps.exif_transpose(img)
# получаем оригинал if img.mode in ("RGBA", "LA"):
obj = s3.get_object(Bucket=BUCKET, Key=s3_key) background = Image.new("RGB", img.size, (255, 255, 255))
content = obj["Body"].read() background.paste(img, mask=img.split()[-1])
img = Image.open(io.BytesIO(content)) img = background
elif img.mode != "RGB":
img = img.convert("RGB")
# разворачиваем по exif и убираем прозрачность variants_meta = []
img = ImageOps.exif_transpose(img) thumb = img.copy()
if img.mode in ("RGBA", "LA"): thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
background = Image.new("RGB", img.size, (255, 255, 255)) thumb_bytes = io.BytesIO()
background.paste(img, mask=img.split()[-1]) thumb.save(thumb_bytes, format="JPEG")
img = background thumb_data = thumb_bytes.getvalue()
elif img.mode != "RGB": s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_thumb.jpg", Body=thumb_data, ContentType="image/jpeg")
img = img.convert("RGB") variants_meta.append({"name": "thumbnail", "content_type": "image/jpeg", "width": thumb.width, "height": thumb.height, "size_bytes": len(thumb_data), "sha256": hashlib.sha256(thumb_data).hexdigest()})
variants_meta = [] crop_img = img.copy()
width, height = crop_img.size
min_dim = min(width, height)
crop_img = crop_img.crop(((width - min_dim) / 2, (height - min_dim) / 2, (width + min_dim) / 2, (height + min_dim) / 2))
crop_img = crop_img.resize((128, 128), Image.Resampling.LANCZOS)
crop_bytes = io.BytesIO()
crop_img.save(crop_bytes, format="JPEG")
crop_data = crop_bytes.getvalue()
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_crop.jpg", Body=crop_data, ContentType="image/jpeg")
variants_meta.append({"name": "crop", "content_type": "image/jpeg", "width": 128, "height": 128, "size_bytes": len(crop_data), "sha256": hashlib.sha256(crop_data).hexdigest()})
# 1. Thumbnail (256x256) opt_img = img.copy()
thumb = img.copy() opt_img.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS) opt_bytes = io.BytesIO()
thumb_bytes = io.BytesIO() opt_img.save(opt_bytes, format="WEBP", quality=85)
thumb.save(thumb_bytes, format="JPEG") opt_data = opt_bytes.getvalue()
thumb_data = thumb_bytes.getvalue() s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_opt.webp", Body=opt_data, ContentType="image/webp")
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_thumb.jpg", Body=thumb_data, ContentType="image/jpeg") variants_meta.append({"name": "optimized", "content_type": "image/webp", "width": opt_img.width, "height": opt_img.height, "size_bytes": len(opt_data), "sha256": hashlib.sha256(opt_data).hexdigest()})
variants_meta.append({
"name": "thumbnail", "content_type": "image/jpeg",
"width": thumb.width, "height": thumb.height,
"size_bytes": len(thumb_data), "sha256": hashlib.sha256(thumb_data).hexdigest()
})
# 2. Crop (128x128) att.status = "ready"
crop_img = img.copy() att.error_code = None
width, height = crop_img.size att.variants = variants_meta
min_dim = min(width, height) att.updated_at = datetime.now(timezone.utc)
left = (width - min_dim) / 2 await session.commit()
top = (height - min_dim) / 2 except Exception as e:
right = (width + min_dim) / 2 async with AsyncSessionLocal() as session:
bottom = (height + min_dim) / 2 att = await session.get(Attachment, att_id)
crop_img = crop_img.crop((left, top, right, bottom)) if att:
crop_img = crop_img.resize((128, 128), Image.Resampling.LANCZOS)
crop_bytes = io.BytesIO()
crop_img.save(crop_bytes, format="JPEG")
crop_data = crop_bytes.getvalue()
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_crop.jpg", Body=crop_data, ContentType="image/jpeg")
variants_meta.append({
"name": "crop", "content_type": "image/jpeg",
"width": 128, "height": 128,
"size_bytes": len(crop_data), "sha256": hashlib.sha256(crop_data).hexdigest()
})
# 3. Optimized (WebP)
opt_img = img.copy()
opt_img.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
opt_bytes = io.BytesIO()
opt_img.save(opt_bytes, format="WEBP", quality=85)
opt_data = opt_bytes.getvalue()
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_opt.webp", Body=opt_data, ContentType="image/webp")
variants_meta.append({
"name": "optimized", "content_type": "image/webp",
"width": opt_img.width, "height": opt_img.height,
"size_bytes": len(opt_data), "sha256": hashlib.sha256(opt_data).hexdigest()
})
att.status = "ready"
att.error_code = None
att.variants = variants_meta
att.updated_at = datetime.now(timezone.utc)
await session.commit()
except Exception as e:
att.status = "failed" att.status = "failed"
att.error_code = "processing_failed" att.error_code = "processing_failed"
att.updated_at = datetime.now(timezone.utc) att.updated_at = datetime.now(timezone.utc)
await session.commit() await session.commit()
print(f"Error processing {att_id}: {e}", flush=True) print(f"Error processing {att_id}: {e}", flush=True)
raise e
finally: finally:
await engine.dispose() await engine.dispose()
def callback(ch, method, properties, body): def callback(ch, method, properties, body):
task = json.loads(body) task = json.loads(body)
asyncio.run(process_attachment(task)) try:
ch.basic_ack(delivery_tag=method.delivery_tag) # Таймаут 30 секунд
asyncio.run(asyncio.wait_for(process_attachment(task), timeout=30.0))
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception as e:
print(f"Task failed, routing to DLQ. Error: {e}", flush=True)
# requeue=False отправляет в DLQ
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
def main(): def main():
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL)) connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
channel = connection.channel() channel = connection.channel()
channel.queue_declare(queue=QUEUE_NAME, durable=True) setup_rabbitmq(channel)
channel.basic_qos(prefetch_count=1) channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=QUEUE_NAME, on_message_callback=callback) channel.basic_consume(queue=QUEUE_NAME, on_message_callback=callback)
print("Worker started, waiting for messages...", flush=True) print("Worker started...", flush=True)
channel.start_consuming() channel.start_consuming()
if __name__ == "__main__": if __name__ == "__main__":
@@ -0,0 +1,38 @@
"""add outbox table
Revision ID: 164e1973508a
Revises: d15635c49e1a
Create Date: 2026-11-12 21:18:12.919668
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '164e1973508a'
down_revision: Union[str, None] = 'd15635c49e1a'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('outbox',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('payload', sa.Text(), nullable=False),
sa.Column('status', sa.String(length=20), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_outbox_status'), 'outbox', ['status'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_outbox_status'), table_name='outbox')
op.drop_table('outbox')
# ### end Alembic commands ###
@@ -20,7 +20,7 @@ depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ### # ### commands auto generated by Alembic - please adjust! ###
op.add_column('attachments', sa.Column('variants', postgresql.JSONB(astext_type=sa.Text()), nullable=False)) op.add_column('attachments', sa.Column('variants', postgresql.JSONB(astext_type=sa.Text()), server_default='[]', nullable=False))
# ### end Alembic commands ### # ### end Alembic commands ###
+69
View File
@@ -0,0 +1,69 @@
import base64
import json
import urllib.request
import urllib.error
import uuid
BASE = "http://127.0.0.1:8080"
PASSWORD = "Example-only-not-a-real-secret-123"
def call(method, path, body=None, token=None, raw_data=None, content_type=None):
h = {"Accept": "application/json"}
if token: h["Authorization"] = f"Bearer {token}"
if method == "POST" and "/messages" in path:
h["Idempotency-Key"] = str(uuid.uuid4())
data = None
if raw_data is not None:
data = raw_data
if content_type: h["Content-Type"] = content_type
elif body is not None:
data = json.dumps(body).encode("utf-8")
h["Content-Type"] = "application/json"
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
with urllib.request.urlopen(req, timeout=10) as r:
payload = r.read()
return r.status, (json.loads(payload) if payload and r.headers.get_content_type()=="application/json" else payload)
except urllib.error.HTTPError as e:
payload = e.read()
try: return e.code, json.loads(payload)
except: return e.code, payload
def setup():
name = f"test_{uuid.uuid4().hex[:6]}"
s, u = call("POST", "/api/v1/users", {"username": name, "display_name": name, "password": PASSWORD})
cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
req = urllib.request.Request(BASE + "/api/v1/auth/sessions", headers={"Authorization": f"Basic {cred}"}, method="POST")
with urllib.request.urlopen(req) as r:
tok = json.loads(r.read())["token"]
s, chat = call("POST", "/api/v1/chats", {"title": "test", "member_ids": [u["id"]]}, token=tok)
return u, tok, chat["id"]
def test_large_file():
u, tok, cid = setup()
big_data = b"\x89PNG\r\n\x1a\n" + b"0" * (11 * 1024 * 1024)
s, _ = call("POST", f"/api/v1/chats/{cid}/attachments?filename=big.png", token=tok, raw_data=big_data, content_type="image/png")
assert s == 413
def test_corrupted_image():
u, tok, cid = setup()
s, _ = call("POST", f"/api/v1/chats/{cid}/attachments?filename=bad.png", token=tok, raw_data=b"not an image", content_type="image/png")
assert s == 415
def test_mime_spoofing():
u, tok, cid = setup()
s, _ = call("POST", f"/api/v1/chats/{cid}/attachments?filename=fake.png", token=tok, raw_data=b"<html>hack</html>", content_type="image/png")
assert s == 415
def test_foreign_attachment():
u1, tok1, cid1 = setup()
u2, tok2, cid2 = setup()
s, att = call("POST", f"/api/v1/chats/{cid1}/attachments?filename=test.png", token=tok1, raw_data=b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82", content_type="image/png")
assert s == 202, f"Upload failed: {att}"
s, response_body = call("POST", f"/api/v1/chats/{cid2}/messages", {"text": "hi", "attachment_ids": [att["id"]]}, token=tok2)
assert s == 404, f"Expected 404, got {s}. Server response: {response_body}"