solution
This commit is contained in:
+295
@@ -0,0 +1,295 @@
|
||||
"""HTTP-эндпоинты API.
|
||||
|
||||
Порядок проверок: аутентификация (401), доступ к чату (404), тело запроса (400).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from typing import List
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from . import crud
|
||||
from .auth import (
|
||||
BASIC_CHALLENGE,
|
||||
current_user,
|
||||
get_session,
|
||||
parse_basic,
|
||||
parse_bearer,
|
||||
unauthorized,
|
||||
)
|
||||
from .cursor import encode_cursor
|
||||
from .errors import ApiError
|
||||
from .http_utils import (
|
||||
parse_cursor,
|
||||
parse_idempotency_key,
|
||||
parse_limit,
|
||||
parse_uuid,
|
||||
read_json_object,
|
||||
validate_body,
|
||||
)
|
||||
from .models import Chat, Message, User
|
||||
from .schemas import (
|
||||
ChatOut,
|
||||
ChatPage,
|
||||
CreateChatIn,
|
||||
CreateMessageIn,
|
||||
CreateUserIn,
|
||||
MessageOut,
|
||||
MessagePage,
|
||||
SessionOut,
|
||||
UserOut,
|
||||
)
|
||||
from .security import (
|
||||
DUMMY_HASH,
|
||||
hash_password_async,
|
||||
hash_token,
|
||||
new_token,
|
||||
verify_password_async,
|
||||
)
|
||||
from .timeutil import format_ts, from_micros, to_micros
|
||||
|
||||
router = APIRouter()
|
||||
api = APIRouter(prefix="/api/v1")
|
||||
|
||||
|
||||
def body_doc(model: type) -> dict:
|
||||
"""Описание тела запроса для OpenAPI-документации."""
|
||||
return {
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {"application/json": {"schema": model.model_json_schema()}},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def user_out(user: User) -> dict:
|
||||
"""User -> словарь ответа."""
|
||||
return {
|
||||
"id": str(user.id),
|
||||
"username": user.username,
|
||||
"display_name": user.display_name,
|
||||
"created_at": format_ts(user.created_at),
|
||||
}
|
||||
|
||||
|
||||
def chat_out(chat: Chat, member_ids: List[uuid.UUID]) -> dict:
|
||||
"""Chat и участники -> словарь ответа."""
|
||||
return {
|
||||
"id": str(chat.id),
|
||||
"title": chat.title,
|
||||
"member_ids": [str(member_id) for member_id in member_ids],
|
||||
"created_at": format_ts(chat.created_at),
|
||||
}
|
||||
|
||||
|
||||
def message_out(message: Message) -> dict:
|
||||
"""Message -> словарь ответа."""
|
||||
return {
|
||||
"id": str(message.id),
|
||||
"chat_id": str(message.chat_id),
|
||||
"sender_id": str(message.sender_id),
|
||||
"text": message.text,
|
||||
"created_at": format_ts(message.created_at),
|
||||
}
|
||||
|
||||
|
||||
def position(key):
|
||||
"""Позицию из курсора перевести в (datetime, UUID)."""
|
||||
if key is None:
|
||||
return None
|
||||
return from_micros(key[0]), uuid.UUID(key[1])
|
||||
|
||||
|
||||
def cursor_for(scope: str, row) -> str:
|
||||
"""Курсор, указывающий на строку row."""
|
||||
return encode_cursor(scope, (to_micros(row.created_at), str(row.id)))
|
||||
|
||||
|
||||
async def open_chat(session: AsyncSession, user: User, chat_id_text: str) -> Chat:
|
||||
"""Чат, доступный пользователю; неверный id -> 400, чужой или несуществующий -> 404."""
|
||||
chat_id = uuid.UUID(parse_uuid(chat_id_text, "chat_id"))
|
||||
chat = await crud.get_chat_for_member(session, chat_id, user.id)
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
return chat
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
async def live() -> dict:
|
||||
"""Процесс жив."""
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
async def ready(request: Request):
|
||||
"""Готовность: миграции применены и БД отвечает."""
|
||||
if not getattr(request.app.state, "ready", False):
|
||||
raise ApiError(503, "unavailable", "Сервис не готов")
|
||||
try:
|
||||
async with request.app.state.sessionmaker() as session:
|
||||
await asyncio.wait_for(session.execute(text("SELECT 1")), timeout=2)
|
||||
except Exception:
|
||||
raise ApiError(503, "unavailable", "База данных недоступна")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@api.post(
|
||||
"/users",
|
||||
status_code=201,
|
||||
response_model=UserOut,
|
||||
openapi_extra=body_doc(CreateUserIn),
|
||||
)
|
||||
async def register_user(request: Request, session: AsyncSession = Depends(get_session)):
|
||||
"""Регистрация пользователя."""
|
||||
body = validate_body(CreateUserIn, await read_json_object(request))
|
||||
password_hash = await hash_password_async(body.password)
|
||||
try:
|
||||
user = await crud.create_user(
|
||||
session, body.username, body.display_name, password_hash
|
||||
)
|
||||
except crud.UsernameTaken:
|
||||
raise ApiError(409, "conflict", "Такое имя пользователя уже занято")
|
||||
return user_out(user)
|
||||
|
||||
|
||||
@api.post("/auth/sessions", status_code=201, response_model=SessionOut)
|
||||
async def login(request: Request, session: AsyncSession = Depends(get_session)):
|
||||
"""Вход по Basic: создать сессию и вернуть Bearer-токен."""
|
||||
username, password = parse_basic(request)
|
||||
user = await crud.get_user_by_username(session, username)
|
||||
password_ok = await verify_password_async(
|
||||
password, user.password_hash if user else DUMMY_HASH
|
||||
)
|
||||
if user is None or not password_ok:
|
||||
raise unauthorized(BASIC_CHALLENGE)
|
||||
token = new_token()
|
||||
expires_at = await crud.create_session(
|
||||
session,
|
||||
user.id,
|
||||
hash_token(token),
|
||||
request.app.state.settings.session_ttl_seconds,
|
||||
)
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": format_ts(expires_at),
|
||||
"user": user_out(user),
|
||||
}
|
||||
|
||||
|
||||
@api.delete("/auth/sessions/current", status_code=204)
|
||||
async def logout(
|
||||
request: Request,
|
||||
user: User = Depends(current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Отозвать текущую сессию."""
|
||||
token_hash = hash_token(parse_bearer(request))
|
||||
await crud.delete_session(session, token_hash)
|
||||
await request.app.state.cache.revoke(token_hash)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@api.get("/users/me", response_model=UserOut)
|
||||
async def read_me(user: User = Depends(current_user)):
|
||||
"""Текущий пользователь."""
|
||||
return user_out(user)
|
||||
|
||||
|
||||
@api.post(
|
||||
"/chats",
|
||||
status_code=201,
|
||||
response_model=ChatOut,
|
||||
openapi_extra=body_doc(CreateChatIn),
|
||||
)
|
||||
async def create_chat(
|
||||
request: Request,
|
||||
user: User = Depends(current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Создать чат с участниками."""
|
||||
body = validate_body(CreateChatIn, await read_json_object(request))
|
||||
member_ids = [uuid.UUID(item) for item in body.member_ids]
|
||||
if user.id not in member_ids:
|
||||
raise ApiError(400, "invalid_request", "member_ids должен включать вас самих")
|
||||
try:
|
||||
chat, members = await crud.create_chat(session, body.title, member_ids)
|
||||
except crud.UnknownMember:
|
||||
raise ApiError(
|
||||
400, "invalid_request", "member_ids содержит несуществующего пользователя"
|
||||
)
|
||||
return chat_out(chat, sorted(members))
|
||||
|
||||
|
||||
@api.get("/chats", response_model=ChatPage)
|
||||
async def list_chats(
|
||||
request: Request,
|
||||
user: User = Depends(current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Страница чатов текущего пользователя."""
|
||||
limit = parse_limit(request.query_params.get("limit"))
|
||||
scope = "chats:" + str(user.id)
|
||||
after = position(parse_cursor(request.query_params.get("cursor"), scope))
|
||||
chats, has_more = await crud.list_chats(session, user.id, after, limit)
|
||||
members = await crud.get_member_ids(session, [chat.id for chat in chats])
|
||||
next_cursor = cursor_for(scope, chats[-1]) if has_more and chats else None
|
||||
return {
|
||||
"items": [chat_out(c, members[c.id]) for c in chats],
|
||||
"next_cursor": next_cursor,
|
||||
}
|
||||
|
||||
|
||||
@api.get("/chats/{chat_id}", response_model=ChatOut)
|
||||
async def read_chat(
|
||||
chat_id: str,
|
||||
user: User = Depends(current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Один чат по id."""
|
||||
chat = await open_chat(session, user, chat_id)
|
||||
members = await crud.get_member_ids(session, [chat.id])
|
||||
return chat_out(chat, members[chat.id])
|
||||
|
||||
|
||||
@api.post(
|
||||
"/chats/{chat_id}/messages",
|
||||
status_code=201,
|
||||
response_model=MessageOut,
|
||||
openapi_extra=body_doc(CreateMessageIn),
|
||||
)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
user: User = Depends(current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Отправить сообщение в чат."""
|
||||
chat = await open_chat(session, user, chat_id)
|
||||
body = validate_body(CreateMessageIn, await read_json_object(request))
|
||||
key = parse_idempotency_key(request)
|
||||
try:
|
||||
message = await crud.create_message_idempotent(session, chat.id, user.id, body.text, key)
|
||||
except crud.IdempotencyConflict:
|
||||
raise ApiError(409, "conflict", "Idempotency-Key уже использован с другим сообщением")
|
||||
return message_out(message)
|
||||
|
||||
|
||||
@api.get("/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
user: User = Depends(current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Страница истории чата."""
|
||||
chat = await open_chat(session, user, chat_id)
|
||||
limit = parse_limit(request.query_params.get("limit"))
|
||||
scope = "messages:" + str(chat.id)
|
||||
after = position(parse_cursor(request.query_params.get("cursor"), scope))
|
||||
messages, has_more = await crud.list_messages(session, chat.id, after, limit)
|
||||
next_cursor = cursor_for(scope, messages[-1]) if has_more and messages else None
|
||||
return {"items": [message_out(m) for m in messages], "next_cursor": next_cursor}
|
||||
Reference in New Issue
Block a user