forked from mtusi2026/mtusi2026lab2
194 lines
6.8 KiB
Python
194 lines
6.8 KiB
Python
import base64
|
|
import bisect
|
|
import binascii
|
|
import json
|
|
import os
|
|
import threading
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
from typing import Dict, List, Optional, Tuple
|
|
|
|
from .models import Chat, Message, User
|
|
|
|
|
|
Key = Tuple[datetime, str]
|
|
|
|
|
|
def _encode_cursor(kind: str, scope: str, item) -> str:
|
|
payload = {
|
|
"v": 1,
|
|
"kind": kind,
|
|
"scope": scope,
|
|
"created_at": item.created_at.isoformat(),
|
|
"id": item.id,
|
|
}
|
|
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
|
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
|
|
|
|
|
def _decode_cursor(cursor: str, kind: str, scope: str) -> Key:
|
|
try:
|
|
if not cursor or len(cursor) > 4096:
|
|
raise ValueError
|
|
padded = cursor + "=" * (-len(cursor) % 4)
|
|
raw = base64.b64decode(padded, altchars=b"-_", validate=True)
|
|
payload = json.loads(raw.decode("utf-8"))
|
|
if not isinstance(payload, dict) or payload.get("v") != 1:
|
|
raise ValueError
|
|
if payload.get("kind") != kind or payload.get("scope") != scope:
|
|
raise ValueError
|
|
item_id = payload.get("id")
|
|
timestamp = payload.get("created_at")
|
|
if not isinstance(item_id, str) or not isinstance(timestamp, str):
|
|
raise ValueError
|
|
created_at = datetime.fromisoformat(timestamp)
|
|
if created_at.tzinfo is None:
|
|
raise ValueError
|
|
created_at = created_at.astimezone(timezone.utc)
|
|
return created_at, item_id
|
|
except (
|
|
ValueError,
|
|
TypeError,
|
|
KeyError,
|
|
UnicodeDecodeError,
|
|
json.JSONDecodeError,
|
|
binascii.Error,
|
|
):
|
|
raise ValueError("invalid_request") from None
|
|
|
|
|
|
class InMemoryStore:
|
|
def __init__(self):
|
|
self._lock = threading.RLock()
|
|
self.users: Dict[str, User] = {}
|
|
self.chats: Dict[str, Chat] = {}
|
|
self.messages: Dict[str, List[Message]] = {}
|
|
self.usernames: Dict[str, str] = {}
|
|
self.message_keys: Dict[str, List[Key]] = {}
|
|
self.message_index_enabled = os.getenv("MESSAGE_INDEX_ENABLED", "1") != "0"
|
|
|
|
def create_user(self, username: str, display_name: str) -> User:
|
|
with self._lock:
|
|
if username in self.usernames:
|
|
raise ValueError("conflict")
|
|
user_id = str(uuid.uuid4())
|
|
user = User(
|
|
id=user_id,
|
|
username=username,
|
|
display_name=display_name,
|
|
created_at=datetime.now(timezone.utc),
|
|
)
|
|
self.users[user_id] = user
|
|
self.usernames[username] = user_id
|
|
return user
|
|
|
|
def get_user(self, user_id: str) -> Optional[User]:
|
|
with self._lock:
|
|
return self.users.get(user_id)
|
|
|
|
def create_chat(self, title: str, member_ids: List[str], creator_id: str) -> Chat:
|
|
with self._lock:
|
|
if creator_id not in member_ids or len(member_ids) != len(set(member_ids)):
|
|
raise ValueError("invalid_request")
|
|
if any(member_id not in self.users for member_id in member_ids):
|
|
raise ValueError("invalid_request")
|
|
|
|
chat_id = str(uuid.uuid4())
|
|
chat = Chat(
|
|
id=chat_id,
|
|
title=title,
|
|
member_ids=list(member_ids),
|
|
created_at=datetime.now(timezone.utc),
|
|
)
|
|
self.chats[chat_id] = chat
|
|
self.messages[chat_id] = []
|
|
self.message_keys[chat_id] = []
|
|
return chat
|
|
|
|
def get_chat(self, chat_id: str, user_id: str) -> Optional[Chat]:
|
|
with self._lock:
|
|
chat = self.chats.get(chat_id)
|
|
if chat is None or user_id not in chat.member_ids:
|
|
return None
|
|
return chat
|
|
|
|
def list_chats(
|
|
self, user_id: str, limit: int, cursor: Optional[str]
|
|
) -> Tuple[List[Chat], Optional[str]]:
|
|
with self._lock:
|
|
user_chats = [chat for chat in self.chats.values() if user_id in chat.member_ids]
|
|
user_chats.sort(key=lambda chat: (chat.created_at, chat.id))
|
|
keys = [(chat.created_at, chat.id) for chat in user_chats]
|
|
|
|
start_index = 0
|
|
if cursor:
|
|
target_key = _decode_cursor(cursor, kind="chats", scope=user_id)
|
|
start_index = bisect.bisect_right(keys, target_key)
|
|
|
|
page_with_extra = user_chats[start_index : start_index + limit + 1]
|
|
has_next = len(page_with_extra) > limit
|
|
page = page_with_extra[:limit]
|
|
next_cursor = None
|
|
if has_next and page:
|
|
next_cursor = _encode_cursor("chats", user_id, page[-1])
|
|
return page, next_cursor
|
|
|
|
def create_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
|
with self._lock:
|
|
chat = self.chats.get(chat_id)
|
|
if chat is None or sender_id not in chat.member_ids:
|
|
raise ValueError("not_found")
|
|
|
|
message = Message(
|
|
id=str(uuid.uuid4()),
|
|
chat_id=chat_id,
|
|
sender_id=sender_id,
|
|
text=text,
|
|
created_at=datetime.now(timezone.utc),
|
|
)
|
|
messages = self.messages[chat_id]
|
|
keys = self.message_keys[chat_id]
|
|
key = (message.created_at, message.id)
|
|
|
|
if self.message_index_enabled:
|
|
index = bisect.bisect_right(keys, key)
|
|
keys.insert(index, key)
|
|
messages.insert(index, message)
|
|
else:
|
|
current_keys = [(item.created_at, item.id) for item in messages]
|
|
index = bisect.bisect_right(current_keys, key)
|
|
messages.insert(index, message)
|
|
keys.insert(index, key)
|
|
return message
|
|
|
|
def list_messages(
|
|
self,
|
|
chat_id: str,
|
|
user_id: str,
|
|
limit: int,
|
|
cursor: Optional[str],
|
|
) -> Tuple[List[Message], Optional[str]]:
|
|
with self._lock:
|
|
chat = self.chats.get(chat_id)
|
|
if chat is None or user_id not in chat.member_ids:
|
|
raise ValueError("not_found")
|
|
|
|
messages = self.messages[chat_id]
|
|
if self.message_index_enabled:
|
|
keys = self.message_keys[chat_id]
|
|
else:
|
|
keys = [(item.created_at, item.id) for item in messages]
|
|
|
|
start_index = 0
|
|
if cursor:
|
|
target_key = _decode_cursor(cursor, kind="messages", scope=chat_id)
|
|
start_index = bisect.bisect_right(keys, target_key)
|
|
|
|
page_with_extra = messages[start_index : start_index + limit + 1]
|
|
has_next = len(page_with_extra) > limit
|
|
page = page_with_extra[:limit]
|
|
next_cursor = None
|
|
if has_next and page:
|
|
next_cursor = _encode_cursor("messages", chat_id, page[-1])
|
|
return page, next_cursor
|