""" In-memory хранилище для Lab1. Никакой БД — только dict/list в памяти процесса. Данные пропадают при перезапуске, это ожидаемо для уровня 3 этой лабы. Порядок истории задаётся монотонным счётчиком _seq. UUID случайны и не сохраняют порядок создания, а created_at может совпадать у нескольких записей. _seq не попадает в API-ответы: это внутренний ключ порядка и cursor. Для эксперимента уровня 5 используется message_index_by_seq: chat_id -> {message_seq -> position_in_chat_messages}. Он позволяет находить начало следующей страницы истории по cursor за O(1), вместо линейного обхода списка сообщений O(N). Цена оптимизации — дополнительная память O(N). """ import base64 import itertools import threading import uuid from datetime import datetime, timezone from typing import Dict, List, Optional, Tuple def now_iso() -> str: return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") def _strip_seq(obj: dict) -> dict: """Убирает внутреннее поле _seq перед отдачей объекта наружу через API.""" return {key: value for key, value in obj.items() if key != "_seq"} def _encode_cursor(seq: int) -> str: return base64.urlsafe_b64encode(str(seq).encode()).decode() def _decode_cursor(cursor: str) -> Optional[int]: try: return int(base64.urlsafe_b64decode(cursor.encode()).decode()) except Exception: return None def _encode_message_cursor(chat_id: str, seq: int) -> str: raw = f"{chat_id}|{seq}" return base64.urlsafe_b64encode(raw.encode()).decode() def _decode_message_cursor(cursor: str) -> Optional[Tuple[str, int]]: try: raw = base64.urlsafe_b64decode(cursor.encode()).decode() chat_id, seq = raw.split("|", 1) return chat_id, int(seq) except Exception: return None class Storage: def __init__(self) -> None: self._lock = threading.Lock() self._seq = itertools.count(1) self.users: Dict[str, dict] = {} self.usernames: Dict[str, str] = {} self.chats: Dict[str, dict] = {} self.chat_order: List[str] = [] self.messages: Dict[str, List[dict]] = {} self.message_index_by_seq: Dict[str, Dict[int, int]] = {} # Пользователи def create_user(self, username: str, display_name: str) -> Optional[dict]: with self._lock: if username in self.usernames: return None user_id = str(uuid.uuid4()) user = { "id": user_id, "username": username, "display_name": display_name, "created_at": now_iso(), } self.users[user_id] = user self.usernames[username] = user_id return user def get_user(self, user_id: str) -> Optional[dict]: return self.users.get(user_id) # Чаты def create_chat(self, title: str, member_ids: List[str]) -> dict: with self._lock: chat_id = str(uuid.uuid4()) chat = { "id": chat_id, "title": title, "member_ids": list(member_ids), "created_at": now_iso(), "_seq": next(self._seq), } self.chats[chat_id] = chat self.chat_order.append(chat_id) self.messages[chat_id] = [] self.message_index_by_seq[chat_id] = {} return _strip_seq(chat) def get_chat(self, chat_id: str) -> Optional[dict]: chat = self.chats.get(chat_id) return _strip_seq(chat) if chat else None def list_chats_for_user( self, user_id: str, limit: int, cursor: Optional[str], ) -> Tuple[List[dict], Optional[str]]: visible = sorted( ( self.chats[chat_id] for chat_id in self.chat_order if user_id in self.chats[chat_id]["member_ids"] ), key=lambda chat: chat["_seq"], ) start_idx = 0 if cursor is not None: last_seq = _decode_cursor(cursor) if last_seq is None: raise ValueError("bad cursor") start_idx = next( ( index for index, chat in enumerate(visible) if chat["_seq"] > last_seq ), len(visible), ) window = visible[start_idx:start_idx + limit + 1] has_more = len(window) > limit page = window[:limit] next_cursor = ( _encode_cursor(page[-1]["_seq"]) if has_more and page else None ) return [_strip_seq(chat) for chat in page], next_cursor # ---------- Сообщения ---------- def create_message(self, chat_id: str, sender_id: str, text: str) -> dict: with self._lock: msg_id = str(uuid.uuid4()) msg = { "id": msg_id, "chat_id": chat_id, "sender_id": sender_id, "text": text, "created_at": now_iso(), "_seq": next(self._seq), } chat_messages = self.messages[chat_id] position = len(chat_messages) chat_messages.append(msg) self.message_index_by_seq[chat_id][msg["_seq"]] = position return _strip_seq(msg) def list_messages( self, chat_id: str, limit: int, cursor: Optional[str], ) -> Tuple[List[dict], Optional[str]]: all_msgs = self.messages.get(chat_id, []) start_idx = 0 if cursor is not None: decoded = _decode_message_cursor(cursor) if decoded is None: raise ValueError("bad cursor") cur_chat_id, last_seq = decoded if cur_chat_id != chat_id: raise ValueError("cursor belongs to another chat") position = self.message_index_by_seq.get(chat_id, {}).get(last_seq) if position is None: raise ValueError("unknown cursor sequence") start_idx = position + 1 window = all_msgs[start_idx:start_idx + limit + 1] has_more = len(window) > limit page = window[:limit] next_cursor = ( _encode_message_cursor(chat_id, page[-1]["_seq"]) if has_more and page else None ) return [_strip_seq(message) for message in page], next_cursor # Диагностика уровня 5 def counts(self) -> dict: with self._lock: return { "users": len(self.users), "chats": len(self.chats), "messages": sum( len(chat_messages) for chat_messages in self.messages.values() ), } storage = Storage()