feat: add users chats and member access
This commit is contained in:
+35
-4
@@ -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))
|
||||
|
||||
+3
-4
@@ -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):
|
||||
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user