level 3 basics
This commit is contained in:
+271
-92
@@ -2,12 +2,13 @@ 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
|
||||
import asyncpg
|
||||
|
||||
from .errors import conflict, invalid_request, unavailable
|
||||
from .pagination import Key
|
||||
from .passwords import hash_password, password_matches
|
||||
|
||||
@@ -62,23 +63,6 @@ class Message:
|
||||
}
|
||||
|
||||
|
||||
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()
|
||||
|
||||
@@ -87,102 +71,297 @@ 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 _parse_stamp(value: str) -> datetime:
|
||||
if value.endswith('Z'):
|
||||
value = value[:-1] + '+00:00'
|
||||
return datetime.fromisoformat(value)
|
||||
|
||||
def __init__(self, session_ttl_seconds: int = 3600) -> None:
|
||||
|
||||
def _user(row: asyncpg.Record) -> User:
|
||||
return User(str(row['id']), row['username'], row['display_name'], _stamp(row['created_at']))
|
||||
|
||||
|
||||
def _as_uuid(value: str, message: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(value)
|
||||
except ValueError:
|
||||
raise invalid_request(message) from None
|
||||
|
||||
|
||||
class Store:
|
||||
"""PostgreSQL is the source of truth. One process clock keeps created_at ordered."""
|
||||
|
||||
def __init__(self, pool: asyncpg.Pool, session_ttl_seconds: int = 3600) -> None:
|
||||
self._pool = pool
|
||||
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:
|
||||
def _now(self) -> datetime:
|
||||
"""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)
|
||||
with self._lock:
|
||||
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 moment
|
||||
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
async def ready(self) -> None:
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute('SELECT 1')
|
||||
except Exception:
|
||||
raise unavailable('Хранилище недоступно') from None
|
||||
|
||||
async 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
|
||||
user_id = uuid.uuid4()
|
||||
created = self._now()
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
'''
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
''',
|
||||
user_id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash,
|
||||
created,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
raise conflict('Username уже занят') from None
|
||||
return User(str(user_id), username, display_name, _stamp(created))
|
||||
|
||||
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):
|
||||
async def authenticate(self, username: str, password: str) -> Optional[User]:
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
''',
|
||||
username,
|
||||
)
|
||||
stored_hash = row['password_hash'] if row is not None else None
|
||||
if not password_matches(stored_hash, password) or row is None:
|
||||
return None
|
||||
return user
|
||||
return _user(row)
|
||||
|
||||
def create_session(self, user_id: str) -> Tuple[str, str]:
|
||||
async 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)
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
'''
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
''',
|
||||
_token_key(token),
|
||||
_as_uuid(user_id, 'Некорректный user_id'),
|
||||
expires,
|
||||
)
|
||||
return token, _stamp(expires)
|
||||
|
||||
def user_for_token(self, token: str) -> Optional[User]:
|
||||
async 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:
|
||||
key = _token_key(token)
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
''',
|
||||
key,
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
user_id, expires = record
|
||||
if expires <= now:
|
||||
del self._sessions[_token_key(token)]
|
||||
if row['expires_at'] <= now:
|
||||
await conn.execute('DELETE FROM sessions WHERE token_hash = $1', key)
|
||||
return None
|
||||
return self._users.get(user_id)
|
||||
return _user(row)
|
||||
|
||||
def revoke_session(self, token: str) -> bool:
|
||||
async 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
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1 AND expires_at > $2
|
||||
RETURNING token_hash
|
||||
''',
|
||||
_token_key(token),
|
||||
now,
|
||||
)
|
||||
return row is not None
|
||||
|
||||
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
|
||||
async def create_chat(self, title: str, member_ids: Sequence[str]) -> Chat:
|
||||
ids = [_as_uuid(member_id, 'Некорректный user_id') for member_id in member_ids]
|
||||
chat_id = uuid.uuid4()
|
||||
created = self._now()
|
||||
async with self._pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
found = await conn.fetch(
|
||||
'SELECT id FROM users WHERE id = ANY($1::uuid[])',
|
||||
ids,
|
||||
)
|
||||
if len(found) != len(ids):
|
||||
raise invalid_request('Все участники должны быть существующими пользователями')
|
||||
await conn.execute(
|
||||
'INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)',
|
||||
chat_id,
|
||||
title,
|
||||
created,
|
||||
)
|
||||
await conn.execute(
|
||||
'''
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT $1, member_id, (ordinality - 1)::integer
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS members(member_id, ordinality)
|
||||
''',
|
||||
chat_id,
|
||||
ids,
|
||||
)
|
||||
return Chat(str(chat_id), title, tuple(member_ids), _stamp(created))
|
||||
|
||||
def find_chat(self, chat_id: str, member_id: str) -> Optional[Chat]:
|
||||
async 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
|
||||
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
|
||||
member_uuid = _as_uuid(member_id, 'Некорректный user_id')
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'''
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $2
|
||||
WHERE c.id = $1
|
||||
''',
|
||||
chat_uuid,
|
||||
member_uuid,
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
members = await self._members(conn, [chat_uuid])
|
||||
return Chat(str(row['id']), row['title'], members.get(chat_uuid, ()), _stamp(row['created_at']))
|
||||
|
||||
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)
|
||||
async def list_chats(self, member_id: str, limit: int, after: Optional[Key]) -> Tuple[List[Chat], bool]:
|
||||
member_uuid = _as_uuid(member_id, 'Некорректный user_id')
|
||||
after_at, after_id = self._cursor(after)
|
||||
async with self._pool.acquire() as conn:
|
||||
if after_at is None:
|
||||
rows = await conn.fetch(
|
||||
'''
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2
|
||||
''',
|
||||
member_uuid,
|
||||
limit + 1,
|
||||
)
|
||||
else:
|
||||
rows = await conn.fetch(
|
||||
'''
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $1
|
||||
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
''',
|
||||
member_uuid,
|
||||
after_at,
|
||||
after_id,
|
||||
limit + 1,
|
||||
)
|
||||
page = rows[:limit]
|
||||
members = await self._members(conn, [row['id'] for row in page])
|
||||
chats = [
|
||||
Chat(str(row['id']), row['title'], members.get(row['id'], ()), _stamp(row['created_at']))
|
||||
for row in page
|
||||
]
|
||||
return chats, len(rows) > limit
|
||||
|
||||
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
|
||||
async def add_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
||||
message_id = uuid.uuid4()
|
||||
created = self._now()
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
'''
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
''',
|
||||
message_id,
|
||||
_as_uuid(chat_id, 'Некорректный chat_id'),
|
||||
_as_uuid(sender_id, 'Некорректный user_id'),
|
||||
text,
|
||||
created,
|
||||
)
|
||||
return Message(str(message_id), chat_id, sender_id, text, _stamp(created))
|
||||
|
||||
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)
|
||||
async def list_messages(self, chat_id: str, limit: int, after: Optional[Key]) -> Tuple[List[Message], bool]:
|
||||
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
|
||||
after_at, after_id = self._cursor(after)
|
||||
async with self._pool.acquire() as conn:
|
||||
if after_at is None:
|
||||
rows = await conn.fetch(
|
||||
'''
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
''',
|
||||
chat_uuid,
|
||||
limit + 1,
|
||||
)
|
||||
else:
|
||||
rows = await conn.fetch(
|
||||
'''
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
''',
|
||||
chat_uuid,
|
||||
after_at,
|
||||
after_id,
|
||||
limit + 1,
|
||||
)
|
||||
page = rows[:limit]
|
||||
messages = [
|
||||
Message(str(row['id']), str(row['chat_id']), str(row['sender_id']), row['text'], _stamp(row['created_at']))
|
||||
for row in page
|
||||
]
|
||||
return messages, len(rows) > limit
|
||||
|
||||
async def _members(self, conn: asyncpg.Connection, chat_ids: Sequence[uuid.UUID]) -> Dict[uuid.UUID, Tuple[str, ...]]:
|
||||
if not chat_ids:
|
||||
return {}
|
||||
rows = await conn.fetch(
|
||||
'''
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY($1::uuid[])
|
||||
ORDER BY chat_id, position
|
||||
''',
|
||||
list(chat_ids),
|
||||
)
|
||||
grouped: Dict[uuid.UUID, List[str]] = {}
|
||||
for row in rows:
|
||||
grouped.setdefault(row['chat_id'], []).append(str(row['user_id']))
|
||||
return {chat_id: tuple(member_ids) for chat_id, member_ids in grouped.items()}
|
||||
|
||||
def _cursor(self, after: Optional[Key]) -> Tuple[Optional[datetime], Optional[uuid.UUID]]:
|
||||
if after is None:
|
||||
return None, None
|
||||
try:
|
||||
return _parse_stamp(after[0]), uuid.UUID(after[1])
|
||||
except ValueError:
|
||||
raise invalid_request('Некорректный cursor') from None
|
||||
|
||||
Reference in New Issue
Block a user