189 lines
6.8 KiB
Python
189 lines
6.8 KiB
Python
import hashlib
|
|
import secrets
|
|
import threading
|
|
import uuid
|
|
from bisect import bisect_right
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Dict, List, Optional, Sequence, Tuple
|
|
|
|
from .errors import conflict, invalid_request
|
|
from .pagination import Key
|
|
from .passwords import hash_password, password_matches
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class User:
|
|
id: str
|
|
username: str
|
|
display_name: str
|
|
created_at: str
|
|
|
|
def to_dict(self) -> dict:
|
|
return {
|
|
'id': self.id,
|
|
'username': self.username,
|
|
'display_name': self.display_name,
|
|
'created_at': self.created_at,
|
|
}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Chat:
|
|
id: str
|
|
title: str
|
|
member_ids: Tuple[str, ...]
|
|
created_at: str
|
|
|
|
def to_dict(self) -> dict:
|
|
return {
|
|
'id': self.id,
|
|
'title': self.title,
|
|
'member_ids': list(self.member_ids),
|
|
'created_at': self.created_at,
|
|
}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Message:
|
|
id: str
|
|
chat_id: str
|
|
sender_id: str
|
|
text: str
|
|
created_at: str
|
|
|
|
def to_dict(self) -> dict:
|
|
return {
|
|
'id': self.id,
|
|
'chat_id': self.chat_id,
|
|
'sender_id': self.sender_id,
|
|
'text': self.text,
|
|
'created_at': self.created_at,
|
|
}
|
|
|
|
|
|
class _Timeline:
|
|
"""Append-only sequence ordered by (created_at, id), paginated with bisect."""
|
|
|
|
def __init__(self) -> None:
|
|
self._keys: List[Key] = []
|
|
self._items: List = []
|
|
|
|
def append(self, item) -> None:
|
|
self._keys.append((item.created_at, item.id))
|
|
self._items.append(item)
|
|
|
|
def page(self, limit: int, after: Optional[Key]) -> Tuple[List, bool]:
|
|
start = bisect_right(self._keys, after) if after is not None else 0
|
|
items = self._items[start:start + limit]
|
|
return items, start + len(items) < len(self._items)
|
|
|
|
|
|
def _token_key(token: str) -> str:
|
|
return hashlib.sha256(token.encode('utf-8')).hexdigest()
|
|
|
|
|
|
def _stamp(moment: datetime) -> str:
|
|
return moment.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
|
|
|
|
|
class Store:
|
|
"""Single owner of mutable state; one lock keeps concurrent requests consistent."""
|
|
|
|
def __init__(self, session_ttl_seconds: int = 3600) -> None:
|
|
self._session_ttl = timedelta(seconds=session_ttl_seconds)
|
|
self._lock = threading.Lock()
|
|
self._users: Dict[str, User] = {}
|
|
self._user_id_by_username: Dict[str, str] = {}
|
|
self._password_hashes: Dict[str, str] = {}
|
|
self._sessions: Dict[str, Tuple[str, datetime]] = {}
|
|
self._chats: Dict[str, Chat] = {}
|
|
self._chats_of_user: Dict[str, _Timeline] = {}
|
|
self._messages_of_chat: Dict[str, _Timeline] = {}
|
|
self._last_moment: Optional[datetime] = None
|
|
|
|
def _now(self) -> str:
|
|
"""Strictly increasing server time, so append order always equals sort order."""
|
|
moment = datetime.now(timezone.utc)
|
|
if self._last_moment is not None and moment <= self._last_moment:
|
|
moment = self._last_moment + timedelta(microseconds=1)
|
|
self._last_moment = moment
|
|
return _stamp(moment)
|
|
|
|
def create_user(self, username: str, display_name: str, password: str) -> User:
|
|
password_hash = hash_password(password)
|
|
with self._lock:
|
|
if username in self._user_id_by_username:
|
|
raise conflict('Username уже занят')
|
|
user = User(str(uuid.uuid4()), username, display_name, self._now())
|
|
self._users[user.id] = user
|
|
self._user_id_by_username[username] = user.id
|
|
self._password_hashes[user.id] = password_hash
|
|
return user
|
|
|
|
def authenticate(self, username: str, password: str) -> Optional[User]:
|
|
with self._lock:
|
|
user_id = self._user_id_by_username.get(username)
|
|
user = self._users.get(user_id) if user_id is not None else None
|
|
stored_hash = self._password_hashes.get(user_id) if user_id is not None else None
|
|
if not password_matches(stored_hash, password):
|
|
return None
|
|
return user
|
|
|
|
def create_session(self, user_id: str) -> Tuple[str, str]:
|
|
token = secrets.token_urlsafe(32)
|
|
expires = datetime.now(timezone.utc) + self._session_ttl
|
|
with self._lock:
|
|
self._sessions[_token_key(token)] = (user_id, expires)
|
|
return token, _stamp(expires)
|
|
|
|
def user_for_token(self, token: str) -> Optional[User]:
|
|
now = datetime.now(timezone.utc)
|
|
with self._lock:
|
|
record = self._sessions.get(_token_key(token))
|
|
if record is None:
|
|
return None
|
|
user_id, expires = record
|
|
if expires <= now:
|
|
del self._sessions[_token_key(token)]
|
|
return None
|
|
return self._users.get(user_id)
|
|
|
|
def revoke_session(self, token: str) -> bool:
|
|
now = datetime.now(timezone.utc)
|
|
with self._lock:
|
|
record = self._sessions.pop(_token_key(token), None)
|
|
return record is not None and record[1] > now
|
|
|
|
def create_chat(self, title: str, member_ids: Sequence[str]) -> Chat:
|
|
with self._lock:
|
|
if any(member_id not in self._users for member_id in member_ids):
|
|
raise invalid_request('Все участники должны быть существующими пользователями')
|
|
chat = Chat(str(uuid.uuid4()), title, tuple(member_ids), self._now())
|
|
self._chats[chat.id] = chat
|
|
for member_id in member_ids:
|
|
self._chats_of_user.setdefault(member_id, _Timeline()).append(chat)
|
|
return chat
|
|
|
|
def find_chat(self, chat_id: str, member_id: str) -> Optional[Chat]:
|
|
"""A chat of somebody else is indistinguishable from a missing one."""
|
|
with self._lock:
|
|
chat = self._chats.get(chat_id)
|
|
return chat if chat is not None and member_id in chat.member_ids else None
|
|
|
|
def list_chats(self, member_id: str, limit: int, after: Optional[Key]) -> Tuple[List[Chat], bool]:
|
|
with self._lock:
|
|
timeline = self._chats_of_user.get(member_id)
|
|
return timeline.page(limit, after) if timeline is not None else ([], False)
|
|
|
|
def add_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
|
with self._lock:
|
|
message = Message(str(uuid.uuid4()), chat_id, sender_id, text, self._now())
|
|
self._messages_of_chat.setdefault(chat_id, _Timeline()).append(message)
|
|
return message
|
|
|
|
def list_messages(self, chat_id: str, limit: int, after: Optional[Key]) -> Tuple[List[Message], bool]:
|
|
with self._lock:
|
|
timeline = self._messages_of_chat.get(chat_id)
|
|
return timeline.page(limit, after) if timeline is not None else ([], False)
|