"""Process-local state for lab 1.""" import base64 import binascii import json from bisect import bisect_right, insort 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 message_key(item: dict) -> tuple[str, str]: return item["created_at"], item["id"] 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] = {} self.messages: dict[str, list[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 self.messages[chat["id"]] = [] 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} 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(), } insort(self.messages[chat_id], message, key=message_key) 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 = self.messages[chat_id] start = bisect_right(items, after, key=message_key) if after is not None else 0 page = items[start:start + limit] next_cursor = encode_cursor(f"messages:{chat_id}", page[-1]) if len(items) > start + limit else None return {"items": page, "next_cursor": next_cursor} store = Store()