forked from mtusi2026/mtusi2026lab5
chore: copy lab4 solution (api, nginx, migrations, tests, s3)
This commit is contained in:
+85
@@ -0,0 +1,85 @@
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
import bcrypt
|
||||
from fastapi import Depends, Header, HTTPException
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from .db.models import SessionRow, User
|
||||
from .db.session import get_db
|
||||
|
||||
import redis.asyncio as redis
|
||||
|
||||
redis_client = redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0"))
|
||||
|
||||
SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
|
||||
def _prehash(password: str) -> bytes:
|
||||
# bcrypt работает с ≤72 байт, SHA-256 даёт 32 байта и снимает ограничение
|
||||
return hashlib.sha256(password.encode("utf-8")).hexdigest().encode("ascii")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(_prehash(password), bcrypt.gensalt(rounds=12)).decode("ascii")
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(_prehash(password), password_hash.encode("ascii"))
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def generate_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def _unauthorized_bearer() -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=401,
|
||||
detail="Unauthorized",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
|
||||
async def create_session(user_id: str) -> str:
|
||||
token = generate_token()
|
||||
await redis_client.setex(
|
||||
f"session:{hash_token(token)}", SESSION_TTL, str(user_id)
|
||||
)
|
||||
return token
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
authorization: str | None = Header(None, alias="Authorization"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise _unauthorized_bearer()
|
||||
token = authorization[7:]
|
||||
token_hash = hash_token(token)
|
||||
user_id_raw = await redis_client.get(f"session:{token_hash}")
|
||||
if user_id_raw is None:
|
||||
raise _unauthorized_bearer()
|
||||
user = await db.get(User, UUID(user_id_raw.decode()))
|
||||
if user is None:
|
||||
raise _unauthorized_bearer()
|
||||
return user
|
||||
|
||||
|
||||
async def revoke_current_session(authorization: str, db: AsyncSession) -> None:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise _unauthorized_bearer()
|
||||
token = authorization[7:]
|
||||
deleted = await redis_client.delete(f"session:{hash_token(token)}")
|
||||
if deleted == 0:
|
||||
raise _unauthorized_bearer()
|
||||
@@ -0,0 +1,5 @@
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
@@ -0,0 +1,135 @@
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text
|
||||
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy import UniqueConstraint
|
||||
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
|
||||
)
|
||||
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
|
||||
)
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
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
|
||||
)
|
||||
|
||||
__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,
|
||||
)
|
||||
|
||||
__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
|
||||
)
|
||||
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"),
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
from sqlalchemy import UniqueConstraint
|
||||
|
||||
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)
|
||||
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"),
|
||||
)
|
||||
|
||||
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)
|
||||
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)
|
||||
status: Mapped[str] = mapped_column(String(20), default="ready", nullable=False)
|
||||
error_code: Mapped[str] = mapped_column(String(50), nullable=True)
|
||||
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)
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,31 @@
|
||||
import os
|
||||
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
|
||||
DATABASE_URL = os.getenv(
|
||||
"DATABASE_URL",
|
||||
"postgresql+asyncpg://messenger:strongpassword@localhost:5432/messenger",
|
||||
)
|
||||
|
||||
engine = create_async_engine(
|
||||
DATABASE_URL,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
pool_timeout=5,
|
||||
pool_recycle=1800,
|
||||
pool_pre_ping=True,
|
||||
connect_args={"timeout": 5, "command_timeout": 10},
|
||||
)
|
||||
|
||||
async_session = async_sessionmaker(
|
||||
engine, class_=AsyncSession, expire_on_commit=False
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncSession:
|
||||
async with async_session() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,25 @@
|
||||
import io
|
||||
from PIL import Image
|
||||
from fastapi import HTTPException
|
||||
|
||||
MAX_SIZE = 10 * 1024 * 1024 # 10 мбайт
|
||||
MAX_PIXELS = 40_000_000
|
||||
|
||||
def validate_image(content: bytes) -> str:
|
||||
if len(content) > MAX_SIZE:
|
||||
raise HTTPException(413, "File too large")
|
||||
try:
|
||||
img = Image.open(io.BytesIO(content))
|
||||
img.verify()
|
||||
img = Image.open(io.BytesIO(content))
|
||||
except Exception:
|
||||
raise HTTPException(415, "Invalid image format")
|
||||
|
||||
if img.format not in ("PNG", "JPEG"):
|
||||
raise HTTPException(415, "Unsupported media type")
|
||||
|
||||
width, height = img.size
|
||||
if width * height > MAX_PIXELS:
|
||||
raise HTTPException(413, "Image too large in pixels")
|
||||
|
||||
return "image/png" if img.format == "PNG" else "image/jpeg"
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
import os
|
||||
import socket
|
||||
import uuid
|
||||
import hashlib
|
||||
import json
|
||||
from contextvars import ContextVar
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
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 .models import CreateChat, CreateMessage, CreateUser
|
||||
from .repositories import chats as chats_repo
|
||||
from .repositories import messages as messages_repo
|
||||
from .repositories import users as users_repo
|
||||
from .s3_client import s3, BUCKET, ensure_bucket
|
||||
from .image_utils import validate_image
|
||||
|
||||
INSTANCE_ID = os.environ.get("HOSTNAME", f"api-{socket.gethostname()}")
|
||||
request_id_var: ContextVar[str] = ContextVar("request_id", default="")
|
||||
|
||||
_HTTP_CODES = {
|
||||
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",
|
||||
}
|
||||
|
||||
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
|
||||
return resp
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request_id_var.set(rid)
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — lab4")
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
security = HTTPBasic(auto_error=False)
|
||||
|
||||
@app.on_event("startup")
|
||||
def startup_event():
|
||||
ensure_bucket()
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def _validation(request: Request, exc: RequestValidationError):
|
||||
return err_json(400, "invalid_request", "Validation error")
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def _http(request: Request, exc: HTTPException):
|
||||
code = _HTTP_CODES.get(exc.status_code, "internal_error")
|
||||
detail = exc.detail if isinstance(exc.detail, str) else "Error"
|
||||
resp = err_json(exc.status_code, code, detail)
|
||||
if exc.headers:
|
||||
for k, v in exc.headers.items():
|
||||
resp.headers[k] = v
|
||||
return resp
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def _generic(request: Request, exc: Exception):
|
||||
return err_json(500, "internal_error", "Internal server error")
|
||||
|
||||
def _iso_z(dt: datetime) -> str:
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
def _user_json(u: User) -> dict:
|
||||
return {"id": str(u.id), "username": u.username, "display_name": u.display_name, "created_at": _iso_z(u.created_at)}
|
||||
|
||||
def _chat_json(chat, member_ids: list[str]) -> dict:
|
||||
return {"id": str(chat.id), "title": chat.title, "member_ids": member_ids, "created_at": _iso_z(chat.created_at)}
|
||||
|
||||
def _msg_json(m, attachment_ids=None) -> dict:
|
||||
return {
|
||||
"id": str(m.id), "chat_id": str(m.chat_id), "sender_id": str(m.sender_id),
|
||||
"text": m.text, "created_at": _iso_z(m.created_at),
|
||||
"attachment_ids": [str(a) for a in (attachment_ids or [])]
|
||||
}
|
||||
|
||||
def _attachment_json(att: Attachment) -> dict:
|
||||
return {
|
||||
"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,
|
||||
"sha256": att.sha256, "status": att.status, "error_code": att.error_code,
|
||||
"variants": [],
|
||||
"created_at": _iso_z(att.created_at),
|
||||
"updated_at": _iso_z(att.updated_at),
|
||||
}
|
||||
|
||||
@app.get("/health/live")
|
||||
def live(): return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def ready(db: AsyncSession = Depends(get_db)):
|
||||
try: await db.execute(text("SELECT 1"))
|
||||
except Exception: return err_json(503, "unavailable", "Database unavailable")
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def register(body: CreateUser, db: AsyncSession = Depends(get_db)):
|
||||
existing = await users_repo.get_by_username(db, body.username)
|
||||
if existing is not None: raise HTTPException(409, "Username already exists")
|
||||
try:
|
||||
user = await users_repo.create(db, body.username, body.display_name, hash_password(body.password))
|
||||
except Exception: raise HTTPException(409, "Username already exists")
|
||||
return _user_json(user)
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
async def login(creds: Optional[HTTPBasicCredentials] = Depends(security), db: AsyncSession = Depends(get_db)):
|
||||
basic_challenge = 'Basic realm="messenger", charset="UTF-8"'
|
||||
if creds is None: raise HTTPException(401, "Unauthorized", headers={"WWW-Authenticate": basic_challenge})
|
||||
user = await users_repo.get_by_username(db, creds.username)
|
||||
if user is None or not verify_password(creds.password, user.password_hash):
|
||||
raise HTTPException(401, "Unauthorized", headers={"WWW-Authenticate": basic_challenge})
|
||||
expires = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)
|
||||
token = await create_session(str(user.id))
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": _iso_z(expires), "user": _user_json(user)}
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def logout(authorization: str = Header(...), db: AsyncSession = Depends(get_db)):
|
||||
await revoke_current_session(authorization, db)
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def me(user: User = Depends(get_current_user)):
|
||||
return _user_json(user)
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(body: CreateChat, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||
if user.id not in body.member_ids: raise HTTPException(400, "Caller must be in member_ids")
|
||||
try:
|
||||
chat = await chats_repo.create_atomic(db, body.title, body.member_ids)
|
||||
except ValueError: raise HTTPException(404, "Member not found")
|
||||
return _chat_json(chat, [str(x) for x in body.member_ids])
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(user: User = Depends(get_current_user), limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = Query(None, min_length=1), db: AsyncSession = Depends(get_db)):
|
||||
parsed = None
|
||||
if cursor is not None:
|
||||
try:
|
||||
c_created, c_id = cursor.split("|", 1)
|
||||
parsed = (datetime.fromisoformat(c_created), UUID(c_id))
|
||||
except Exception: raise HTTPException(400, "Invalid cursor")
|
||||
rows, next_cursor = await chats_repo.list_for_user(db, user.id, limit, parsed)
|
||||
items = []
|
||||
for chat in rows:
|
||||
members = await chats_repo.list_member_ids(db, chat.id)
|
||||
items.append(_chat_json(chat, [str(m) for m in members]))
|
||||
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
|
||||
return {"items": items, "next_cursor": nxt}
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: UUID, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||
chat = await chats_repo.get_if_member(db, chat_id, user.id)
|
||||
if chat is None: raise HTTPException(404, "Chat not found")
|
||||
members = await chats_repo.list_member_ids(db, chat.id)
|
||||
return _chat_json(chat, [str(m) for m in members])
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def post_message(chat_id: UUID, body: CreateMessage, idempotency_key: str = Header(..., alias="Idempotency-Key"), user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||
chat = await chats_repo.get_if_member(db, chat_id, user.id)
|
||||
if chat is None: raise HTTPException(404, "Chat not found")
|
||||
|
||||
if not body.text.strip() and not body.attachment_ids:
|
||||
raise HTTPException(400, "Empty message without attachments")
|
||||
|
||||
req_hash = hashlib.sha256(body.model_dump_json().encode("utf-8")).hexdigest()
|
||||
stmt = select(IdempotencyRecord).where(IdempotencyRecord.user_id == user.id, IdempotencyRecord.key == idempotency_key)
|
||||
record = (await db.execute(stmt)).scalar_one_or_none()
|
||||
|
||||
if record:
|
||||
if record.request_hash != req_hash: raise HTTPException(409, "Idempotency key conflict")
|
||||
return JSONResponse(status_code=201, content=json.loads(record.response_body))
|
||||
|
||||
msg = await messages_repo.create_and_invalidate(db, chat_id, user.id, body.text)
|
||||
|
||||
if body.attachment_ids:
|
||||
for att_id in body.attachment_ids:
|
||||
att = await db.get(Attachment, att_id)
|
||||
if not att or att.chat_id != chat_id:
|
||||
raise HTTPException(404, f"Attachment {att_id} not found in this chat")
|
||||
db.add(MessageAttachment(message_id=msg.id, attachment_id=att_id))
|
||||
|
||||
resp_dict = _msg_json(msg, body.attachment_ids)
|
||||
resp_body = json.dumps(resp_dict)
|
||||
|
||||
db.add(IdempotencyRecord(user_id=user.id, key=idempotency_key, request_hash=req_hash, response_body=resp_body))
|
||||
try:
|
||||
await db.commit()
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
record = (await db.execute(stmt)).scalar_one_or_none()
|
||||
if record and record.request_hash == req_hash:
|
||||
return JSONResponse(status_code=201, content=json.loads(record.response_body))
|
||||
raise HTTPException(409, "Idempotency key conflict")
|
||||
|
||||
return JSONResponse(status_code=201, content=json.loads(resp_body))
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: UUID, user: User = Depends(get_current_user), limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = Query(None, min_length=1), db: AsyncSession = Depends(get_db)):
|
||||
chat = await chats_repo.get_if_member(db, chat_id, user.id)
|
||||
if chat is None: raise HTTPException(404, "Chat not found")
|
||||
|
||||
parsed = None
|
||||
if cursor is not None:
|
||||
try:
|
||||
c_created, c_id = cursor.split("|", 1)
|
||||
parsed = (datetime.fromisoformat(c_created), UUID(c_id))
|
||||
except Exception: raise HTTPException(400, "Invalid cursor")
|
||||
|
||||
rows, next_cursor, _cached = await messages_repo.list_page_cached(db, chat_id, limit, parsed)
|
||||
|
||||
msg_ids = [m.id for m in rows]
|
||||
att_map = {}
|
||||
if msg_ids:
|
||||
att_stmt = select(MessageAttachment.message_id, MessageAttachment.attachment_id).where(MessageAttachment.message_id.in_(msg_ids))
|
||||
att_rows = (await db.execute(att_stmt)).all()
|
||||
for mid, aid in att_rows: att_map.setdefault(mid, []).append(aid)
|
||||
|
||||
items = [_msg_json(m, att_map.get(m.id, [])) for m in rows]
|
||||
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
|
||||
return {"items": items, "next_cursor": nxt}
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
|
||||
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")
|
||||
|
||||
content = await request.body()
|
||||
mime = validate_image(content)
|
||||
|
||||
sha256 = hashlib.sha256(content).hexdigest()
|
||||
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)
|
||||
|
||||
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)
|
||||
db.add(att)
|
||||
await db.commit()
|
||||
await db.refresh(att)
|
||||
return _attachment_json(att)
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
async def get_attachment(attachment_id: UUID, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||
att = await db.get(Attachment, attachment_id)
|
||||
if not att: raise HTTPException(404, "Attachment not found")
|
||||
chat = await chats_repo.get_if_member(db, att.chat_id, user.id)
|
||||
if not chat: raise HTTPException(404, "Attachment not found")
|
||||
return _attachment_json(att)
|
||||
|
||||
@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)):
|
||||
att = await db.get(Attachment, attachment_id)
|
||||
if not att: raise HTTPException(404, "Attachment not found")
|
||||
chat = await chats_repo.get_if_member(db, att.chat_id, user.id)
|
||||
if not chat: raise HTTPException(404, "Attachment not found")
|
||||
|
||||
obj = s3.get_object(Bucket=BUCKET, Key=att.s3_key)
|
||||
content = obj["Body"].read()
|
||||
return Response(content=content, media_type=att.content_type)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("APP_PORT", "8080")))
|
||||
@@ -0,0 +1,61 @@
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
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=12, max_length=128)
|
||||
|
||||
@field_validator("display_name", "password")
|
||||
@classmethod
|
||||
def _not_blank(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("must not be blank")
|
||||
return v
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def _title_not_blank(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("title must not be blank")
|
||||
return v
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def _unique_members(cls, v: list[UUID]) -> list[UUID]:
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("duplicate member_ids")
|
||||
return v
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
# min_length=0 разрешает пустой текст, если прикреплен файл
|
||||
text: str = Field(min_length=0, max_length=4000)
|
||||
attachment_ids: list[UUID] | None = None
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: str
|
||||
user: dict
|
||||
|
||||
class AttachmentResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
error_code: str | None = None
|
||||
variants: list = []
|
||||
created_at: str
|
||||
updated_at: str
|
||||
@@ -0,0 +1,80 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..db.models import Chat, ChatMember, User
|
||||
|
||||
|
||||
async def create_atomic(
|
||||
db: AsyncSession, title: str, member_ids: list[UUID]
|
||||
) -> Chat:
|
||||
found = (
|
||||
(await db.execute(select(User.id).where(User.id.in_(member_ids))))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
if len(set(found)) != len(set(member_ids)):
|
||||
await db.rollback()
|
||||
raise ValueError("member_not_found")
|
||||
|
||||
chat = Chat(title=title)
|
||||
db.add(chat)
|
||||
await db.flush()
|
||||
|
||||
for uid in member_ids:
|
||||
db.add(ChatMember(chat_id=chat.id, user_id=uid))
|
||||
|
||||
try:
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
await db.refresh(chat)
|
||||
return chat
|
||||
|
||||
|
||||
async def get_if_member(
|
||||
db: AsyncSession, chat_id: UUID, user_id: UUID
|
||||
) -> Chat | None:
|
||||
stmt = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(Chat.id == chat_id, ChatMember.user_id == user_id)
|
||||
)
|
||||
return (await db.execute(stmt)).scalar_one_or_none()
|
||||
|
||||
|
||||
async def list_member_ids(db: AsyncSession, chat_id: UUID) -> list[UUID]:
|
||||
stmt = select(ChatMember.user_id).where(ChatMember.chat_id == chat_id)
|
||||
return list((await db.execute(stmt)).scalars().all())
|
||||
|
||||
|
||||
async def list_for_user(
|
||||
db: AsyncSession,
|
||||
user_id: UUID,
|
||||
limit: int,
|
||||
cursor: tuple[datetime, UUID] | None,
|
||||
) -> tuple[list[Chat], tuple[datetime, UUID] | None]:
|
||||
stmt = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user_id)
|
||||
.order_by(Chat.created_at.asc(), Chat.id.asc())
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if cursor is not None:
|
||||
c_created, c_id = cursor
|
||||
stmt = stmt.where(
|
||||
(Chat.created_at > c_created)
|
||||
| ((Chat.created_at == c_created) & (Chat.id > c_id))
|
||||
)
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
last = rows[-1]
|
||||
next_cursor = (last.created_at, last.id)
|
||||
return rows, next_cursor
|
||||
@@ -0,0 +1,128 @@
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID
|
||||
|
||||
import redis.asyncio as redis
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..db.models import Message
|
||||
|
||||
redis_client = redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0"))
|
||||
CACHE_TTL = 30
|
||||
|
||||
|
||||
def _serialize(rows: list[Message], next_cursor):
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"id": str(m.id),
|
||||
"chat_id": str(m.chat_id),
|
||||
"sender_id": str(m.sender_id),
|
||||
"text": m.text,
|
||||
"created_at": m.created_at.isoformat(),
|
||||
}
|
||||
for m in rows
|
||||
],
|
||||
"next_cursor": (
|
||||
[next_cursor[0].isoformat(), str(next_cursor[1])] if next_cursor else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _deserialize(data: dict):
|
||||
items = [
|
||||
SimpleNamespace(
|
||||
id=UUID(row["id"]),
|
||||
chat_id=UUID(row["chat_id"]),
|
||||
sender_id=UUID(row["sender_id"]),
|
||||
text=row["text"],
|
||||
created_at=datetime.fromisoformat(row["created_at"]),
|
||||
)
|
||||
for row in data["items"]
|
||||
]
|
||||
nc = data.get("next_cursor")
|
||||
next_cursor = (datetime.fromisoformat(nc[0]), UUID(nc[1])) if nc else None
|
||||
return items, next_cursor
|
||||
|
||||
|
||||
async def create(
|
||||
db: AsyncSession, chat_id: UUID, sender_id: UUID, text: str
|
||||
) -> Message:
|
||||
msg = Message(chat_id=chat_id, sender_id=sender_id, text=text)
|
||||
db.add(msg)
|
||||
await db.commit()
|
||||
await db.refresh(msg)
|
||||
return msg
|
||||
|
||||
|
||||
async def create_and_invalidate(
|
||||
db: AsyncSession, chat_id: UUID, sender_id: UUID, text: str
|
||||
) -> Message:
|
||||
msg = await create(db, chat_id, sender_id, text)
|
||||
keys = [f"chat:{chat_id}:first_page:{n}" for n in (10, 20, 50)]
|
||||
await redis_client.delete(*keys)
|
||||
return msg
|
||||
|
||||
|
||||
async def list_page(
|
||||
db: AsyncSession,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
cursor: tuple[datetime, UUID] | None,
|
||||
) -> tuple[list[Message], tuple[datetime, UUID] | None]:
|
||||
stmt = (
|
||||
select(Message)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at.asc(), Message.id.asc())
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if cursor is not None:
|
||||
c_created, c_id = cursor
|
||||
stmt = stmt.where(
|
||||
(Message.created_at > c_created)
|
||||
| ((Message.created_at == c_created) & (Message.id > c_id))
|
||||
)
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
last = rows[-1]
|
||||
next_cursor = (last.created_at, last.id)
|
||||
return rows, next_cursor
|
||||
|
||||
|
||||
async def list_page_cached(
|
||||
db: AsyncSession,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
cursor: tuple[datetime, UUID] | None,
|
||||
) -> tuple[list, tuple[datetime, UUID] | None, bool]:
|
||||
"""Возвращает (rows, next_cursor, cached)."""
|
||||
use_cache = cursor is None and limit <= 50
|
||||
key = f"chat:{chat_id}:first_page:{limit}"
|
||||
|
||||
if use_cache:
|
||||
raw = await redis_client.get(key)
|
||||
if raw is not None:
|
||||
try:
|
||||
rows, next_cursor = _deserialize(json.loads(raw))
|
||||
return rows, next_cursor, True
|
||||
except Exception:
|
||||
pass # повреждённый кэш — игнорируем и идём в БД
|
||||
|
||||
rows, next_cursor = await list_page(db, chat_id, limit, cursor)
|
||||
|
||||
if use_cache:
|
||||
try:
|
||||
payload = json.dumps(_serialize(rows, next_cursor))
|
||||
await redis_client.setex(key, CACHE_TTL, payload)
|
||||
print(f"CACHE SET OK: {key}", flush=True)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
print(f"CACHE SET FAILED: {type(e).__name__}: {e}", flush=True)
|
||||
|
||||
return rows, next_cursor, False
|
||||
@@ -0,0 +1,28 @@
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..db.models import User
|
||||
|
||||
|
||||
async def get_by_username(db: AsyncSession, username: str) -> User | None:
|
||||
return (
|
||||
await db.execute(select(User).where(User.username == username))
|
||||
).scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_by_id(db: AsyncSession, user_id: UUID) -> User | None:
|
||||
return await db.get(User, user_id)
|
||||
|
||||
|
||||
async def create(
|
||||
db: AsyncSession, username: str, display_name: str, password_hash: str
|
||||
) -> User:
|
||||
user = User(
|
||||
username=username, display_name=display_name, password_hash=password_hash
|
||||
)
|
||||
db.add(user)
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
return user
|
||||
@@ -0,0 +1,20 @@
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
import os
|
||||
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.getenv("S3_ENDPOINT", "http://minio:9000"),
|
||||
aws_access_key_id=os.getenv("S3_ACCESS_KEY", "minioadmin"),
|
||||
aws_secret_access_key=os.getenv("S3_SECRET_KEY", "minioadmin"),
|
||||
config=Config(signature_version="s3v4"),
|
||||
region_name="us-east-1",
|
||||
)
|
||||
|
||||
BUCKET = os.getenv("S3_BUCKET", "attachments")
|
||||
|
||||
def ensure_bucket():
|
||||
try:
|
||||
s3.head_bucket(Bucket=BUCKET)
|
||||
except Exception:
|
||||
s3.create_bucket(Bucket=BUCKET)
|
||||
Reference in New Issue
Block a user