Files
mtusi2026lab4/app/routes.py
T

301 lines
11 KiB
Python

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, payload_too_large, unauthorized, unavailable, unsupported_media_type
from .images import MAX_UPLOAD_BYTES, inspect_image
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.
CreateMessage always includes attachment_ids, so a missing field and [] are the same body.
"""
canonical = json.dumps(payload.model_dump(), sort_keys=True, separators=(',', ':'), ensure_ascii=False)
return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
def _filename(value: Optional[str]) -> str:
if value is None or not value.strip() or len(value) > 255:
raise invalid_request('Некорректное filename')
if any(ord(char) < 32 or ord(char) == 127 or char in '/\\' for char in value):
raise invalid_request('Некорректное filename')
return value
def _declared_image_type(value: Optional[str]) -> str:
if not value:
raise unsupported_media_type('Требуется Content-Type image/png или image/jpeg')
media = value.split(';', 1)[0].strip().lower()
if media not in ('image/png', 'image/jpeg'):
raise unsupported_media_type('Требуется Content-Type image/png или image/jpeg')
return media
async def _read_upload(request: Request) -> bytes:
declared = request.headers.get('content-length')
if declared is not None:
try:
size = int(declared)
except ValueError:
raise invalid_request('Некорректный Content-Length') from None
if size > MAX_UPLOAD_BYTES:
raise payload_too_large('Файл больше 10 МиБ')
buf = bytearray()
async for chunk in request.stream():
if len(buf) + len(chunk) > MAX_UPLOAD_BYTES:
raise payload_too_large('Файл больше 10 МиБ')
buf.extend(chunk)
return bytes(buf)
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,
payload.attachment_ids,
path='/api/v1/chats/%s/messages' % chat.id,
key=key,
request_hash=_request_hash(payload),
)
return JSONResponse(message.to_dict(), status_code=201)
@router.post('/api/v1/chats/{chat_id}/attachments')
async def upload_attachment(
chat_id: str,
request: Request,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
chat = await _member_chat(store, chat_id, actor)
filename = _filename(request.query_params.get('filename'))
declared = _declared_image_type(request.headers.get('content-type'))
data = await _read_upload(request)
actual = inspect_image(data)
if actual != declared:
raise unsupported_media_type('Содержимое не соответствует Content-Type')
attachment = await store.create_attachment(
chat.id,
actor.id,
filename,
actual,
data,
hashlib.sha256(data).hexdigest(),
)
return JSONResponse(attachment.to_dict(), status_code=201)
def _variant(request: Request) -> str:
raw = request.query_params.get('variant')
variant = 'original' if raw is None else raw
if variant not in ('original', 'thumbnail', 'crop', 'optimized'):
raise invalid_request('Некорректный variant')
return variant
@router.get('/api/v1/attachments/{attachment_id}')
async def show_attachment(
attachment_id: str,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
attachment = await store.find_attachment(attachment_id, actor.id)
if attachment is None:
raise not_found('Вложение не найдено')
return JSONResponse(attachment.to_dict())
@router.get('/api/v1/attachments/{attachment_id}/content')
async def download_attachment(
attachment_id: str,
request: Request,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> Response:
variant = _variant(request)
if variant != 'original':
attachment = await store.find_attachment(attachment_id, actor.id)
if attachment is None:
raise not_found('Вложение не найдено')
raise not_found('Вариант не найден')
found = await store.read_original(attachment_id, actor.id)
if found is None:
raise not_found('Вложение не найдено')
content_type, body = found
return Response(content=body, media_type=content_type)
@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))