+ скопировала все файлы проекта из л.р. 1
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Security
|
||||
from ..models.schemas import Chat, ChatPage, CreateChat
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
def _encode_cursor(user_id: UUID, chat: Chat) -> str:
|
||||
"""Простой курсор: user_id + id + created_at, base64."""
|
||||
data = {"user_id": str(user_id), "id": str(chat.id), "created_at": chat.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(user_id: UUID, cursor: str) -> tuple:
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
if data.get("user_id") != str(user_id):
|
||||
raise ValueError("cursor_user_mismatch")
|
||||
return UUID(data["id"]), data["created_at"]
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="",
|
||||
summary="Создать чат",
|
||||
response_model=Chat,
|
||||
status_code=201,
|
||||
)
|
||||
def create_chat(
|
||||
payload: CreateChat,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
) -> Chat:
|
||||
"""Вызывающий должен входить в member_ids"""
|
||||
|
||||
if user_id not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if len(set(payload.member_ids)) != len(payload.member_ids):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
try:
|
||||
return storage.create_chat(payload.title, list(payload.member_ids))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="",
|
||||
summary="Получить список чатов текущего пользователя",
|
||||
response_model=ChatPage,
|
||||
)
|
||||
def list_chats(
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> ChatPage:
|
||||
chats = storage.list_chats_for_user(user_id)
|
||||
if cursor:
|
||||
cid, ccreated = _decode_cursor(user_id, cursor)
|
||||
chats = [c for c in chats if (c.created_at.isoformat(), str(c.id)) > (ccreated, str(cid))]
|
||||
page = chats[:limit]
|
||||
next_cursor = _encode_cursor(user_id, page[-1]) if len(chats) > limit else None
|
||||
return ChatPage(items=page, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}",
|
||||
summary="Получить доступный чат по идентификатору",
|
||||
response_model=Chat,
|
||||
)
|
||||
def get_chat(
|
||||
chat_id: UUID,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
) -> Chat:
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
@@ -0,0 +1,25 @@
|
||||
from fastapi import APIRouter
|
||||
from ..models.schemas import Health
|
||||
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/health/live",
|
||||
summary="Проверка жизнеспособности процесса",
|
||||
response_model=Health,
|
||||
)
|
||||
def liveness() -> Health:
|
||||
"""Процесс жив"""
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/health/ready",
|
||||
summary="Проверка готовности принимать трафик",
|
||||
response_model=Health,
|
||||
)
|
||||
def readiness() -> Health:
|
||||
"""Готов принимать трафик. В lab1 критичных зависимостей нет."""
|
||||
return Health(status="ok")
|
||||
@@ -0,0 +1,81 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Security
|
||||
from ..models.schemas import CreateMessage, Message, MessagePage
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
|
||||
|
||||
def _encode_cursor(chat_id: UUID, message: Message) -> str:
|
||||
data = {"chat_id": str(chat_id), "id": str(message.id), "created_at": message.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
if data.get("chat_id") != str(chat_id):
|
||||
raise ValueError("cursor_chat_mismatch")
|
||||
return UUID(data["id"]), data["created_at"]
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Отправить сообщение в чат",
|
||||
response_model=Message,
|
||||
status_code=201,
|
||||
)
|
||||
def create_message(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessage,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
) -> Message:
|
||||
_require_member(chat_id, user_id)
|
||||
if not payload.text.strip():
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
return storage.add_message(chat_id, user_id, payload.text)
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Получить историю сообщений чата",
|
||||
response_model=MessagePage,
|
||||
)
|
||||
def list_messages(
|
||||
chat_id: UUID,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> MessagePage:
|
||||
"""Реализована курсорная пагинация"""
|
||||
|
||||
_require_member(chat_id, user_id)
|
||||
messages = storage.list_messages(chat_id)
|
||||
if cursor:
|
||||
mid, mcreated = _decode_cursor(chat_id, cursor)
|
||||
messages = [m for m in messages if (m.created_at.isoformat(), str(m.id)) > (mcreated, str(mid))]
|
||||
page = messages[:limit]
|
||||
next_cursor = _encode_cursor(chat_id, page[-1]) if len(messages) > limit else None
|
||||
return MessagePage(items=page, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,3 @@
|
||||
from fastapi.security import APIKeyHeader
|
||||
|
||||
dev_user = APIKeyHeader(name="X-User-Id", auto_error=False, scheme_name="devUser")
|
||||
@@ -0,0 +1,45 @@
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from ..models.schemas import CreateUser, User
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
from fastapi import Security
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["users"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
"""Достаёт X-User-Id из заголовков и валидирует."""
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/users",
|
||||
summary="Создать пользователя",
|
||||
response_model=User,
|
||||
status_code=201,
|
||||
)
|
||||
def register_user(payload: CreateUser) -> User:
|
||||
"""Публичная регистрация."""
|
||||
try:
|
||||
return storage.create_user(payload.username, payload.display_name)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/users/me",
|
||||
summary="Получить текущего пользователя",
|
||||
response_model=User,
|
||||
)
|
||||
def current_user(user_id: UUID = Depends(_current_user_id)) -> User:
|
||||
"""Текущий пользователь по X-User-Id."""
|
||||
user = storage.get_user(user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
return user
|
||||
Reference in New Issue
Block a user