diff --git a/src/api.py b/src/api.py index 9cfe73f..dcbff9b 100644 --- a/src/api.py +++ b/src/api.py @@ -1,8 +1,11 @@ -"""HTTP routes; domain operations are added in subsequent units.""" +"""Lab 1 HTTP routes.""" -from fastapi import APIRouter +from uuid import UUID -from .models import CreateUser +from fastapi import APIRouter, Depends, Header, HTTPException, Query + +from .models import CreateChat, CreateUser +from .store import store router = APIRouter() @@ -19,4 +22,32 @@ def ready(): @router.post("/api/v1/users", status_code=201) def register_user(body: CreateUser): - raise NotImplementedError("User registration is implemented in U2") + return store.register(body.username, body.display_name) + + +def current_user(x_user_id: str | None = Header(None, alias="X-User-Id")) -> dict: + return store.user(x_user_id) + + +@router.get("/api/v1/users/me") +def user_me(actor: dict = Depends(current_user)): + return actor + + +@router.post("/api/v1/chats", status_code=201) +def create_chat(body: CreateChat, actor: dict = Depends(current_user)): + return store.create_chat(actor["id"], body.title, body.member_ids) + + +@router.get("/api/v1/chats") +def list_chats( + 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_chats(actor["id"], int(limit), cursor) + + +@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)) diff --git a/src/models.py b/src/models.py index 7937880..1d76f31 100644 --- a/src/models.py +++ b/src/models.py @@ -35,11 +35,10 @@ class CreateChat(StrictBody): @field_validator("member_ids") @classmethod def valid_members(cls, value: list[str]) -> list[str]: - if len(set(value)) != len(value): + members = [str(UUID(member_id)) for member_id in value] + if len(set(members)) != len(members): raise ValueError("duplicate member") - for member_id in value: - UUID(member_id) - return value + return members class CreateMessage(StrictBody): diff --git a/src/store.py b/src/store.py new file mode 100644 index 0000000..850d128 --- /dev/null +++ b/src/store.py @@ -0,0 +1,93 @@ +"""Process-local state for lab 1.""" + +import base64 +import binascii +import json +from datetime import datetime, timezone +from threading import Lock +from uuid import UUID, uuid4 + +from fastapi import HTTPException + + +def now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") + + +def encode_cursor(resource: str, item: dict) -> str: + value = [resource, item["created_at"], item["id"]] + return base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":")).encode()).decode().rstrip("=") + + +def decode_cursor(cursor: str | None, resource: str) -> tuple[str, str] | None: + if cursor is None: + return None + try: + raw = base64.b64decode(cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True) + value = json.loads(raw) + if not isinstance(value, list) or len(value) != 3 or value[0] != resource: + raise ValueError + timestamp, item_id = value[1:] + if not isinstance(timestamp, str) or not timestamp.endswith("Z") or not isinstance(item_id, str): + raise ValueError + datetime.fromisoformat(timestamp[:-1] + "+00:00") + UUID(item_id) + return timestamp, item_id + except (binascii.Error, UnicodeError, ValueError, TypeError): + raise HTTPException(400) from None + + +class Store: + def __init__(self): + # ponytail: one process-wide lock; use narrower locks if measured contention demands it. + self.lock = Lock() + self.users: dict[str, dict] = {} + self.usernames: dict[str, str] = {} + self.chats: dict[str, dict] = {} + + def register(self, username: str, display_name: str) -> dict: + with self.lock: + if username in self.usernames: + raise HTTPException(409) + user = {"id": str(uuid4()), "username": username, "display_name": display_name, "created_at": now()} + self.users[user["id"]] = user + self.usernames[username] = user["id"] + return user + + def user(self, user_id: str | None) -> dict: + with self.lock: + user = self.users.get(user_id or "") + if user is None: + raise HTTPException(401) + return user + + def create_chat(self, actor_id: str, title: str, member_ids: list[str]) -> dict: + with self.lock: + if actor_id not in member_ids or any(member_id not in self.users for member_id in member_ids): + raise HTTPException(400) + chat = {"id": str(uuid4()), "title": title, "member_ids": member_ids.copy(), "created_at": now()} + self.chats[chat["id"]] = chat + return chat + + def chat(self, actor_id: str, chat_id: 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) + return chat + + def list_chats(self, actor_id: str, limit: int, cursor: str | None) -> dict: + after = decode_cursor(cursor, f"chats:{actor_id}") + with self.lock: + items = sorted( + (chat for chat in self.chats.values() if actor_id in chat["member_ids"]), + key=lambda chat: (chat["created_at"], chat["id"]), + ) + if after is not None: + items = [chat for chat in items if (chat["created_at"], chat["id"]) > after] + page = items[:limit] + next_cursor = encode_cursor(f"chats:{actor_id}", page[-1]) if len(items) > limit else None + return {"items": page, "next_cursor": next_cursor} + + +store = Store() diff --git a/student-tests/test_api.py b/student-tests/test_api.py index 80b668f..4ed01da 100644 --- a/student-tests/test_api.py +++ b/student-tests/test_api.py @@ -42,8 +42,10 @@ class APIContractTests(unittest.TestCase): cls.thread.join(timeout=5) @classmethod - def call(cls, method, path, body=None, content_type="application/json"): + def call(cls, method, path, body=None, content_type="application/json", actor=None): headers = {"Content-Type": content_type} if body is not None else {} + if actor is not None: + headers["X-User-Id"] = actor request = Request(cls.url + path, data=body, headers=headers, method=method) try: response = urlopen(request, timeout=3) @@ -84,6 +86,39 @@ class APIContractTests(unittest.TestCase): self.assertEqual(payload["error"]["code"], "internal_error") self.assertNotIn("private exception detail", json.dumps(payload)) + def test_users_chats_and_cursor(self): + 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 ("u2_alice", "u2_bob", "u2_eve")) + self.assert_error(*self.call("POST", "/api/v1/users", b'{"username":"u2_alice","display_name":"Other"}'), 409) + self.assert_error(*self.call("GET", "/api/v1/users/me"), 401) + self.assert_error(*self.call("GET", "/api/v1/users/me", actor="00000000-0000-4000-8000-000000000000"), 401) + self.assertEqual(self.call("GET", "/api/v1/users/me", actor=alice["id"])[2], alice) + + def chat(member_ids): + body = json.dumps({"title": "Чат 👋", "member_ids": member_ids}).encode() + return self.call("POST", "/api/v1/chats", body, actor=alice["id"]) + + for members in ([alice["id"], alice["id"]], [bob["id"]], [alice["id"], "00000000-0000-4000-8000-000000000000"]): + self.assert_error(*chat(members), 400) + self.assertEqual(self.call("GET", "/api/v1/chats", actor=alice["id"])[2]["items"], []) + first = chat([alice["id"], bob["id"]])[2] + second = chat([alice["id"], bob["id"]])[2] + self.assertEqual(self.call("GET", f'/api/v1/chats/{first["id"]}', actor=bob["id"])[2], first) + self.assert_error(*self.call("GET", f'/api/v1/chats/{first["id"]}', actor=eve["id"]), 404) + self.assertEqual(self.call("GET", "/api/v1/chats", actor=eve["id"])[2]["items"], []) + page = self.call("GET", "/api/v1/chats?limit=1", actor=alice["id"])[2] + self.assertEqual(page["items"], [first]) + self.assertTrue(page["next_cursor"]) + from urllib.parse import quote + next_path = "/api/v1/chats?limit=1&cursor=" + quote(page["next_cursor"], safe="") + self.assertEqual(self.call("GET", next_path, actor=alice["id"])[2], {"items": [second], "next_cursor": None}) + 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) + if __name__ == "__main__": unittest.main()