feat: add message history and concurrent writes
This commit is contained in:
+18
-1
@@ -4,7 +4,7 @@ from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
||||
|
||||
from .models import CreateChat, CreateUser
|
||||
from .models import CreateChat, CreateMessage, CreateUser
|
||||
from .store import store
|
||||
|
||||
router = APIRouter()
|
||||
@@ -51,3 +51,20 @@ def list_chats(
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(chat_id: UUID, actor: dict = Depends(current_user)):
|
||||
return store.chat(actor["id"], str(chat_id))
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(chat_id: UUID, body: CreateMessage, actor: dict = Depends(current_user)):
|
||||
return store.create_message(actor["id"], str(chat_id), body.text)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(
|
||||
chat_id: UUID,
|
||||
limit: str = Query("50"),
|
||||
cursor: str | None = Query(None, min_length=1),
|
||||
actor: dict = Depends(current_user),
|
||||
):
|
||||
if not limit.isdecimal() or not 1 <= int(limit) <= 100:
|
||||
raise HTTPException(400)
|
||||
return store.list_messages(actor["id"], str(chat_id), int(limit), cursor)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -119,6 +119,58 @@ class APIContractTests(unittest.TestCase):
|
||||
self.assert_error(*self.call("GET", next_path, actor=bob["id"]), 400)
|
||||
self.assert_error(*self.call("GET", "/api/v1/chats?limit=0", actor=alice["id"]), 400)
|
||||
|
||||
def test_messages_access_validation_and_pages(self):
|
||||
from urllib.parse import quote
|
||||
|
||||
def user(name):
|
||||
status, _, value = self.call("POST", "/api/v1/users", json.dumps({"username": name, "display_name": name}).encode())
|
||||
self.assertEqual(status, 201)
|
||||
return value
|
||||
|
||||
alice, bob, eve = (user(name) for name in ("u3_alice", "u3_bob", "u3_eve"))
|
||||
|
||||
def chat():
|
||||
body = json.dumps({"title": "U3 👋", "member_ids": [alice["id"], bob["id"]]}).encode()
|
||||
status, _, value = self.call("POST", "/api/v1/chats", body, actor=alice["id"])
|
||||
self.assertEqual(status, 201)
|
||||
return value
|
||||
|
||||
first_chat, second_chat = chat(), chat()
|
||||
path = f'/api/v1/chats/{first_chat["id"]}/messages'
|
||||
other_path = f'/api/v1/chats/{second_chat["id"]}/messages'
|
||||
|
||||
def send(actor, body, target=path):
|
||||
return self.call("POST", target, json.dumps(body, ensure_ascii=False).encode(), actor=actor)
|
||||
|
||||
for actor, text in ((alice, "Привет 👋"), (bob, "Ответ Боба"), (alice, "Третье сообщение")):
|
||||
status, _, value = send(actor["id"], {"text": text})
|
||||
self.assertEqual(status, 201)
|
||||
self.assertEqual((value["chat_id"], value["sender_id"], value["text"]), (first_chat["id"], actor["id"], text))
|
||||
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
suffix = "?limit=1" + ("&cursor=" + quote(cursor, safe="") if cursor else "")
|
||||
status, _, page = self.call("GET", path + suffix, actor=bob["id"])
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(len(page["items"]), 1)
|
||||
seen.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual([item["text"] for item in seen], ["Привет 👋", "Ответ Боба", "Третье сообщение"])
|
||||
self.assertEqual(len({item["id"] for item in seen}), 3)
|
||||
self.assertEqual(seen, sorted(seen, key=lambda item: (item["created_at"], item["id"])))
|
||||
|
||||
for body in ({"text": ""}, {"text": " "}, {"text": "a" * 4001}, {"text": "x", "sender_id": eve["id"]}):
|
||||
self.assert_error(*send(alice["id"], body), 400)
|
||||
self.assertEqual(send(alice["id"], {"text": "🌟" * 4000})[0], 201)
|
||||
self.assert_error(*send(eve["id"], {"text": "чужое"}), 404)
|
||||
self.assert_error(*self.call("GET", path, actor=eve["id"]), 404)
|
||||
self.assert_error(*self.call("GET", path + "?limit=0", actor=alice["id"]), 400)
|
||||
self.assert_error(*self.call("GET", path + "?cursor=broken", actor=alice["id"]), 400)
|
||||
self.assert_error(*self.call("GET", other_path + "?cursor=" + quote(self.call("GET", path + "?limit=1", actor=alice["id"])[2]["next_cursor"], safe=""), actor=alice["id"]), 400)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""One 10-client / 100-message exercise of the in-memory store."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import unittest
|
||||
from urllib.parse import quote
|
||||
|
||||
import test_api
|
||||
|
||||
|
||||
class ConcurrentMessagesTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
test_api.APIContractTests.setUpClass()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
test_api.APIContractTests.tearDownClass()
|
||||
|
||||
def test_100_messages_from_10_clients(self):
|
||||
call = test_api.APIContractTests.call
|
||||
status, _, actor = call("POST", "/api/v1/users", b'{"username":"u3_concurrent","display_name":"Load"}')
|
||||
self.assertEqual(status, 201)
|
||||
body = json.dumps({"title": "Concurrent", "member_ids": [actor["id"]]}).encode()
|
||||
status, _, chat = call("POST", "/api/v1/chats", body, actor=actor["id"])
|
||||
self.assertEqual(status, 201)
|
||||
path = f'/api/v1/chats/{chat["id"]}/messages'
|
||||
|
||||
def send(index):
|
||||
body = json.dumps({"text": f"client-{index // 10}:message-{index}"}).encode()
|
||||
status, _, result = call("POST", path, body, actor=actor["id"])
|
||||
return status, result
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(send, range(100)))
|
||||
self.assertTrue(all(status == 201 for status, _ in responses))
|
||||
expected = {result["id"]: result["text"] for _, result in responses}
|
||||
self.assertEqual(len(expected), 100)
|
||||
|
||||
seen = {}
|
||||
cursor = None
|
||||
while True:
|
||||
suffix = "?limit=17" + ("&cursor=" + quote(cursor, safe="") if cursor else "")
|
||||
status, _, page = call("GET", path + suffix, actor=actor["id"])
|
||||
self.assertEqual(status, 200)
|
||||
for item in page["items"]:
|
||||
self.assertNotIn(item["id"], seen)
|
||||
seen[item["id"]] = item["text"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(seen, expected)
|
||||
print("Concurrency evidence: 10 clients, 100 writes, 100 unique messages read")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user