10 Commits
9 changed files with 320 additions and 33 deletions
+4 -1
View File
@@ -15,4 +15,7 @@ MINIO_ROOT_PASSWORD=minioadmin
S3_ENDPOINT=http://minio:9000 S3_ENDPOINT=http://minio:9000
S3_ACCESS_KEY=minioadmin S3_ACCESS_KEY=minioadmin
S3_SECRET_KEY=minioadmin S3_SECRET_KEY=minioadmin
S3_BUCKET=attachments S3_BUCKET=attachments
RABBITMQ_USER=guest
RABBITMQ_PASSWORD=guest
+50 -15
View File
@@ -1,10 +1,10 @@
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 from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PG_UUID 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 sqlalchemy import UniqueConstraint
from .base import Base from .base import Base
@@ -99,37 +99,72 @@ class SessionRow(Base):
DateTime(timezone=True), default=_now, nullable=False DateTime(timezone=True), default=_now, nullable=False
) )
from sqlalchemy import UniqueConstraint
class IdempotencyRecord(Base): class IdempotencyRecord(Base):
__tablename__ = "idempotency_keys" __tablename__ = "idempotency_keys"
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4) id: Mapped[UUID] = mapped_column(
user_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False) 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) 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(DateTime(timezone=True), default=_now, nullable=False) created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, nullable=False
)
__table_args__ = ( __table_args__ = (
UniqueConstraint("user_id", "key", name="uq_idempotency_user_key"), UniqueConstraint("user_id", "key", name="uq_idempotency_user_key"),
) )
class Attachment(Base): class Attachment(Base):
__tablename__ = "attachments" __tablename__ = "attachments"
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4) id: Mapped[UUID] = mapped_column(
chat_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False) PG_UUID(as_uuid=True), primary_key=True, default=uuid4
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)
status: Mapped[str] = mapped_column(String(20), default="ready", nullable=False)
# ИЗМЕНЕНО: по умолчанию "queued", так как теперь обработка асинхронная
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)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), 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
)
class MessageAttachment(Base): class MessageAttachment(Base):
__tablename__ = "message_attachments" __tablename__ = "message_attachments"
message_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True) message_id: Mapped[UUID] = mapped_column(
attachment_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("attachments.id", ondelete="CASCADE"), primary_key=True) 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
)
+35 -9
View File
@@ -18,8 +18,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.base import BaseHTTPMiddleware
from .auth import ( from .auth import (
SESSION_TTL, create_session, get_current_user, SESSION_TTL, create_session, get_current_user, hash_password,
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
from .db.session import get_db from .db.session import get_db
@@ -29,6 +29,7 @@ from .repositories import messages as messages_repo
from .repositories import users as users_repo from .repositories import users as users_repo
from .s3_client import s3, BUCKET, ensure_bucket from .s3_client import s3, BUCKET, ensure_bucket
from .image_utils import validate_image from .image_utils import validate_image
from .queue import publish_task
INSTANCE_ID = os.environ.get("HOSTNAME", f"api-{socket.gethostname()}") INSTANCE_ID = os.environ.get("HOSTNAME", f"api-{socket.gethostname()}")
request_id_var: ContextVar[str] = ContextVar("request_id", default="") request_id_var: ContextVar[str] = ContextVar("request_id", default="")
@@ -53,7 +54,7 @@ class RequestIdMiddleware(BaseHTTPMiddleware):
response.headers["X-Instance-Id"] = INSTANCE_ID response.headers["X-Instance-Id"] = INSTANCE_ID
return response return response
app = FastAPI(title="MTUSI Messenger — lab4") app = FastAPI(title="MTUSI Messenger — lab5")
app.add_middleware(RequestIdMiddleware) app.add_middleware(RequestIdMiddleware)
security = HTTPBasic(auto_error=False) security = HTTPBasic(auto_error=False)
@@ -100,7 +101,7 @@ def _attachment_json(att: Attachment) -> dict:
"id": str(att.id), "chat_id": str(att.chat_id), "owner_id": str(att.owner_id), "id": str(att.id), "chat_id": str(att.chat_id), "owner_id": str(att.owner_id),
"filename": att.filename, "content_type": att.content_type, "size_bytes": att.size_bytes, "filename": att.filename, "content_type": att.content_type, "size_bytes": att.size_bytes,
"sha256": att.sha256, "status": att.status, "error_code": att.error_code, "sha256": att.sha256, "status": att.status, "error_code": att.error_code,
"variants": [], "variants": att.variants or [],
"created_at": _iso_z(att.created_at), "created_at": _iso_z(att.created_at),
"updated_at": _iso_z(att.updated_at), "updated_at": _iso_z(att.updated_at),
} }
@@ -238,7 +239,7 @@ async def list_messages(chat_id: UUID, user: User = Depends(get_current_user), l
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
return {"items": items, "next_cursor": nxt} return {"items": items, "next_cursor": nxt}
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201) @app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
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)): 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) 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")
@@ -252,10 +253,19 @@ async def upload_attachment(chat_id: UUID, request: Request, filename: str = Que
s3.put_object(Bucket=BUCKET, Key=s3_key, Body=content, ContentType=mime) s3.put_object(Bucket=BUCKET, Key=s3_key, Body=content, ContentType=mime)
att = Attachment(chat_id=chat_id, owner_id=user.id, filename=filename, content_type=mime, size_bytes=len(content), sha256=sha256, status="ready", 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.commit()
await db.refresh(att) await db.refresh(att)
# отправляем задачу в rabbitmq
publish_task({
"attachment_id": str(att.id),
"chat_id": str(chat_id),
"s3_key": s3_key,
"mime": mime,
})
return _attachment_json(att) return _attachment_json(att)
@app.get("/api/v1/attachments/{attachment_id}") @app.get("/api/v1/attachments/{attachment_id}")
@@ -267,15 +277,31 @@ async def get_attachment(attachment_id: UUID, user: User = Depends(get_current_u
return _attachment_json(att) return _attachment_json(att)
@app.get("/api/v1/attachments/{attachment_id}/content") @app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(attachment_id: UUID, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): async def download_attachment(attachment_id: UUID, variant: str = Query("original"), user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
att = await db.get(Attachment, attachment_id) att = await db.get(Attachment, attachment_id)
if not att: raise HTTPException(404, "Attachment not found") if not att: raise HTTPException(404, "Attachment not found")
chat = await chats_repo.get_if_member(db, att.chat_id, user.id) chat = await chats_repo.get_if_member(db, att.chat_id, user.id)
if not chat: raise HTTPException(404, "Attachment not found") if not chat: raise HTTPException(404, "Attachment not found")
obj = s3.get_object(Bucket=BUCKET, Key=att.s3_key) if att.status != "ready":
raise HTTPException(409, "Attachment not ready")
key = att.s3_key
mime = att.content_type
if variant == "thumbnail":
key = f"{att.s3_key}_thumb.jpg"
mime = "image/jpeg"
elif variant == "crop":
key = f"{att.s3_key}_crop.jpg"
mime = "image/jpeg"
elif variant == "optimized":
key = f"{att.s3_key}_opt.webp"
mime = "image/webp"
obj = s3.get_object(Bucket=BUCKET, Key=key)
content = obj["Body"].read() content = obj["Body"].read()
return Response(content=content, media_type=att.content_type) return Response(content=content, media_type=mime)
if __name__ == "__main__": if __name__ == "__main__":
import uvicorn import uvicorn
+3 -7
View File
@@ -10,8 +10,7 @@ class CreateUser(BaseModel):
@field_validator("display_name", "password") @field_validator("display_name", "password")
@classmethod @classmethod
def _not_blank(cls, v: str) -> str: def _not_blank(cls, v: str) -> str:
if not v.strip(): if not v.strip(): raise ValueError("must not be blank")
raise ValueError("must not be blank")
return v return v
class CreateChat(BaseModel): class CreateChat(BaseModel):
@@ -22,20 +21,17 @@ class CreateChat(BaseModel):
@field_validator("title") @field_validator("title")
@classmethod @classmethod
def _title_not_blank(cls, v: str) -> str: def _title_not_blank(cls, v: str) -> str:
if not v.strip(): if not v.strip(): raise ValueError("title must not be blank")
raise ValueError("title must not be blank")
return v return v
@field_validator("member_ids") @field_validator("member_ids")
@classmethod @classmethod
def _unique_members(cls, v: list[UUID]) -> list[UUID]: def _unique_members(cls, v: list[UUID]) -> list[UUID]:
if len(set(v)) != len(v): if len(set(v)) != len(v): raise ValueError("duplicate member_ids")
raise ValueError("duplicate member_ids")
return v return v
class CreateMessage(BaseModel): class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid") model_config = ConfigDict(extra="forbid")
# min_length=0 разрешает пустой текст, если прикреплен файл
text: str = Field(min_length=0, max_length=4000) text: str = Field(min_length=0, max_length=4000)
attachment_ids: list[UUID] | None = None attachment_ids: list[UUID] | None = None
+18
View File
@@ -0,0 +1,18 @@
import pika
import os
import json
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/")
QUEUE_NAME = "attachment_tasks"
def publish_task(task: dict):
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
channel = connection.channel()
channel.queue_declare(queue=QUEUE_NAME, durable=True)
channel.basic_publish(
exchange="",
routing_key=QUEUE_NAME,
body=json.dumps(task),
properties=pika.BasicProperties(delivery_mode=2),
)
connection.close()
+131
View File
@@ -0,0 +1,131 @@
import asyncio
import json
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
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 att.status == "ready" and len(att.variants or []) == 3:
return
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 = []
# 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()
})
# 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 = "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)
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)
def main():
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
channel = connection.channel()
channel.queue_declare(queue=QUEUE_NAME, durable=True)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=QUEUE_NAME, on_message_callback=callback)
print("Worker started, waiting for messages...", flush=True)
channel.start_consuming()
if __name__ == "__main__":
main()
+47
View File
@@ -43,6 +43,20 @@ services:
timeout: 5s timeout: 5s
retries: 10 retries: 10
rabbitmq:
image: rabbitmq:3.13-management-alpine
environment:
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD}
ports:
- "127.0.0.1:5672:5672"
- "127.0.0.1:15672:15672"
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "check_port_connectivity"]
interval: 5s
timeout: 5s
retries: 10
migrator: migrator:
build: . build: .
command: alembic upgrade head command: alembic upgrade head
@@ -62,6 +76,7 @@ services:
S3_ACCESS_KEY: ${S3_ACCESS_KEY} S3_ACCESS_KEY: ${S3_ACCESS_KEY}
S3_SECRET_KEY: ${S3_SECRET_KEY} S3_SECRET_KEY: ${S3_SECRET_KEY}
S3_BUCKET: ${S3_BUCKET} S3_BUCKET: ${S3_BUCKET}
RABBITMQ_URL: amqp://${RABBITMQ_USER}:${RABBITMQ_PASSWORD}@rabbitmq:5672/
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
@@ -69,8 +84,40 @@ services:
condition: service_healthy condition: service_healthy
minio: minio:
condition: service_healthy condition: service_healthy
rabbitmq:
condition: service_healthy
migrator: migrator:
condition: service_completed_successfully condition: service_completed_successfully
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
worker:
build: .
command: python -m app.worker
environment:
DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}
S3_ENDPOINT: ${S3_ENDPOINT}
S3_ACCESS_KEY: ${S3_ACCESS_KEY}
S3_SECRET_KEY: ${S3_SECRET_KEY}
S3_BUCKET: ${S3_BUCKET}
RABBITMQ_URL: amqp://${RABBITMQ_USER}:${RABBITMQ_PASSWORD}@rabbitmq:5672/
depends_on:
postgres:
condition: service_healthy
minio:
condition: service_healthy
rabbitmq:
condition: service_healthy
migrator:
condition: service_completed_successfully
deploy:
resources:
limits:
cpus: '1.0'
memory: 1G
nginx: nginx:
image: nginx:1.25-alpine image: nginx:1.25-alpine
@@ -0,0 +1,30 @@
"""add variants to attachments
Revision ID: d15635c49e1a
Revises: 133990c80d19
Create Date: 2026-11-11 21:38:16.802941
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = 'd15635c49e1a'
down_revision: Union[str, None] = '133990c80d19'
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.add_column('attachments', sa.Column('variants', postgresql.JSONB(astext_type=sa.Text()), nullable=False))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('attachments', 'variants')
# ### end Alembic commands ###
+2 -1
View File
@@ -11,4 +11,5 @@ httpx==0.27.0
pytest==8.1.1 pytest==8.1.1
pytest-asyncio==0.23.5 pytest-asyncio==0.23.5
boto3==1.34.0 boto3==1.34.0
Pillow==10.2.0 Pillow==10.2.0
pika==1.3.2