forked from mtusi2026/mtusi2026lab2
89 lines
3.3 KiB
Python
89 lines
3.3 KiB
Python
"""Потокобезопасное in-memory хранилище пользователей, чатов и сообщений."""
|
||
import threading
|
||
import uuid
|
||
from datetime import datetime, timezone
|
||
from typing import Any
|
||
|
||
|
||
def utc_now() -> str:
|
||
"""RFC 3339 UTC с суффиксом Z, секунды — как в примерах контракта."""
|
||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
|
||
|
||
def new_id() -> str:
|
||
return str(uuid.uuid4())
|
||
|
||
|
||
class Store:
|
||
"""Все данные живут в памяти одного процесса и исчезают при рестарте."""
|
||
|
||
def __init__(self) -> None:
|
||
self._lock = threading.RLock()
|
||
self.users: dict[str, dict[str, Any]] = {}
|
||
self.usernames: dict[str, str] = {}
|
||
self.chats: dict[str, dict[str, Any]] = {}
|
||
self.messages: dict[str, list[dict[str, Any]]] = {}
|
||
|
||
# --- пользователи -----------------------------------------------------
|
||
def create_user(self, username: str, display_name: str) -> dict[str, Any]:
|
||
with self._lock:
|
||
if username in self.usernames:
|
||
return None # сигнал конфликта
|
||
user = {
|
||
"id": new_id(),
|
||
"username": username,
|
||
"display_name": display_name,
|
||
"created_at": utc_now(),
|
||
}
|
||
self.users[user["id"]] = user
|
||
self.usernames[username] = user["id"]
|
||
return dict(user)
|
||
|
||
def get_user(self, user_id: str) -> dict[str, Any] | None:
|
||
with self._lock:
|
||
user = self.users.get(user_id)
|
||
return dict(user) if user else None
|
||
|
||
# --- чаты -------------------------------------------------------------
|
||
def create_chat(self, title: str, member_ids: list[str]) -> dict[str, Any]:
|
||
with self._lock:
|
||
chat = {
|
||
"id": new_id(),
|
||
"title": title,
|
||
"member_ids": list(member_ids),
|
||
"created_at": utc_now(),
|
||
}
|
||
self.chats[chat["id"]] = chat
|
||
self.messages[chat["id"]] = []
|
||
return dict(chat)
|
||
|
||
def get_chat(self, chat_id: str) -> dict[str, Any] | None:
|
||
with self._lock:
|
||
chat = self.chats.get(chat_id)
|
||
return dict(chat) if chat else None
|
||
|
||
def list_chats_for(self, user_id: str) -> list[dict[str, Any]]:
|
||
with self._lock:
|
||
items = [dict(c) for c in self.chats.values() if user_id in c["member_ids"]]
|
||
items.sort(key=lambda c: (c["created_at"], c["id"]))
|
||
return items
|
||
|
||
# --- сообщения --------------------------------------------------------
|
||
def add_message(self, chat_id: str, sender_id: str, text: str) -> dict[str, Any]:
|
||
with self._lock:
|
||
message = {
|
||
"id": new_id(),
|
||
"chat_id": chat_id,
|
||
"sender_id": sender_id,
|
||
"text": text,
|
||
"created_at": utc_now(),
|
||
}
|
||
self.messages.setdefault(chat_id, []).append(message)
|
||
return dict(message)
|
||
|
||
def list_messages(self, chat_id: str) -> list[dict[str, Any]]:
|
||
with self._lock:
|
||
items = [dict(m) for m in self.messages.get(chat_id, [])]
|
||
items.sort(key=lambda m: (m["created_at"], m["id"]))
|
||
return items
|