Files
mtusi2026lab2/app/storage.py
T

242 lines
8.9 KiB
Python

from __future__ import annotations
import asyncio
import base64
import json
import uuid
from app.schemas import (
ChatResponse,
MessageResponse,
UserResponse,
now_utc_iso,
)
class StorageError(Exception):
pass
class InvalidRequestError(StorageError):
pass
class NotFoundError(StorageError):
pass
class ConflictError(StorageError):
pass
class UnauthorizedError(StorageError):
pass
def encode_cursor(data: dict) -> str:
raw = json.dumps(data, separators=(",", ":")).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("utf-8").rstrip("=")
def decode_cursor(cursor_str: str) -> dict:
if not isinstance(cursor_str, str) or not cursor_str.strip():
raise InvalidRequestError("Некорректный курсор")
try:
padded = cursor_str + "=" * (-len(cursor_str) % 4)
raw = base64.urlsafe_b64decode(padded.encode("utf-8"))
data = json.loads(raw.decode("utf-8"))
if not isinstance(data, dict):
raise InvalidRequestError("Некорректный курсор")
return data
except InvalidRequestError:
raise
except Exception as exc:
raise InvalidRequestError("Некорректный курсор") from exc
class InMemoryStorage:
def __init__(self) -> None:
self._lock = asyncio.Lock()
self._users_by_id: dict[str, UserResponse] = {}
self._users_by_username: dict[str, UserResponse] = {}
self._chats_by_id: dict[str, ChatResponse] = {}
self._messages_by_chat: dict[str, list[MessageResponse]] = {}
async def create_user(self, username: str, display_name: str) -> UserResponse:
async with self._lock:
if username in self._users_by_username:
raise ConflictError("Имя пользователя уже занято")
user_id = str(uuid.uuid4())
created_at = now_utc_iso()
user = UserResponse(
id=user_id,
username=username,
display_name=display_name,
created_at=created_at,
)
self._users_by_id[user_id] = user
self._users_by_username[username] = user
return user
async def get_user_by_id(self, user_id: str) -> UserResponse:
async with self._lock:
user = self._users_by_id.get(user_id)
if not user:
raise UnauthorizedError("Пользователь не найден или не авторизован")
return user
async def create_chat(
self, caller_id: str, title: str, member_ids: list[str]
) -> ChatResponse:
async with self._lock:
# Вызывающий обязан быть в списке участников
if caller_id not in member_ids:
raise InvalidRequestError("Создатель чата должен быть в списке участников member_ids")
# Все участники обязаны существовать
for mid in member_ids:
if mid not in self._users_by_id:
raise InvalidRequestError(f"Пользователь {mid} не существует")
chat_id = str(uuid.uuid4())
created_at = now_utc_iso()
chat = ChatResponse(
id=chat_id,
title=title,
member_ids=list(member_ids),
created_at=created_at,
)
self._chats_by_id[chat_id] = chat
self._messages_by_chat[chat_id] = []
return chat
async def get_chat(self, caller_id: str, chat_id: str) -> ChatResponse:
async with self._lock:
chat = self._chats_by_id.get(chat_id)
# Если чата нет или вызывающий не участник — строго 404
if not chat or caller_id not in chat.member_ids:
raise NotFoundError("Чат не найден")
return chat
async def list_chats(
self, caller_id: str, limit: int = 50, cursor: str | None = None
) -> tuple[list[ChatResponse], str | None]:
async with self._lock:
# Фильтруем только чаты, где пользователь — участник
user_chats = [
chat
for chat in self._chats_by_id.values()
if caller_id in chat.member_ids
]
# Сортировка по (created_at, id) по возрастанию
user_chats.sort(key=lambda x: (x.created_at, x.id))
start_idx = 0
if cursor is not None:
c_data = decode_cursor(cursor)
if c_data.get("type") != "chats":
raise InvalidRequestError("Курсор недействителен для списка чатов")
c_created = c_data.get("created_at")
c_id = c_data.get("id")
if (
not isinstance(c_created, str)
or not isinstance(c_id, str)
or not c_created.strip()
or not c_id.strip()
):
raise InvalidRequestError("Поврежденный курсор")
# Ищем первый элемент, строго больший курсора
start_idx = len(user_chats)
for idx, chat in enumerate(user_chats):
if (chat.created_at, chat.id) > (c_created, c_id):
start_idx = idx
break
items = user_chats[start_idx : start_idx + limit]
has_next = (start_idx + limit) < len(user_chats)
next_cursor = None
if has_next and items:
last = items[-1]
next_cursor = encode_cursor(
{"type": "chats", "created_at": last.created_at, "id": last.id}
)
return items, next_cursor
async def create_message(
self, caller_id: str, chat_id: str, text: str
) -> MessageResponse:
async with self._lock:
chat = self._chats_by_id.get(chat_id)
if not chat or caller_id not in chat.member_ids:
raise NotFoundError("Чат не найден")
message_id = str(uuid.uuid4())
created_at = now_utc_iso()
msg = MessageResponse(
id=message_id,
chat_id=chat_id,
sender_id=caller_id,
text=text,
created_at=created_at,
)
self._messages_by_chat[chat_id].append(msg)
return msg
async def list_messages(
self, caller_id: str, chat_id: str, limit: int = 50, cursor: str | None = None
) -> tuple[list[MessageResponse], str | None]:
async with self._lock:
chat = self._chats_by_id.get(chat_id)
if not chat or caller_id not in chat.member_ids:
raise NotFoundError("Чат не найден")
all_msgs = self._messages_by_chat.get(chat_id, [])
# Сортировка по (created_at, id) по возрастанию
sorted_msgs = sorted(all_msgs, key=lambda x: (x.created_at, x.id))
start_idx = 0
if cursor is not None:
c_data = decode_cursor(cursor)
if c_data.get("type") != "messages" or c_data.get("chat_id") != chat_id:
raise InvalidRequestError(
"Курсор принадлежит другому чату или недействителен"
)
c_created = c_data.get("created_at")
c_id = c_data.get("id")
if (
not isinstance(c_created, str)
or not isinstance(c_id, str)
or not c_created.strip()
or not c_id.strip()
):
raise InvalidRequestError("Поврежденный курсор")
start_idx = len(sorted_msgs)
for idx, msg in enumerate(sorted_msgs):
if (msg.created_at, msg.id) > (c_created, c_id):
start_idx = idx
break
items = sorted_msgs[start_idx : start_idx + limit]
has_next = (start_idx + limit) < len(sorted_msgs)
next_cursor = None
if has_next and items:
last = items[-1]
next_cursor = encode_cursor(
{
"type": "messages",
"chat_id": chat_id,
"created_at": last.created_at,
"id": last.id,
}
)
return items, next_cursor
# Глобальный экземпляр хранилища для процесса
storage = InMemoryStorage()