275 lines
9.6 KiB
Python
275 lines
9.6 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import selectinload
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
|
|
from app.database import get_db
|
|
from app.models import Chat as ChatModel, ChatMember as ChatMemberModel, Message as MessageModel, User as UserModel
|
|
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)
|
|
):
|
|
if current_user.id not in chat_in.member_ids:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail={"code": "invalid_request", "message": "Creator must be in member_ids", }
|
|
)
|
|
|
|
user_ids = list(set(chat_in.member_ids))
|
|
result = await db.execute(select(UserModel).where(UserModel.id.in_(user_ids)))
|
|
if len(result.scalars().all()) != len(user_ids):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
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()
|
|
|
|
members = [ChatMemberModel(chat_id=new_chat.id, user_id=uid) for uid in user_ids]
|
|
db.add_all(members)
|
|
|
|
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=status.HTTP_400_BAD_REQUEST,
|
|
detail={"code": "invalid_request", "message": "Invalid cursor", }
|
|
)
|
|
|
|
stmt = stmt.limit(limit + 1)
|
|
result = await db.execute(stmt)
|
|
chats = result.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 = []
|
|
for c in chats:
|
|
member_ids = [str(m.user_id) for m in c.members]
|
|
items.append(Chat(
|
|
id=str(c.id),
|
|
title=c.title,
|
|
member_ids=member_ids,
|
|
created_at=c.created_at.isoformat().replace('+00:00', 'Z')
|
|
))
|
|
|
|
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=status.HTTP_404_NOT_FOUND,
|
|
detail={"code": "not_found", "message": "Chat not found or access denied", }
|
|
)
|
|
|
|
member_ids = [str(m.user_id) for m in chat.members]
|
|
return Chat(
|
|
id=str(chat.id),
|
|
title=chat.title,
|
|
member_ids=member_ids,
|
|
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}}
|
|
)
|
|
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)
|
|
):
|
|
stmt = select(ChatMemberModel).where(
|
|
ChatMemberModel.chat_id == chat_id, ChatMemberModel.user_id == current_user.id
|
|
)
|
|
if not (await db.execute(stmt)).scalar_one_or_none():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail={"code": "not_found", "message": "Chat not found or access denied", }
|
|
)
|
|
|
|
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)
|
|
|
|
# GRADE 5: Инвалидация кэша при записи (Read-After-Write consistency)
|
|
await redis_client.delete(f"messages:{chat_id}:*")
|
|
|
|
return Message(
|
|
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')
|
|
)
|
|
|
|
@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=status.HTTP_404_NOT_FOUND,
|
|
detail={"code": "not_found", "message": "Chat not found or access denied", }
|
|
)
|
|
|
|
cache_key = f"messages:{chat_id}:{limit}:{cursor or 'null'}"
|
|
|
|
# 1. Проверяем основной кэш
|
|
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)
|
|
|
|
# 2. GRADE 5: Защита от Cache Stampede (Request Coalescing)
|
|
lock_key = f"lock:{cache_key}"
|
|
acquired = await redis_client.set(lock_key, "1", nx=True, ex=5)
|
|
|
|
if not acquired:
|
|
stale_data = await redis_client.get(f"stale:{cache_key}")
|
|
if stale_data:
|
|
return MessagePage.model_validate_json(stale_data)
|
|
|
|
# 3. Выполняем запрос к БД
|
|
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=status.HTTP_400_BAD_REQUEST,
|
|
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 = []
|
|
for m in messages:
|
|
items.append(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')
|
|
))
|
|
|
|
page = MessagePage(items=items, next_cursor=next_cursor)
|
|
|
|
# 4. GRADE 5: Сохраняем старые данные как stale перед обновлением основного кэша
|
|
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())
|
|
await redis_client.delete(lock_key)
|
|
|
|
return page |