import hashlib import json import logging import os import re import tempfile import uuid from typing import BinaryIO, Optional, Sequence, Tuple, 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 .broker import BrokerDown from .fault import consume_fault from .outbox import publish_job from .drain import draining from .errors import ( conflict, invalid_request, not_found, payload_too_large, unauthorized, unavailable, unsupported_media_type, ) from .images import INSPECT_PREFIX, MAX_UPLOAD_BYTES, inspect_image, inspect_prefix from .pagination import encode_cursor, parse_page from .schemas import CreateChat, CreateMessage, CreateUser from .store import Chat, Store, User # Bytes kept in RAM before SpooledTemporaryFile rolls over to an ephemeral file. # The original is never persisted on the API volume; the spool dies with the request. _SPOOL_RAM = 64 * 1024 logger = logging.getLogger('messenger') 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 _spool_upload(request: Request, declared: str) -> Tuple[BinaryIO, int, str, str]: """Stream the body into a size-capped spool, hash it, and inspect the header. Returns (spool, size, sha256, sniffed_type). The caller must close the spool. One request never holds more than INSPECT_PREFIX plus _SPOOL_RAM in Python heap; the rest, if any, is an ephemeral tempfile deleted in finally. """ length = request.headers.get('content-length') if length is not None: try: size = int(length) except ValueError: raise invalid_request('Некорректный Content-Length') from None if size > MAX_UPLOAD_BYTES: raise payload_too_large('Файл больше 10 МиБ') spool = tempfile.SpooledTemporaryFile(max_size=_SPOOL_RAM) hasher = hashlib.sha256() head = bytearray() total = 0 sniffed: Optional[str] = None try: async for chunk in request.stream(): if not chunk: continue if total + len(chunk) > MAX_UPLOAD_BYTES: raise payload_too_large('Файл больше 10 МиБ') hasher.update(chunk) spool.write(chunk) total += len(chunk) if len(head) < INSPECT_PREFIX: head.extend(chunk[: INSPECT_PREFIX - len(head)]) if sniffed is None and len(head) >= 24: sniffed = inspect_prefix(bytes(head), complete=False) if sniffed is not None and sniffed != declared: raise unsupported_media_type('Содержимое не соответствует Content-Type') if sniffed is None: sniffed = inspect_image(bytes(head)) if sniffed != declared: raise unsupported_media_type('Содержимое не соответствует Content-Type') spool.seek(0) return spool, total, hasher.hexdigest(), sniffed except BaseException: spool.close() raise 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(request: Request, store: Store = Depends(get_store)) -> JSONResponse: if draining.is_set(): raise unavailable('Реплика завершает работу') await store.ready() try: await request.app.state.broker.ready() except BrokerDown: raise unavailable('Очередь недоступна') from None 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')) spool = None try: spool, size, digest, actual = await _spool_upload(request, declared) queued = await store.create_attachment( chat.id, actor.id, filename, actual, spool, size, digest, ) finally: if spool is not None: spool.close() # The row is committed. A crash before the confirm leaves it for the outbox relay. if await consume_fault(store.pool, 'commit-before-publish'): logger.warning('fault commit-before-publish: exiting before publish of %s', queued.attachment.id) logging.shutdown() os._exit(75) try: await publish_job(store.pool, request.app.state.broker, queued.job_id) except BrokerDown: logger.warning('upload %s is committed and waits in the outbox', queued.attachment.id) return JSONResponse(queued.attachment.to_dict(), status_code=202) 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) attachment = await store.find_attachment(attachment_id, actor.id) if attachment is None: raise not_found('Вложение не найдено') if attachment.status != 'ready': raise conflict('Вложение ещё не готово') found = await store.read_content(attachment_id, actor.id, variant) if found is None: raise not_found('Вариант не найден' if variant != 'original' else 'Вложение не найдено') 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))