import hashlib import json import re import uuid from typing import Optional, Sequence, Type, TypeVar from fastapi import APIRouter, Depends, Request from fastapi.responses import JSONResponse from pydantic import BaseModel, ValidationError from starlette.responses import Response from .auth import BASIC_CHALLENGE, BEARER_CHALLENGE, parse_basic, parse_bearer from .drain import draining from .errors import invalid_request, not_found, unauthorized, unavailable from .pagination import encode_cursor, parse_page from .schemas import CreateChat, CreateMessage, CreateUser from .store import Chat, Store, User router = APIRouter() Body = TypeVar('Body', bound=BaseModel) _IDEMPOTENCY_KEY = re.compile(r'[A-Za-z0-9._:-]{1,128}') async def get_store(request: Request) -> Store: return request.app.state.store async def current_user(request: Request) -> User: """Bearer only. X-User-Id is ignored and does not identify anyone.""" token = parse_bearer(request.headers.get('Authorization', '')) if token is None: raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE) user = await request.app.state.store.user_for_token(token) if user is None: raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE) return user async def read_body(request: Request, model: Type[Body]) -> Body: try: payload = json.loads(await request.body()) except (UnicodeDecodeError, ValueError): raise invalid_request('Тело запроса не является корректным JSON') from None if not isinstance(payload, dict): raise invalid_request('Тело запроса должно быть JSON-объектом') try: return model.model_validate(payload) except ValidationError: raise invalid_request('Тело запроса не соответствует контракту') from None def _request_hash(payload: BaseModel) -> str: """Key order in the client JSON does not matter: the validated body is re-serialized canonically.""" canonical = json.dumps(payload.model_dump(), sort_keys=True, separators=(',', ':'), ensure_ascii=False) return hashlib.sha256(canonical.encode('utf-8')).hexdigest() async def _member_chat(store: Store, chat_id: str, actor: User) -> Chat: try: canonical = str(uuid.UUID(chat_id)) except ValueError: raise invalid_request('Некорректный chat_id') from None chat = await store.find_chat(canonical, actor.id) if chat is None: raise not_found('Чат не найден') return chat def _page(items: Sequence, has_more: bool, scope: str) -> dict: cursor: Optional[str] = None if has_more and items: cursor = encode_cursor(scope, (items[-1].created_at, items[-1].id)) return {'items': [item.to_dict() for item in items], 'next_cursor': cursor} @router.get('/health/live') async def liveness() -> JSONResponse: return JSONResponse({'status': 'ok'}) @router.get('/health/ready') async def readiness(store: Store = Depends(get_store)) -> JSONResponse: if draining.is_set(): raise unavailable('Реплика завершает работу') await store.ready() return JSONResponse({'status': 'ok'}) @router.post('/api/v1/users') async def register_user(request: Request, store: Store = Depends(get_store)) -> JSONResponse: payload = await read_body(request, CreateUser) user = await store.create_user(payload.username, payload.display_name, payload.password) return JSONResponse(user.to_dict(), status_code=201) @router.post('/api/v1/auth/sessions') async def create_session(request: Request, store: Store = Depends(get_store)) -> JSONResponse: parsed = parse_basic(request.headers.get('Authorization', '')) if parsed is None: raise unauthorized('Неверные учётные данные', BASIC_CHALLENGE) user = await store.authenticate(*parsed) if user is None: raise unauthorized('Неверные учётные данные', BASIC_CHALLENGE) token, expires_at = await store.create_session(user.id) body = { 'token': token, 'token_type': 'Bearer', 'expires_at': expires_at, 'user': user.to_dict(), } return JSONResponse(body, status_code=201) @router.delete('/api/v1/auth/sessions/current') async def revoke_session(request: Request, actor: User = Depends(current_user)) -> Response: token = parse_bearer(request.headers.get('Authorization', '')) if token is None or not await request.app.state.store.revoke_session(token): raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE) return Response(status_code=204) @router.get('/api/v1/users/me') async def show_current_user(actor: User = Depends(current_user)) -> JSONResponse: return JSONResponse(actor.to_dict()) @router.post('/api/v1/chats') async def create_chat( request: Request, actor: User = Depends(current_user), store: Store = Depends(get_store), ) -> JSONResponse: payload = await read_body(request, CreateChat) if actor.id not in payload.member_ids: raise invalid_request('Создатель чата должен быть указан в member_ids') chat = await store.create_chat(payload.title, payload.member_ids) return JSONResponse(chat.to_dict(), status_code=201) @router.get('/api/v1/chats') async def list_chats( request: Request, actor: User = Depends(current_user), store: Store = Depends(get_store), ) -> JSONResponse: scope = 'chats:' + actor.id limit, after = parse_page(request.query_params, scope) chats, has_more = await store.list_chats(actor.id, limit, after) return JSONResponse(_page(chats, has_more, scope)) @router.get('/api/v1/chats/{chat_id}') async def show_chat( chat_id: str, actor: User = Depends(current_user), store: Store = Depends(get_store), ) -> JSONResponse: return JSONResponse((await _member_chat(store, chat_id, actor)).to_dict()) @router.post('/api/v1/chats/{chat_id}/messages') async def send_message( chat_id: str, request: Request, actor: User = Depends(current_user), store: Store = Depends(get_store), ) -> JSONResponse: chat = await _member_chat(store, chat_id, actor) payload = await read_body(request, CreateMessage) key = request.headers.get('Idempotency-Key') if key is None or not _IDEMPOTENCY_KEY.fullmatch(key): raise invalid_request('Требуется корректный Idempotency-Key') message = await store.add_message( chat.id, actor.id, payload.text, path='/api/v1/chats/%s/messages' % chat.id, key=key, request_hash=_request_hash(payload), ) return JSONResponse(message.to_dict(), status_code=201) @router.get('/api/v1/chats/{chat_id}/messages') async def list_messages( chat_id: str, request: Request, actor: User = Depends(current_user), store: Store = Depends(get_store), ) -> JSONResponse: chat = await _member_chat(store, chat_id, actor) scope = 'messages:' + chat.id limit, after = parse_page(request.query_params, scope) messages, has_more = await store.list_messages(chat.id, limit, after) return JSONResponse(_page(messages, has_more, scope))