feat(lab3): add nginx load balancing, scaling, idempotency and failover script

This commit is contained in:
2026-10-23 03:54:09 +03:00
parent 0ab3a341aa
commit a99e4c72c6
21 changed files with 973 additions and 0 deletions
View File
+31
View File
@@ -0,0 +1,31 @@
import os
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql+asyncpg://app_user:secure_password_123@postgres:5432/messenger_db")
REDIS_URL: str = os.getenv("REDIS_URL", "redis://redis:6379/0")
SESSION_TTL_SECONDS: int = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
settings = Settings()
engine = create_async_engine(
settings.DATABASE_URL,
pool_size=10,
max_overflow=20,
pool_timeout=30,
pool_recycle=1800
)
async_session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_db():
async with async_session_maker() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
+56
View File
@@ -0,0 +1,56 @@
import uuid
import logging
from datetime import datetime, timezone
from fastapi import Depends, HTTPException, status, Security
from fastapi.security import HTTPBearer, HTTPBasic, HTTPBasicCredentials
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError
from app.database import get_db
from app.models import User as UserModel, UserSession
from app.redis_client import get_redis
logger = logging.getLogger(__name__)
security_bearer = HTTPBearer(auto_error=False)
security_basic = HTTPBasic(auto_error=False)
async def get_current_user(credentials = Security(security_bearer), db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis)) -> UserModel:
if not credentials:
raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "Missing Bearer token"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
token = credentials.credentials
user_id_str = None
try:
user_id_str = await redis_client.get(f"session:{token}")
except Exception as e:
logger.warning(f"Redis unavailable, falling back to PostgreSQL: {e}")
if not user_id_str:
try:
result = await db.execute(select(UserSession).where(UserSession.token == token).where(UserSession.expires_at > datetime.now(timezone.utc)))
session = result.scalar_one_or_none()
if session:
user_id_str = str(session.user_id)
else:
raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "Invalid or expired session"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
except HTTPException:
raise
except SQLAlchemyError as e:
logger.error(f"PostgreSQL error during session check: {e}")
raise HTTPException(status_code=500, detail={"code": "internal_error", "message": "Session store unavailable"})
try:
user_id = uuid.UUID(user_id_str)
except (ValueError, TypeError):
raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "Invalid session data"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
result = await db.execute(select(UserModel).where(UserModel.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "User not found"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
return user
def get_basic_auth(credentials: HTTPBasicCredentials = Security(security_basic)):
if not credentials:
raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "Missing Basic auth"}, headers={"WWW-Authenticate": "Basic realm=\"messenger\", charset=\"UTF-8\""})
return credentials
+71
View File
@@ -0,0 +1,71 @@
import os
import uuid
import logging
import traceback
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from app.routers import auth, chats
from app.redis_client import get_redis
logger = logging.getLogger(__name__)
app = FastAPI()
app.include_router(auth.router)
app.include_router(chats.router)
# Уникальный ID для этой реплики (генерируется при старте или берется из env)
INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4())[:8])
@app.middleware("http")
async def add_instance_and_request_id(request: Request, call_next):
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception as e:
# <--- ДОБАВИТЬ ЭТО: Печатаем настоящую ошибку в логи
logger.error(f"Unhandled exception: {e}")
traceback.print_exc()
return JSONResponse(
status_code=500,
content={"error": {"code": "internal_error", "message": "Unexpected error", "request_id": request_id}},
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
)
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
first_error = exc.errors()[0] if exc.errors() else {"msg": "Invalid request"}
return JSONResponse(
status_code=400,
content={"error": {"code": "invalid_request", "message": first_error.get("msg", "Invalid request"), "request_id": request_id}},
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
detail = exc.detail if isinstance(exc.detail, dict) else {"code": "internal_error", "message": str(exc.detail)}
clean_error = {"code": detail.get("code", "internal_error"), "message": detail.get("message", "Unknown error"), "request_id": request_id}
headers = {"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
if exc.headers: headers.update(exc.headers)
return JSONResponse(status_code=exc.status_code, content={"error": clean_error}, headers=headers)
@app.get("/health/live")
async def liveness():
return {"status": "ok"}
@app.get("/health/ready")
async def readiness(redis_client = Depends(get_redis)):
try:
await redis_client.ping()
except Exception as e:
logger.warning(f"Redis health check failed, PostgreSQL fallback is active: {e}")
return {"status": "ok"}
+59
View File
@@ -0,0 +1,59 @@
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, Index, Text
from sqlalchemy.orm import declarative_base, relationship
from sqlalchemy.dialects.postgresql import UUID, JSONB
import uuid
from datetime import datetime, timezone
Base = declarative_base()
def utc_now():
return datetime.now(timezone.utc)
class User(Base):
__tablename__ = "users"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
username = Column(String(32), unique=True, nullable=False, index=True)
display_name = Column(String(100), nullable=False)
password_hash = Column(String(255), nullable=False)
created_at = Column(DateTime(timezone=True), default=utc_now)
sessions = relationship("UserSession", back_populates="user", cascade="all, delete-orphan")
class Chat(Base):
__tablename__ = "chats"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
title = Column(String(100), nullable=False)
created_at = Column(DateTime(timezone=True), default=utc_now)
members = relationship("ChatMember", back_populates="chat", cascade="all, delete-orphan")
messages = relationship("Message", back_populates="chat", cascade="all, delete-orphan")
class ChatMember(Base):
__tablename__ = "chat_members"
chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
chat = relationship("Chat", back_populates="members")
class Message(Base):
__tablename__ = "messages"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False)
sender_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
text = Column(String(4000), nullable=False)
created_at = Column(DateTime(timezone=True), default=utc_now, nullable=False)
chat = relationship("Chat", back_populates="messages")
__table_args__ = (Index("ix_messages_chat_history", "chat_id", "created_at", "id"),)
class UserSession(Base):
__tablename__ = "sessions"
token = Column(String(255), primary_key=True)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
created_at = Column(DateTime(timezone=True), default=utc_now, nullable=False)
expires_at = Column(DateTime(timezone=True), nullable=False)
user = relationship("User", back_populates="sessions")
class IdempotencyKey(Base):
"""Таблица для хранения ключей идемпотентности (Требование Lab 3)"""
__tablename__ = "idempotency_keys"
key = Column(String(255), primary_key=True)
chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False)
response_data = Column(JSONB, nullable=False) # Сохраняем полный ответ, чтобы вернуть его при повторе
created_at = Column(DateTime(timezone=True), default=utc_now, nullable=False)
+12
View File
@@ -0,0 +1,12 @@
import redis.asyncio as redis
from app.database import settings
redis_client = redis.from_url(
settings.REDIS_URL,
encoding="utf-8",
decode_responses=True,
health_check_interval=30
)
async def get_redis():
return redis_client
+117
View File
@@ -0,0 +1,117 @@
import secrets
import logging
import bcrypt
import asyncpg
from datetime import datetime, timezone, timedelta
from fastapi import APIRouter, Depends, HTTPException, status, Response
from fastapi.security import HTTPBearer
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.exc import SQLAlchemyError
from app.database import get_db, settings
from app.models import User as UserModel, UserSession
from app.schemas import CreateUser, User, Session, ErrorResponse
from app.dependencies import get_basic_auth, get_current_user
from app.redis_client import get_redis
logger = logging.getLogger(__name__)
router = APIRouter()
def verify_password(plain_password: str, hashed_password: str) -> bool:
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
def get_password_hash(password: str) -> str:
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
@router.post("/api/v1/users", response_model=User, status_code=status.HTTP_201_CREATED, responses={409: {"model": ErrorResponse}})
async def register_user(user_in: CreateUser, db: AsyncSession = Depends(get_db)):
new_user = UserModel(
username=user_in.username,
display_name=user_in.display_name,
password_hash=get_password_hash(user_in.password)
)
db.add(new_user)
try:
await db.commit()
await db.refresh(new_user)
# Явное форматирование полей в строки для гарантии совместимости с Pydantic v2
return User(
id=str(new_user.id),
username=new_user.username,
display_name=new_user.display_name,
created_at=new_user.created_at.isoformat().replace('+00:00', 'Z')
)
except Exception as e:
await db.rollback()
if isinstance(e.__cause__, asyncpg.exceptions.UniqueViolationError) or "unique constraint" in str(e).lower():
raise HTTPException(status_code=409, detail={"code": "conflict", "message": "Username already exists"})
logger.error(f"Database error during registration: {e}")
raise HTTPException(status_code=500, detail={"code": "internal_error", "message": "Database error"})
@router.post("/api/v1/auth/sessions", response_model=Session, status_code=status.HTTP_201_CREATED, responses={401: {"model": ErrorResponse}})
async def create_session(credentials = Depends(get_basic_auth), db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis)):
result = await db.execute(select(UserModel).where(UserModel.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=401, detail={"code": "unauthorized", "message": "Invalid username or password"}, headers={"WWW-Authenticate": "Basic realm=\"messenger\", charset=\"UTF-8\""})
token = secrets.token_urlsafe(32)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.SESSION_TTL_SECONDS)
try:
await redis_client.setex(f"session:{token}", settings.SESSION_TTL_SECONDS, str(user.id))
except Exception as e:
logger.warning(f"Redis unavailable during session creation: {e}")
try:
db.add(UserSession(token=token, user_id=user.id, expires_at=expires_at))
await db.commit()
except SQLAlchemyError as e:
await db.rollback()
logger.error(f"Failed to save session to PostgreSQL: {e}")
raise HTTPException(status_code=500, detail={"code": "internal_error", "message": "Failed to create session"})
return Session(
token=token,
token_type="Bearer",
expires_at=expires_at,
user=User(
id=str(user.id),
username=user.username,
display_name=user.display_name,
created_at=user.created_at.isoformat().replace('+00:00', 'Z')
)
)
@router.delete("/api/v1/auth/sessions/current", status_code=status.HTTP_204_NO_CONTENT, responses={401: {"model": ErrorResponse}})
async def revoke_session(credentials = Depends(HTTPBearer()), db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis)):
token = credentials.credentials
try:
await redis_client.delete(f"session:{token}")
except Exception as e:
logger.warning(f"Redis unavailable during session revocation: {e}")
try:
result = await db.execute(select(UserSession).where(UserSession.token == token))
session = result.scalar_one_or_none()
if session:
await db.delete(session)
await db.commit()
else:
raise HTTPException(status_code=401, detail={"code": "unauthorized", "message": "Invalid or expired session"}, headers={"WWW-Authenticate": "Bearer realm=\"messenger\""})
except HTTPException:
raise
except SQLAlchemyError as e:
await db.rollback()
raise HTTPException(status_code=500, detail={"code": "internal_error", "message": "Failed to revoke session"})
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.get("/api/v1/users/me", response_model=User, responses={401: {"model": ErrorResponse}})
async def current_user(current_user: UserModel = Depends(get_current_user)):
return User(
id=str(current_user.id),
username=current_user.username,
display_name=current_user.display_name,
created_at=current_user.created_at.isoformat().replace('+00:00', 'Z')
)
+187
View File
@@ -0,0 +1,187 @@
import uuid
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, status, Query, Header
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.database import get_db
from app.models import Chat as ChatModel, ChatMember as ChatMemberModel, Message as MessageModel, User as UserModel, IdempotencyKey
from app.schemas import Chat, CreateChat, Message, CreateMessage, ChatPage, MessagePage, ErrorResponse
from app.dependencies import get_current_user
from app.redis_client import get_redis
router = APIRouter()
@router.post("/api/v1/chats", response_model=Chat, status_code=status.HTTP_201_CREATED, responses={400: {"model": ErrorResponse}, 401: {"model": ErrorResponse}})
async def create_chat(
chat_in: CreateChat,
current_user: UserModel = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
):
# Преобразуем строки в UUID для корректного сравнения
try:
member_uuids = [uuid.UUID(uid) for uid in chat_in.member_ids]
except ValueError:
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "Invalid member_id format"})
# Проверяем, что создатель в списке участников
if current_user.id not in member_uuids:
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "Creator must be in member_ids"})
# Проверяем, что все участники существуют
user_ids = list(set(member_uuids))
result = await db.execute(select(UserModel).where(UserModel.id.in_(user_ids)))
found_users = result.scalars().all()
if len(found_users) != len(user_ids):
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "One or more member_ids do not exist"})
# Создаём чат
new_chat = ChatModel(title=chat_in.title)
db.add(new_chat)
await db.flush()
db.add_all([ChatMemberModel(chat_id=new_chat.id, user_id=uid) for uid in user_ids])
await db.commit()
await db.refresh(new_chat)
return Chat(
id=str(new_chat.id),
title=new_chat.title,
member_ids=[str(uid) for uid in user_ids],
created_at=new_chat.created_at.isoformat().replace('+00:00', 'Z')
)
@router.get("/api/v1/chats", response_model=ChatPage, responses={401: {"model": ErrorResponse}})
async def list_chats(limit: int = Query(50, ge=1, le=100), cursor: str | None = None, current_user: UserModel = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
stmt = select(ChatModel).options(selectinload(ChatModel.members)).join(ChatMemberModel, ChatModel.id == ChatMemberModel.chat_id).where(ChatMemberModel.user_id == current_user.id).order_by(ChatModel.created_at.desc(), ChatModel.id.desc())
if cursor:
try:
created_at_str, chat_id_str = cursor.split(",")
created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
chat_id = uuid.UUID(chat_id_str)
stmt = stmt.where((ChatModel.created_at < created_at) | ((ChatModel.created_at == created_at) & (ChatModel.id < chat_id)))
except (ValueError, TypeError):
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "Invalid cursor"})
stmt = stmt.limit(limit + 1)
chats = (await db.execute(stmt)).scalars().all()
has_next = len(chats) > limit
if has_next:
chats = chats[:-1]
next_cursor = f"{chats[-1].created_at.isoformat().replace('+00:00', 'Z')},{chats[-1].id}"
else:
next_cursor = None
items = [Chat(id=str(c.id), title=c.title, member_ids=[str(m.user_id) for m in c.members], created_at=c.created_at.isoformat().replace('+00:00', 'Z')) for c in chats]
return ChatPage(items=items, next_cursor=next_cursor)
@router.get("/api/v1/chats/{chat_id}", response_model=Chat, responses={401: {"model": ErrorResponse}, 404: {"model": ErrorResponse}})
async def get_chat(chat_id: uuid.UUID, current_user: UserModel = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
stmt = select(ChatModel).options(selectinload(ChatModel.members)).join(ChatMemberModel, ChatModel.id == ChatMemberModel.chat_id).where(ChatModel.id == chat_id, ChatMemberModel.user_id == current_user.id)
chat = (await db.execute(stmt)).scalar_one_or_none()
if not chat:
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Chat not found or access denied"})
return Chat(id=str(chat.id), title=chat.title, member_ids=[str(m.user_id) for m in chat.members], created_at=chat.created_at.isoformat().replace('+00:00', 'Z'))
@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=status.HTTP_201_CREATED, responses={400: {"model": ErrorResponse}, 401: {"model": ErrorResponse}, 404: {"model": ErrorResponse}, 409: {"model": ErrorResponse}})
async def create_message(
chat_id: uuid.UUID,
message_in: CreateMessage,
current_user: UserModel = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
redis_client = Depends(get_redis),
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key")
):
if not idempotency_key:
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "Idempotency-Key header is required"})
if not (await db.execute(select(ChatMemberModel).where(ChatMemberModel.chat_id == chat_id, ChatMemberModel.user_id == current_user.id))).scalar_one_or_none():
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Chat not found or access denied"})
existing_key = await db.execute(select(IdempotencyKey).where(IdempotencyKey.key == idempotency_key))
existing_record = existing_key.scalar_one_or_none()
if existing_record:
if existing_record.response_data.get("text") != message_in.text:
raise HTTPException(status_code=409, detail={"code": "conflict", "message": "Idempotency-Key already used with different payload"})
return Message(**existing_record.response_data)
new_message = MessageModel(chat_id=chat_id, sender_id=current_user.id, text=message_in.text)
db.add(new_message)
await db.commit()
await db.refresh(new_message)
response_data = {
"id": str(new_message.id),
"chat_id": str(new_message.chat_id),
"sender_id": str(new_message.sender_id),
"text": new_message.text,
"created_at": new_message.created_at.isoformat().replace('+00:00', 'Z')
}
db.add(IdempotencyKey(key=idempotency_key, chat_id=chat_id, response_data=response_data))
await db.commit()
try:
await redis_client.delete(f"messages:{chat_id}:*")
except Exception as e:
pass
return Message(**response_data)
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage, responses={400: {"model": ErrorResponse}, 401: {"model": ErrorResponse}, 404: {"model": ErrorResponse}})
async def list_messages(chat_id: uuid.UUID, limit: int = Query(50, ge=1, le=100), cursor: str | None = None, current_user: UserModel = Depends(get_current_user), db: AsyncSession = Depends(get_db), redis_client = Depends(get_redis)):
if not (await db.execute(select(ChatMemberModel).where(ChatMemberModel.chat_id == chat_id, ChatMemberModel.user_id == current_user.id))).scalar_one_or_none():
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Chat not found or access denied"})
cache_key = f"messages:{chat_id}:{limit}:{cursor or 'null'}"
redis_available = True
try:
cached_data = await redis_client.get(cache_key)
if cached_data:
await redis_client.expire(cache_key, 60)
return MessagePage.model_validate_json(cached_data)
except Exception as e:
redis_available = False
lock_acquired = False
if redis_available:
lock_key = f"lock:{cache_key}"
try:
lock_acquired = await redis_client.set(lock_key, "1", nx=True, ex=5)
if not lock_acquired:
stale_data = await redis_client.get(f"stale:{cache_key}")
if stale_data: return MessagePage.model_validate_json(stale_data)
except Exception as e:
redis_available = False
stmt = select(MessageModel).where(MessageModel.chat_id == chat_id).order_by(MessageModel.created_at.asc(), MessageModel.id.asc())
if cursor:
try:
created_at_str, msg_id_str = cursor.split(",")
created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
msg_id = uuid.UUID(msg_id_str)
stmt = stmt.where((MessageModel.created_at > created_at) | ((MessageModel.created_at == created_at) & (MessageModel.id > msg_id)))
except (ValueError, TypeError):
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "Invalid cursor"})
stmt = stmt.limit(limit + 1)
messages = (await db.execute(stmt)).scalars().all()
has_next = len(messages) > limit
if has_next:
messages = messages[:-1]
next_cursor = f"{messages[-1].created_at.isoformat().replace('+00:00', 'Z')},{messages[-1].id}"
else:
next_cursor = None
items = [Message(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().replace('+00:00', 'Z')) for m in messages]
page = MessagePage(items=items, next_cursor=next_cursor)
if redis_available:
try:
old_cache = await redis_client.get(cache_key)
if old_cache: await redis_client.setex(f"stale:{cache_key}", 120, old_cache)
await redis_client.setex(cache_key, 60, page.model_dump_json())
if lock_acquired: await redis_client.delete(f"lock:{cache_key}")
except Exception as e:
pass
return page
+55
View File
@@ -0,0 +1,55 @@
from pydantic import BaseModel, Field, ConfigDict
from typing import List, Optional
from datetime import datetime
class User(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
username: str
display_name: str
created_at: str
class CreateUser(BaseModel):
username: str = Field(..., min_length=3, max_length=32, pattern="^[a-z0-9_]+$")
display_name: str = Field(..., min_length=1, max_length=100)
password: str = Field(..., min_length=12, max_length=128)
class Session(BaseModel):
model_config = ConfigDict(from_attributes=True)
token: str
token_type: str
expires_at: datetime
user: User
class Chat(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
title: str
member_ids: List[str]
created_at: str
class CreateChat(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
member_ids: List[str]
class ChatPage(BaseModel):
items: List[Chat]
next_cursor: Optional[str] = None
class Message(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
chat_id: str
sender_id: str
text: str
created_at: str
class CreateMessage(BaseModel):
text: str = Field(..., min_length=1, max_length=4000)
class MessagePage(BaseModel):
items: List[Message]
next_cursor: Optional[str] = None
class ErrorResponse(BaseModel):
error: dict