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 uuid import UUID, uuid4
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PG_UUID, JSONB
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
def _now() -> datetime:
return datetime.now(timezone.utc)
class User(Base):
__tablename__ = "users"
id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True), primary_key=True, default=uuid4
)
username: Mapped[str] = mapped_column(
String(32), unique=True, nullable=False, index=True
)
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
username: Mapped[str] = mapped_column(String(32), unique=True, nullable=False, index=True)
display_name: Mapped[str] = mapped_column(String(100), nullable=False)
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, nullable=False
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
class Chat(Base):
__tablename__ = "chats"
id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True), primary_key=True, default=uuid4
)
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
title: Mapped[str] = mapped_column(String(100), nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, nullable=False
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
__table_args__ = (Index("idx_chats_created_id", "created_at", "id"),)
class ChatMember(Base):
__tablename__ = "chat_members"
chat_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=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,
)
chat_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=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"),)
class Message(Base):
__tablename__ = "messages"
id: Mapped[UUID] = mapped_column(
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
)
id: Mapped[UUID] = mapped_column(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)
text: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, nullable=False
)
__table_args__ = (
Index("idx_messages_chat_created_id", "chat_id", "created_at", "id"),
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
__table_args__ = (Index("idx_messages_chat_created_id", "chat_id", "created_at", "id"),)
class SessionRow(Base):
__tablename__ = "sessions"
id: Mapped[UUID] = mapped_column(
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
)
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
)
id: Mapped[UUID] = mapped_column(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)
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):
__tablename__ = "idempotency_keys"
id: Mapped[UUID] = mapped_column(
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
)
id: Mapped[UUID] = mapped_column(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)
key: Mapped[str] = mapped_column(String(128), nullable=False)
request_hash: Mapped[str] = mapped_column(String(64), nullable=False)
response_body: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, nullable=False
)
__table_args__ = (
UniqueConstraint("user_id", "key", name="uq_idempotency_user_key"),
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
__table_args__ = (UniqueConstraint("user_id", "key", name="uq_idempotency_user_key"),)
class Attachment(Base):
__tablename__ = "attachments"
id: Mapped[UUID] = mapped_column(
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
)
id: Mapped[UUID] = mapped_column(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)
filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[str] = mapped_column(String(100), nullable=False)
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
# ИЗМЕНЕНО: по умолчанию "queued", так как теперь обработка асинхронная
status: Mapped[str] = mapped_column(String(20), default="queued", nullable=False)
error_code: Mapped[str] = mapped_column(String(50), nullable=True)
s3_key: Mapped[str] = mapped_column(String(500), 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
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, onupdate=_now, nullable=False
)
created_at: Mapped[datetime] = mapped_column(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):
__tablename__ = "message_attachments"
message_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey("messages.id", ondelete="CASCADE"),
primary_key=True
)
attachment_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey("attachments.id", ondelete="CASCADE"),
primary_key=True
)
message_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True)
attachment_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("attachments.id", ondelete="CASCADE"), primary_key=True)
class Outbox(Base):
__tablename__ = "outbox"
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
payload: Mapped[str] = mapped_column(Text, nullable=False)
status: Mapped[str] = mapped_column(String(20), default="pending", nullable=False, index=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
+57 -16
View File
@@ -3,6 +3,7 @@ import socket
import uuid
import hashlib
import json
import asyncio
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from typing import Optional
@@ -16,13 +17,14 @@ from sqlalchemy import select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.concurrency import run_in_threadpool
from .auth import (
SESSION_TTL, create_session, get_current_user, hash_password,
revoke_current_session, verify_password,
)
from .db.models import IdempotencyRecord, User, Attachment, MessageAttachment
from .db.session import get_db
from .db.models import IdempotencyRecord, User, Attachment, MessageAttachment, Outbox
from .db.session import get_db, async_session
from .models import CreateChat, CreateMessage, CreateUser
from .repositories import chats as chats_repo
from .repositories import messages as messages_repo
@@ -40,6 +42,25 @@ _HTTP_CODES = {
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:
resp = JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id_var.get()}})
resp.headers["X-Instance-Id"] = INSTANCE_ID
@@ -59,8 +80,10 @@ app.add_middleware(RequestIdMiddleware)
security = HTTPBasic(auto_error=False)
@app.on_event("startup")
def startup_event():
async def startup_event():
ensure_bucket()
# Запускаем фоновую задачу для отправки сообщений из БД в RabbitMQ
asyncio.create_task(outbox_publisher())
@app.exception_handler(RequestValidationError)
async def _validation(request: Request, exc: RequestValidationError):
@@ -243,6 +266,9 @@ async def list_messages(chat_id: UUID, user: User = Depends(get_current_user), l
async def upload_attachment(chat_id: UUID, request: Request, filename: str = Query(..., min_length=1, max_length=255), user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
chat = await chats_repo.get_if_member(db, chat_id, user.id)
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()
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"
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)
db.add(att)
await db.commit()
await db.refresh(att)
# отправляем задачу в rabbitmq
publish_task({
"attachment_id": str(att.id),
"chat_id": str(chat_id),
"s3_key": s3_key,
"mime": mime,
})
try:
# Получаем ID вложения без коммита
await db.flush()
# Создаем задачу в Outbox
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)
@@ -299,8 +336,12 @@ async def download_attachment(attachment_id: UUID, variant: str = Query("origina
key = f"{att.s3_key}_opt.webp"
mime = "image/webp"
obj = s3.get_object(Bucket=BUCKET, Key=key)
content = obj["Body"].read()
try:
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)
if __name__ == "__main__":
+18 -1
View File
@@ -4,11 +4,28 @@ import json
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/")
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):
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
channel = connection.channel()
channel.queue_declare(queue=QUEUE_NAME, durable=True)
setup_rabbitmq(channel)
channel.basic_publish(
exchange="",
routing_key=QUEUE_NAME,
+60 -83
View File
@@ -4,127 +4,104 @@ import os
import io
import hashlib
from datetime import datetime, timezone
import pika
from PIL import Image, ImageOps
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy.pool import NullPool
from .db.models import Attachment
from .s3_client import s3, BUCKET
from .queue import RABBITMQ_URL, QUEUE_NAME, setup_rabbitmq
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):
att_id = task["attachment_id"]
s3_key = task["s3_key"]
# ВАЖНО: создаем engine внутри функции с NullPool, чтобы избежать ошибки разных event loop
engine = create_async_engine(DATABASE_URL, poolclass=NullPool)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
try:
async with AsyncSessionLocal() as session:
att = await session.get(Attachment, att_id)
if not att:
return
if not att: return
if att.status == "ready" and len(att.variants or []) == 3: return
# идемпотентность: если уже обработано, пропускаем
if att.status == "ready" and len(att.variants or []) == 3:
return
obj = s3.get_object(Bucket=BUCKET, Key=s3_key)
content = obj["Body"].read()
img = Image.open(io.BytesIO(content))
img = ImageOps.exif_transpose(img)
if img.mode in ("RGBA", "LA"):
background = Image.new("RGB", img.size, (255, 255, 255))
background.paste(img, mask=img.split()[-1])
img = background
elif img.mode != "RGB":
img = img.convert("RGB")
try:
# получаем оригинал
obj = s3.get_object(Bucket=BUCKET, Key=s3_key)
content = obj["Body"].read()
img = Image.open(io.BytesIO(content))
# разворачиваем по exif и убираем прозрачность
img = ImageOps.exif_transpose(img)
if img.mode in ("RGBA", "LA"):
background = Image.new("RGB", img.size, (255, 255, 255))
background.paste(img, mask=img.split()[-1])
img = background
elif img.mode != "RGB":
img = img.convert("RGB")
variants_meta = []
thumb = img.copy()
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
thumb_bytes = io.BytesIO()
thumb.save(thumb_bytes, format="JPEG")
thumb_data = thumb_bytes.getvalue()
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_thumb.jpg", Body=thumb_data, ContentType="image/jpeg")
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)
thumb = img.copy()
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
thumb_bytes = io.BytesIO()
thumb.save(thumb_bytes, format="JPEG")
thumb_data = thumb_bytes.getvalue()
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_thumb.jpg", Body=thumb_data, ContentType="image/jpeg")
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()
})
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()})
# 2. Crop (128x128)
crop_img = img.copy()
width, height = crop_img.size
min_dim = min(width, height)
left = (width - min_dim) / 2
top = (height - min_dim) / 2
right = (width + min_dim) / 2
bottom = (height + min_dim) / 2
crop_img = crop_img.crop((left, top, right, bottom))
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 = "ready"
att.error_code = None
att.variants = variants_meta
att.updated_at = datetime.now(timezone.utc)
await session.commit()
except Exception as e:
async with AsyncSessionLocal() as session:
att = await session.get(Attachment, att_id)
if att:
att.status = "failed"
att.error_code = "processing_failed"
att.updated_at = datetime.now(timezone.utc)
await session.commit()
print(f"Error processing {att_id}: {e}", flush=True)
print(f"Error processing {att_id}: {e}", flush=True)
raise e
finally:
await engine.dispose()
def callback(ch, method, properties, body):
task = json.loads(body)
asyncio.run(process_attachment(task))
ch.basic_ack(delivery_tag=method.delivery_tag)
try:
# Таймаут 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():
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
channel = connection.channel()
channel.queue_declare(queue=QUEUE_NAME, durable=True)
setup_rabbitmq(channel)
channel.basic_qos(prefetch_count=1)
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()
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:
# ### 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 ###
+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}"