lab4: S3, MinIO, reconciler, трек 2, README
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
|
||||
DATABASE_URL = os.getenv(
|
||||
"DATABASE_URL",
|
||||
"postgresql+asyncpg://messenger:messenger_password@db:5432/messenger_db",
|
||||
)
|
||||
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
CODE_MAP = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
500: "internal_error",
|
||||
}
|
||||
|
||||
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://minio:9000")
|
||||
S3_REGION = os.getenv("S3_REGION", "us-east-1")
|
||||
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
S3_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY_ID", "minioadmin")
|
||||
S3_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_ACCESS_KEY", "minioadmin")
|
||||
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
from app.config import DATABASE_URL
|
||||
|
||||
engine = create_async_engine(
|
||||
DATABASE_URL,
|
||||
pool_size=5,
|
||||
max_overflow=10,
|
||||
pool_timeout=30,
|
||||
pool_recycle=1800,
|
||||
echo=False,
|
||||
)
|
||||
|
||||
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
||||
@@ -0,0 +1,6 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.database import async_session_maker
|
||||
|
||||
async def get_session():
|
||||
async with async_session_maker() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,37 @@
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from app.config import CODE_MAP
|
||||
|
||||
|
||||
def error_response(request: Request, status_code: int, code: str, message: str, extra_headers: dict = None):
|
||||
request_id = getattr(request.state, "request_id", "unknown")
|
||||
|
||||
|
||||
headers = {"X-Request-Id": request_id}
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
code = CODE_MAP.get(exc.status_code, "internal_error")
|
||||
return error_response(request, exc.status_code, code, str(exc.detail), extra_headers=exc.headers)
|
||||
|
||||
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "Ошибка валидации данных")
|
||||
|
||||
async def internal_error_handler(request: Request, exc: Exception):
|
||||
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi import HTTPException
|
||||
import uuid
|
||||
from app.middleware import RequestIdMiddleware
|
||||
from app.exceptions import http_exception_handler, validation_exception_handler
|
||||
from app.routers import health, users, chats, messages, auth, attachments
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger",
|
||||
version="1.1.0",
|
||||
)
|
||||
|
||||
INSTANCE_ID = str(uuid.uuid4())
|
||||
@app.middleware("http")
|
||||
async def add_instance_id_header(request, call_next):
|
||||
response = await call_next(request)
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
app.add_exception_handler(HTTPException, http_exception_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(attachments.router_upload)
|
||||
app.include_router(attachments.router_download)
|
||||
@@ -0,0 +1,11 @@
|
||||
import uuid as uuid_lib
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request, call_next):
|
||||
request_id = str(uuid_lib.uuid4())
|
||||
request.state.request_id = request_id
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
@@ -0,0 +1,19 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from sqlalchemy import String, Integer, ForeignKey, DateTime, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Attachment(Base):
|
||||
__tablename__ = "attachments"
|
||||
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
|
||||
object_key: Mapped[str] = mapped_column(String, unique=True)
|
||||
filename: Mapped[str] = mapped_column(String)
|
||||
mime_type: Mapped[str] = mapped_column(String)
|
||||
size_bytes: Mapped[int] = mapped_column(Integer)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("chats.id"))
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
sha256: Mapped[str] = mapped_column(String, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
@@ -0,0 +1,4 @@
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
@@ -0,0 +1,35 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import String, DateTime, ForeignKey, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||
)
|
||||
title: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("chats.id", ondelete="CASCADE"),
|
||||
primary_key=True,
|
||||
)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("users.id", ondelete="CASCADE"),
|
||||
primary_key=True,
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Text, DateTime, ForeignKey, Index, func, JSON
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
|
||||
attachment_ids: Mapped[list] = mapped_column(JSON, default=list)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||
)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("chats.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
sender_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("users.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
text: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import String, DateTime, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.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(String(255), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
def paginate(items: list, limit: int, cursor: str | None):
|
||||
start = 0
|
||||
if cursor is not None:
|
||||
try:
|
||||
start = int(cursor)
|
||||
except ValueError:
|
||||
start = 0
|
||||
|
||||
if start < 0:
|
||||
start = 0
|
||||
|
||||
page = items[start : start + limit]
|
||||
next_index = start + limit
|
||||
|
||||
if next_index < len(items):
|
||||
next_cursor = str(next_index)
|
||||
else:
|
||||
next_cursor = None
|
||||
|
||||
return page, next_cursor
|
||||
@@ -0,0 +1,9 @@
|
||||
import redis.asyncio as redis
|
||||
from app.config import REDIS_URL
|
||||
|
||||
redis_client = redis.from_url(
|
||||
REDIS_URL,
|
||||
decode_responses=True,
|
||||
socket_timeout=3,
|
||||
socket_connect_timeout=3,
|
||||
)
|
||||
@@ -0,0 +1,172 @@
|
||||
import uuid
|
||||
import filetype
|
||||
import io
|
||||
import hashlib
|
||||
from datetime import datetime, timezone
|
||||
from PIL import Image
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.dependencies import get_session
|
||||
from app.security import get_current_user
|
||||
from app.models.user import User
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.chat import ChatMember
|
||||
from app.storage import minio_client, BUCKET
|
||||
|
||||
router_upload = APIRouter(prefix="/api/v1/chats/{chat_id}/attachments", tags=["attachments"])
|
||||
router_download = APIRouter(prefix="/api/v1/attachments", tags=["attachments"])
|
||||
|
||||
MAX_SIZE = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
CHUNK_SIZE = 64 * 1024
|
||||
|
||||
|
||||
def build_attachment_response(att: Attachment) -> dict:
|
||||
now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
return {
|
||||
"id": str(att.id),
|
||||
"chat_id": str(att.chat_id),
|
||||
"owner_id": str(att.user_id),
|
||||
"filename": att.filename,
|
||||
"content_type": att.mime_type,
|
||||
"size_bytes": att.size_bytes,
|
||||
"sha256": att.sha256,
|
||||
"status": "ready",
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
|
||||
|
||||
@router_upload.post("", status_code=201)
|
||||
async def upload_attachment(
|
||||
chat_id: uuid.UUID,
|
||||
filename: str = Query(..., min_length=1, max_length=255, pattern=r"^[^/\\\x00]+$"),
|
||||
request: Request = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(
|
||||
ChatMember.chat_id == chat_id,
|
||||
ChatMember.user_id == user.id,
|
||||
)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(404, "Чат не найден")
|
||||
|
||||
sha_hasher = hashlib.sha256()
|
||||
buffer = io.BytesIO()
|
||||
total = 0
|
||||
first_bytes = b""
|
||||
|
||||
async for chunk in request.stream():
|
||||
if not chunk:
|
||||
continue
|
||||
total += len(chunk)
|
||||
if total > MAX_SIZE:
|
||||
raise HTTPException(413, "File too large")
|
||||
|
||||
sha_hasher.update(chunk)
|
||||
buffer.write(chunk)
|
||||
|
||||
if len(first_bytes) < 262:
|
||||
need = 262 - len(first_bytes)
|
||||
first_bytes += chunk[:need]
|
||||
|
||||
kind = filetype.guess(first_bytes)
|
||||
if not kind or kind.mime not in ("image/png", "image/jpeg"):
|
||||
raise HTTPException(400, "Only PNG/JPEG allowed")
|
||||
|
||||
contents = buffer.getvalue()
|
||||
try:
|
||||
img = Image.open(io.BytesIO(contents))
|
||||
if img.width * img.height > MAX_PIXELS:
|
||||
raise HTTPException(400, "Image too large (pixels)")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(400, "Corrupted image")
|
||||
|
||||
object_key = f"{uuid.uuid4()}.{kind.extension}"
|
||||
|
||||
minio_client.put_object(
|
||||
BUCKET,
|
||||
object_key,
|
||||
io.BytesIO(contents),
|
||||
len(contents),
|
||||
content_type=kind.mime,
|
||||
)
|
||||
|
||||
sha_hash = sha_hasher.hexdigest()
|
||||
att = Attachment(
|
||||
object_key=object_key,
|
||||
filename=filename,
|
||||
mime_type=kind.mime,
|
||||
size_bytes=len(contents),
|
||||
chat_id=chat_id,
|
||||
user_id=user.id,
|
||||
sha256=sha_hash,
|
||||
)
|
||||
session.add(att)
|
||||
await session.commit()
|
||||
await session.refresh(att)
|
||||
|
||||
return build_attachment_response(att)
|
||||
|
||||
|
||||
@router_download.get("/{attachment_id}/content")
|
||||
async def download_attachment_content(
|
||||
attachment_id: uuid.UUID,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
att = await session.get(Attachment, attachment_id)
|
||||
if not att:
|
||||
raise HTTPException(404, "Not found")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(
|
||||
ChatMember.chat_id == att.chat_id,
|
||||
ChatMember.user_id == user.id,
|
||||
)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(404, "Not found")
|
||||
|
||||
try:
|
||||
response = minio_client.get_object(BUCKET, att.object_key)
|
||||
return StreamingResponse(
|
||||
response,
|
||||
media_type=att.mime_type,
|
||||
headers={"Content-Disposition": f'attachment; filename="{att.filename}"'},
|
||||
)
|
||||
except Exception:
|
||||
raise HTTPException(404, "File not found in storage")
|
||||
|
||||
|
||||
@router_download.get("/{attachment_id}")
|
||||
async def get_attachment_metadata(
|
||||
attachment_id: uuid.UUID,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
att = await session.get(Attachment, attachment_id)
|
||||
if not att:
|
||||
raise HTTPException(404, "Not found")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(
|
||||
ChatMember.chat_id == att.chat_id,
|
||||
ChatMember.user_id == user.id,
|
||||
)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(404, "Not found")
|
||||
|
||||
return build_attachment_response(att)
|
||||
@@ -0,0 +1,84 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPAuthorizationCredentials
|
||||
from pydantic import BaseModel, ConfigDict, field_serializer
|
||||
from app.redis_client import redis_client
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app.database import async_session_maker
|
||||
from app.models.user import User
|
||||
from app.security import verify_password, create_session, delete_session, bearer_scheme
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
security = HTTPBasic(realm="messenger")
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@field_serializer('created_at')
|
||||
def serialize_dt(self, dt: datetime):
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: str
|
||||
user: UserResponse
|
||||
|
||||
@field_serializer('expires_at')
|
||||
def serialize_dt(self, dt_str: str):
|
||||
if dt_str and dt_str.endswith("+00:00"):
|
||||
return dt_str.replace("+00:00", "Z")
|
||||
return dt_str
|
||||
|
||||
|
||||
# Basic Auth в Bearer Token
|
||||
@router.post("/sessions", status_code=201, response_model=SessionResponse)
|
||||
async def login(credentials: HTTPBasicCredentials = Depends(security)):
|
||||
async with async_session_maker() as session:
|
||||
result = await session.execute(select(User).where(User.username == credentials.username))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if not user or not verify_password(credentials.password, user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||
)
|
||||
|
||||
session_data = await create_session(user.id)
|
||||
|
||||
session_data["user"] = user
|
||||
|
||||
return session_data
|
||||
|
||||
@router.delete("/sessions/current", status_code=204)
|
||||
async def logout(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
user_id = await redis_client.get(f"session:{token}")
|
||||
if not user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
await delete_session(token)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field, field_validator, ConfigDict, field_serializer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.models.chat import Chat, ChatMember
|
||||
from app.models.user import User
|
||||
from app.security import get_current_user
|
||||
from app.dependencies import get_session
|
||||
from app.pagination import paginate
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def unique_members(cls, v):
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("member_ids должны быть уникальными")
|
||||
return v
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
title: str
|
||||
member_ids: list[uuid.UUID]
|
||||
created_at: datetime
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@field_serializer('created_at')
|
||||
def serialize_dt(self, dt: datetime):
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_chat(
|
||||
payload: CreateChat,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if str(user.id) not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="Пользователь должен быть участником чата")
|
||||
|
||||
for member_id in payload.member_ids:
|
||||
result = await session.execute(select(User).where(User.id == member_id))
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=400, detail=f"несуществующий пользователь: {member_id}")
|
||||
|
||||
chat = Chat(title=payload.title)
|
||||
session.add(chat)
|
||||
await session.flush()
|
||||
|
||||
for member_id in payload.member_ids:
|
||||
session.add(ChatMember(chat_id=chat.id, user_id=member_id))
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(chat)
|
||||
|
||||
return {
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": payload.member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{chat_id}")
|
||||
async def get_chat(
|
||||
chat_id: str,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
result = await session.execute(select(Chat).where(Chat.id == chat_id))
|
||||
chat = result.scalar_one_or_none()
|
||||
|
||||
if not chat:
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user.id)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))
|
||||
member_ids = []
|
||||
for row in result.all():
|
||||
user_id = row[0]
|
||||
member_ids.append(str(user_id))
|
||||
|
||||
return {
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_chats(
|
||||
limit: int = 20,
|
||||
cursor: str | None = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100")
|
||||
|
||||
result = await session.execute(
|
||||
select(Chat)
|
||||
.join(ChatMember, Chat.id == ChatMember.chat_id)
|
||||
.where(ChatMember.user_id == user.id)
|
||||
.order_by(Chat.created_at, Chat.id)
|
||||
)
|
||||
chats = result.scalars().all()
|
||||
|
||||
my_chats = []
|
||||
for chat in chats:
|
||||
result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))
|
||||
member_ids = []
|
||||
for row in result.all():
|
||||
user_id = row[0]
|
||||
member_ids.append(str(user_id))
|
||||
|
||||
my_chats.append({
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
})
|
||||
|
||||
page, next_cursor = paginate(my_chats, limit, cursor)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,34 @@
|
||||
from fastapi import APIRouter
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import text
|
||||
from app.database import async_session_maker
|
||||
from app.redis_client import redis_client
|
||||
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
async def ready():
|
||||
try:
|
||||
async with async_session_maker() as session:
|
||||
await session.execute(text("SELECT 1"))
|
||||
|
||||
await redis_client.ping()
|
||||
|
||||
return {"status": "ok"}
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
|
||||
@router.get("/")
|
||||
def home():
|
||||
return {
|
||||
"service": "MTUSI Messenger",
|
||||
"version": "1.1.0",
|
||||
"docs": "/docs",
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends, Header
|
||||
from pydantic import BaseModel, Field, ConfigDict, field_serializer, model_validator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from app.redis_client import redis_client
|
||||
import json
|
||||
|
||||
from app.models.message import Message
|
||||
from app.models.chat import Chat, ChatMember
|
||||
from app.models.user import User
|
||||
from app.models.attachment import Attachment
|
||||
from app.security import get_current_user
|
||||
from app.dependencies import get_session
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(min_length=0, max_length=4000)
|
||||
attachment_ids: list[uuid.UUID] = []
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_text_or_attachment(self):
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError("Сообщение должно содержать текст или вложение")
|
||||
return self
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
attachment_ids: list[uuid.UUID] = []
|
||||
|
||||
@field_serializer('created_at')
|
||||
def serialize_dt(self, dt: datetime):
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
async def check_chat_access(chat_id: str, user_id: uuid.UUID, session: AsyncSession):
|
||||
chat = await session.get(Chat, chat_id)
|
||||
if not chat:
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user_id)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
return chat
|
||||
|
||||
|
||||
@router.post("", status_code=201, response_model=MessageResponse)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
payload: CreateMessage,
|
||||
idempotency_key: str = Header(
|
||||
...,
|
||||
alias="Idempotency-Key",
|
||||
min_length=1,
|
||||
max_length=128,
|
||||
pattern=r"^[A-Za-z0-9._:-]+$",
|
||||
),
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
await check_chat_access(chat_id, user.id, session)
|
||||
|
||||
if payload.attachment_ids:
|
||||
result = await session.execute(
|
||||
select(Attachment.id).where(
|
||||
Attachment.id.in_(payload.attachment_ids),
|
||||
Attachment.chat_id == chat_id,
|
||||
)
|
||||
)
|
||||
found_ids = {str(row[0]) for row in result.all()}
|
||||
requested_ids = {str(a) for a in payload.attachment_ids}
|
||||
if found_ids != requested_ids:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="attachment_ids содержат файлы из другого чата или несуществующие"
|
||||
)
|
||||
|
||||
redis_key = f"idem:{user.id}:{chat_id}:{idempotency_key}"
|
||||
body = payload.model_dump(mode="json")
|
||||
|
||||
raw = await redis_client.get(redis_key)
|
||||
if raw:
|
||||
stored = json.loads(raw)
|
||||
if stored["state"] == "done":
|
||||
if stored["request_body"] == body:
|
||||
return stored["response"]
|
||||
raise HTTPException(status_code=409, detail="Idempotency-Key переиспользован с другим телом запроса")
|
||||
raise HTTPException(status_code=409, detail="Запрос с этим Idempotency-Key ещё обрабатывается")
|
||||
|
||||
acquired = await redis_client.set(
|
||||
redis_key,
|
||||
json.dumps({"state": "processing", "request_body": body}),
|
||||
nx=True,
|
||||
ex=86400,
|
||||
)
|
||||
if not acquired:
|
||||
raise HTTPException(409, "Одновременный запрос с тем же самым Idempotency-Key")
|
||||
|
||||
message = Message(
|
||||
chat_id=chat_id,
|
||||
sender_id=user.id,
|
||||
text=payload.text,
|
||||
attachment_ids=[str(a) for a in payload.attachment_ids]
|
||||
)
|
||||
session.add(message)
|
||||
await session.commit()
|
||||
await session.refresh(message)
|
||||
|
||||
response_data = {
|
||||
"id": str(message.id),
|
||||
"chat_id": str(message.chat_id),
|
||||
"sender_id": str(message.sender_id),
|
||||
"text": message.text,
|
||||
"created_at": message.created_at.isoformat().replace("+00:00", "Z"),
|
||||
"attachment_ids": message.attachment_ids,
|
||||
}
|
||||
|
||||
await redis_client.set(
|
||||
redis_key,
|
||||
json.dumps({"state": "done",
|
||||
"request_body": body,
|
||||
"response": response_data}),
|
||||
ex=86400,
|
||||
)
|
||||
|
||||
return response_data
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100")
|
||||
|
||||
await check_chat_access(chat_id, user.id, session)
|
||||
|
||||
offset = int(cursor) if cursor else 0
|
||||
|
||||
result = await session.execute(
|
||||
select(Message)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id)
|
||||
.limit(limit + 1)
|
||||
.offset(offset)
|
||||
)
|
||||
msgs = result.scalars().all()
|
||||
|
||||
has_next = len(msgs) > limit
|
||||
if has_next:
|
||||
msgs = msgs[:limit]
|
||||
|
||||
my_messages = [
|
||||
{
|
||||
"id": m.id,
|
||||
"chat_id": m.chat_id,
|
||||
"sender_id": m.sender_id,
|
||||
"text": m.text,
|
||||
"created_at": m.created_at.isoformat().replace("+00:00", "Z"),
|
||||
"attachment_ids": m.attachment_ids,
|
||||
} for m in msgs
|
||||
]
|
||||
|
||||
next_cursor = str(offset + limit) if has_next else None
|
||||
return {"items": my_messages, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,55 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field, ConfigDict, field_serializer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from app.models.user import User
|
||||
from app.security import get_password_hash, get_current_user
|
||||
from app.dependencies import get_session
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=5, max_length=128)
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@field_serializer('created_at')
|
||||
def serialize_dt(self, dt: datetime):
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
@router.post("", status_code=201, response_model=UserResponse)
|
||||
async def register_user(payload: CreateUser, session: AsyncSession = Depends(get_session)):
|
||||
result = await session.execute(select(User).where(User.username == payload.username))
|
||||
if result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=409, detail="Имя пользователя уже существует")
|
||||
|
||||
user = User(
|
||||
username=payload.username,
|
||||
display_name=payload.display_name,
|
||||
password_hash=get_password_hash(payload.password)
|
||||
)
|
||||
session.add(user)
|
||||
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError:
|
||||
await session.rollback()
|
||||
raise HTTPException(status_code=409, detail="Имя пользователя уже существует")
|
||||
|
||||
await session.refresh(user)
|
||||
return user
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
async def current_user(user: User = Depends(get_current_user)):
|
||||
return user
|
||||
@@ -0,0 +1,81 @@
|
||||
import secrets
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from passlib.context import CryptContext
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy import select
|
||||
from app.database import async_session_maker
|
||||
from app.models.user import User
|
||||
from app.redis_client import redis_client
|
||||
from app.config import SESSION_TTL_SECONDS
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
async def create_session(user_id: str) -> dict:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
|
||||
await redis_client.setex(
|
||||
name=f"session:{token}",
|
||||
time=SESSION_TTL_SECONDS,
|
||||
value=str(user_id),
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
async def delete_session(token: str) -> None:
|
||||
await redis_client.delete(f"session:{token}")
|
||||
|
||||
|
||||
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
|
||||
try:
|
||||
user_id = await redis_client.get(f"session:{token}")
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Внутренняя ошибка сервера"
|
||||
)
|
||||
|
||||
if not user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
async with async_session_maker() as session:
|
||||
result = await session.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
return user
|
||||
@@ -0,0 +1,22 @@
|
||||
import threading
|
||||
from minio import Minio
|
||||
from app.config import S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_BUCKET
|
||||
|
||||
users_lock = threading.Lock()
|
||||
messages_lock = threading.Lock()
|
||||
|
||||
users_by_id: dict[str, dict] = {}
|
||||
users_by_username: dict[str, dict] = {}
|
||||
chats_by_id: dict[str, dict] = {}
|
||||
messages_by_chat: dict[str, list[dict]] = {}
|
||||
|
||||
endpoint = S3_ENDPOINT.replace("http://", "").replace("https://", "")
|
||||
|
||||
minio_client = Minio(
|
||||
endpoint,
|
||||
access_key=S3_ACCESS_KEY_ID,
|
||||
secret_key=S3_SECRET_ACCESS_KEY,
|
||||
secure=False,
|
||||
)
|
||||
|
||||
BUCKET = S3_BUCKET
|
||||
Reference in New Issue
Block a user