feat: add message history and concurrent writes

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-01 21:27:53 +03:00
parent ac739713b3
commit 55ec45cc3d
4 changed files with 154 additions and 1 deletions
+27
View File
@@ -44,6 +44,7 @@ class Store:
self.users: dict[str, dict] = {}
self.usernames: dict[str, str] = {}
self.chats: dict[str, dict] = {}
self.messages: dict[str, list[dict]] = {}
def register(self, username: str, display_name: str) -> dict:
with self.lock:
@@ -67,6 +68,7 @@ class Store:
raise HTTPException(400)
chat = {"id": str(uuid4()), "title": title, "member_ids": member_ids.copy(), "created_at": now()}
self.chats[chat["id"]] = chat
self.messages[chat["id"]] = []
return chat
def chat(self, actor_id: str, chat_id: str) -> dict:
@@ -89,5 +91,30 @@ class Store:
next_cursor = encode_cursor(f"chats:{actor_id}", page[-1]) if len(items) > limit else None
return {"items": page, "next_cursor": next_cursor}
def create_message(self, actor_id: str, chat_id: str, text: str) -> dict:
with self.lock:
chat = self.chats.get(chat_id)
if chat is None or actor_id not in chat["member_ids"]:
raise HTTPException(404)
message = {
"id": str(uuid4()), "chat_id": chat_id, "sender_id": actor_id,
"text": text, "created_at": now(),
}
self.messages[chat_id].append(message)
return message
def list_messages(self, actor_id: str, chat_id: str, limit: int, cursor: str | None) -> dict:
with self.lock:
chat = self.chats.get(chat_id)
if chat is None or actor_id not in chat["member_ids"]:
raise HTTPException(404)
after = decode_cursor(cursor, f"messages:{chat_id}")
items = sorted(self.messages[chat_id], key=lambda item: (item["created_at"], item["id"]))
if after is not None:
items = [item for item in items if (item["created_at"], item["id"]) > after]
page = items[:limit]
next_cursor = encode_cursor(f"messages:{chat_id}", page[-1]) if len(items) > limit else None
return {"items": page, "next_cursor": next_cursor}
store = Store()