forked from SamohvalovAndreyBPI2302/mtusi2026lab1
feat: add users chats and member access
This commit is contained in:
@@ -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