import asyncio import hashlib import json import logging import secrets import threading import uuid from dataclasses import dataclass from datetime import datetime, timedelta, timezone from typing import BinaryIO, Dict, List, Optional, Sequence, Tuple import asyncpg from .config import job_max_attempts, max_inflight_jobs from .errors import conflict, invalid_request, not_found, rate_limited, unavailable from .jobs import PIPELINE_VERSION, original_key, staging_key from .migrate import expected_versions from .objects import MissingObject, ObjectStore, StorageError from .pagination import Key from .passwords import hash_password, password_matches logger = logging.getLogger('messenger') @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 attachment_ids: Tuple[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, 'attachment_ids': list(self.attachment_ids), } @dataclass(frozen=True) class Variant: name: str content_type: str size_bytes: int width: int height: int sha256: str def to_dict(self) -> dict: return { 'name': self.name, 'content_type': self.content_type, 'size_bytes': self.size_bytes, 'width': self.width, 'height': self.height, 'sha256': self.sha256, } @dataclass(frozen=True) class Attachment: id: str chat_id: str owner_id: str filename: str content_type: str size_bytes: int sha256: str status: str created_at: str updated_at: str variants: Tuple[Variant, ...] = () error_code: Optional[str] = None def to_dict(self) -> dict: return { 'id': self.id, 'chat_id': self.chat_id, 'owner_id': self.owner_id, 'filename': self.filename, 'content_type': self.content_type, 'size_bytes': self.size_bytes, 'sha256': self.sha256, 'status': self.status, 'variants': [item.to_dict() for item in self.variants], 'error_code': self.error_code if self.status == 'failed' else None, 'created_at': self.created_at, 'updated_at': self.updated_at, } @dataclass(frozen=True) class QueuedUpload: attachment: Attachment job_id: str @dataclass(frozen=True) class AttachmentRef: """One metadata row as the reconciler sees it. Not an API response.""" id: str object_key: str created_at: datetime in_use: bool sha256: str 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') def _parse_stamp(value: str) -> datetime: if value.endswith('Z'): value = value[:-1] + '+00:00' return datetime.fromisoformat(value) 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 def _db_down(exc: BaseException) -> bool: return isinstance(exc, ( asyncpg.PostgresConnectionError, asyncpg.InterfaceError, asyncpg.CannotConnectNowError, OSError, TimeoutError, )) class Store: """PostgreSQL holds users, chats, sessions, messages and attachment metadata. Original bytes are in the private bucket. Any replica can read them by the server-assigned key. """ def __init__( self, pool: asyncpg.Pool, session_ttl_seconds: int = 3600, idempotency_ttl_seconds: int = 86400, *, objects: ObjectStore, ) -> None: self._pool = pool self._objects = objects self._session_ttl = timedelta(seconds=session_ttl_seconds) self._idempotency_ttl = timedelta(seconds=idempotency_ttl_seconds) self._lock = threading.Lock() self._last_moment: Optional[datetime] = None self._migrations = expected_versions() @property def pool(self) -> asyncpg.Pool: return self._pool def _now(self) -> datetime: """Strictly increasing within one process; across replicas order relies on the shared host clock.""" 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 async def ready(self) -> None: """Ready when PostgreSQL has this build's schema and the private bucket answers.""" try: async with self._pool.acquire() as conn: applied = await conn.fetchval( 'SELECT count(*) FROM schema_migrations WHERE version = ANY($1::text[])', self._migrations, ) except Exception: raise unavailable('Хранилище недоступно') from None if applied != len(self._migrations): raise unavailable('Схема БД ещё не применена') try: await asyncio.to_thread(self._objects.ready) except StorageError: raise unavailable('Хранилище недоступно') from None async def create_user(self, username: str, display_name: str, password: str) -> User: password_hash = hash_password(password) 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)) async def authenticate(self, username: str, password: str) -> Optional[User]: try: 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, ) except Exception as exc: if _db_down(exc): raise unavailable('Хранилище недоступно') from None raise 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(row) async def create_session(self, user_id: str) -> Tuple[str, str]: token = secrets.token_urlsafe(32) expires = datetime.now(timezone.utc) + self._session_ttl try: 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, ) except Exception as exc: if _db_down(exc): raise unavailable('Хранилище недоступно') from None raise return token, _stamp(expires) async def user_for_token(self, token: str) -> Optional[User]: now = datetime.now(timezone.utc) key = _token_key(token) try: 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 if row['expires_at'] <= now: await conn.execute('DELETE FROM sessions WHERE token_hash = $1', key) return None return _user(row) except Exception as exc: if _db_down(exc): raise unavailable('Хранилище недоступно') from None raise async def revoke_session(self, token: str) -> bool: try: 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), datetime.now(timezone.utc), ) except Exception as exc: if _db_down(exc): raise unavailable('Хранилище недоступно') from None raise return row is not None 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)) async def find_chat(self, chat_id: str, member_id: str) -> Optional[Chat]: """A chat of somebody else is indistinguishable from a missing one.""" 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'])) 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 async def create_attachment( self, chat_id: str, owner_id: str, filename: str, content_type: str, body: BinaryIO, size_bytes: int, sha256: str, ) -> QueuedUpload: chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id') owner_uuid = _as_uuid(owner_id, 'Некорректный user_id') attachment_id = uuid.uuid4() job_id = uuid.uuid4() # filename is never a storage key. Bytes go to staging/ first. The job row is the # outbox: 202 follows this commit, and a missing broker confirm is retried from the row. staged = staging_key(str(attachment_id)) final = original_key(str(attachment_id)) created = self._now() # Reject before the object is stored when the cap is already reached. # The transaction below locks and counts again, so concurrent uploads cannot all slip in. if await self._inflight_jobs() >= max_inflight_jobs(): raise rate_limited('Очередь заполнена, новая работа не принята') try: await asyncio.to_thread(self._objects.put_stream, staged, body, size_bytes, content_type) except StorageError: await self._discard_object(staged) raise unavailable('Хранилище недоступно') from None try: async with self._pool.acquire() as conn: async with conn.transaction(): await self._admit_job(conn) await conn.execute( ''' INSERT INTO attachments ( id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, staging_key, status, created_at, updated_at ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'queued', $10, $10) ''', attachment_id, chat_uuid, owner_uuid, filename, content_type, size_bytes, sha256, final, staged, created, ) await conn.execute( ''' INSERT INTO attachment_jobs ( id, attachment_id, pipeline_version, attempt, max_attempts, created_at, updated_at ) VALUES ($1, $2, $3, 1, $4, $5, $5) ''', job_id, attachment_id, PIPELINE_VERSION, job_max_attempts(), created, ) except Exception: await self._discard_object(staged) raise stamp = _stamp(created) attachment = Attachment( str(attachment_id), str(chat_uuid), str(owner_uuid), filename, content_type, size_bytes, sha256, 'queued', stamp, stamp, ) return QueuedUpload(attachment, str(job_id)) async def attachment_index(self) -> List[AttachmentRef]: """Every attachment row. `in_use` means a message still points at it. The reconciler uses this instead of the HTTP API. A row linked from message_attachments must survive even when the object is gone: the foreign key has no ON DELETE CASCADE, and the message would lose its file. """ async with self._pool.acquire() as conn: rows = await conn.fetch( ''' SELECT a.id, a.object_key, a.created_at, a.sha256, EXISTS ( SELECT 1 FROM message_attachments m WHERE m.attachment_id = a.id ) AS in_use FROM attachments a ''' ) return [ AttachmentRef( str(row['id']), row['object_key'], row['created_at'], bool(row['in_use']), row['sha256'], ) for row in rows ] async def object_key_referenced(self, object_key: str) -> bool: """True when a metadata row owns this key. Checked again immediately before delete.""" async with self._pool.acquire() as conn: found = await conn.fetchval( 'SELECT 1 FROM attachments WHERE object_key = $1', object_key, ) return found is not None async def delete_attachment_if_unlinked(self, attachment_id: str, created_before: datetime) -> bool: """Delete a stale row that no message references. A link or a young row keeps it. `created_before` is the scan clock minus grace, so the row deleted here is the same row the scan classified as stale. The originals/ predicate matches the prefix the reconciler is allowed to own. """ async with self._pool.acquire() as conn: result = await conn.execute( ''' DELETE FROM attachments WHERE id = $1 AND object_key LIKE 'originals/%' AND created_at <= $2 AND NOT EXISTS ( SELECT 1 FROM message_attachments WHERE attachment_id = $1 ) ''', _as_uuid(attachment_id, 'Некорректный attachment_id'), created_before, ) return result == 'DELETE 1' async def rewind_attachment_created_at(self, attachment_id: str, created_at: datetime) -> None: """Move one row's clock back. The track-2 experiment uses this to age a fixture.""" async with self._pool.acquire() as conn: result = await conn.execute( 'UPDATE attachments SET created_at = $2 WHERE id = $1', _as_uuid(attachment_id, 'Некорректный attachment_id'), created_at, ) if result != 'UPDATE 1': raise RuntimeError('attachment row missing') async def find_attachment(self, attachment_id: str, user_id: str) -> Optional[Attachment]: """Metadata for a chat member. Missing and foreign attachments are both absent.""" attachment_uuid = _as_uuid(attachment_id, 'Некорректный attachment_id') user_uuid = _as_uuid(user_id, 'Некорректный user_id') async with self._pool.acquire() as conn: row = await conn.fetchrow( ''' SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 WHERE a.id = $1 ''', attachment_uuid, user_uuid, ) variants = () if row is None else await self._variants(conn, attachment_uuid) if row is None: return None return Attachment( str(row['id']), str(row['chat_id']), str(row['owner_id']), row['filename'], row['content_type'], row['size_bytes'], row['sha256'], row['status'], _stamp(row['created_at']), _stamp(row['updated_at']), variants, row['error_code'], ) async def _variants(self, conn: asyncpg.Connection, attachment_id: uuid.UUID) -> Tuple[Variant, ...]: rows = await conn.fetch( ''' SELECT name, content_type, size_bytes, width, height, sha256 FROM attachment_variants WHERE attachment_id = $1 AND pipeline_version = $2 ORDER BY name ''', attachment_id, PIPELINE_VERSION, ) return tuple( Variant( row['name'], row['content_type'], row['size_bytes'], row['width'], row['height'], row['sha256'], ) for row in rows ) async def read_content(self, attachment_id: str, user_id: str, variant: str) -> Optional[Tuple[str, bytes]]: attachment_uuid = _as_uuid(attachment_id, 'Некорректный attachment_id') user_uuid = _as_uuid(user_id, 'Некорректный user_id') async with self._pool.acquire() as conn: if variant == 'original': row = await conn.fetchrow( ''' SELECT a.content_type, a.size_bytes, a.sha256, a.object_key FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 WHERE a.id = $1 ''', attachment_uuid, user_uuid, ) else: row = await conn.fetchrow( ''' SELECT v.content_type, v.size_bytes, v.sha256, v.object_key FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 WHERE v.attachment_id = $1 AND v.pipeline_version = $3 AND v.name = $4 ''', attachment_uuid, user_uuid, PIPELINE_VERSION, variant, ) if row is None: return None try: body = await asyncio.to_thread(self._objects.get, row['object_key']) except MissingObject: return None except StorageError: raise unavailable('Хранилище недоступно') from None if len(body) != row['size_bytes'] or hashlib.sha256(body).hexdigest() != row['sha256']: logger.warning('object bytes do not match attachment metadata') raise unavailable('Хранилище недоступно') return row['content_type'], body async def _inflight_jobs(self) -> int: async with self._pool.acquire() as conn: value = await conn.fetchval( "SELECT count(*)::int FROM attachments WHERE status IN ('queued', 'processing')" ) return int(value or 0) async def _admit_job(self, conn) -> None: """One lock for the cap. Held only until this transaction commits or rolls back.""" await conn.execute('SELECT pg_advisory_xact_lock($1)', 48151) inflight = await conn.fetchval( "SELECT count(*)::int FROM attachments WHERE status IN ('queued', 'processing')" ) if int(inflight or 0) >= max_inflight_jobs(): raise rate_limited('Очередь заполнена, новая работа не принята') async def _discard_object(self, object_key: str) -> None: try: await asyncio.to_thread(self._objects.delete, object_key) except StorageError: logger.warning('object left in the bucket after a failed metadata write') async def add_message( self, chat_id: str, sender_id: str, text: str, attachment_ids: Sequence[str], *, path: str, key: str, request_hash: str, ) -> Message: """Exactly one message per (sender, POST, path, key), whichever replica receives the request. Concurrent duplicates block on the primary key of idempotency_keys until the first transaction commits or rolls back, so a rolled-back attempt leaves the key free. """ chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id') sender_uuid = _as_uuid(sender_id, 'Некорректный user_id') linked = tuple(_as_uuid(item, 'Некорректный attachment_id') for item in attachment_ids) message = Message( str(uuid.uuid4()), str(chat_uuid), sender_id, text, _stamp(self._now()), tuple(str(item) for item in linked), ) cutoff = datetime.now(timezone.utc) - self._idempotency_ttl async with self._pool.acquire() as conn: async with conn.transaction(): await conn.execute( ''' DELETE FROM idempotency_keys WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3 AND created_at < $4 ''', sender_uuid, path, key, cutoff, ) claimed = await conn.fetchval( ''' INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response) VALUES ($1, 'POST', $2, $3, $4, 201, $5::jsonb) ON CONFLICT (user_id, method, path, key) DO NOTHING RETURNING 1 ''', sender_uuid, path, key, request_hash, json.dumps(message.to_dict()), ) if claimed is None: return await self._replay(conn, sender_uuid, path, key, request_hash) if linked: rows = await conn.fetch( 'SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])', list(linked), ) found = {row['id']: row for row in rows} if len(found) != len(linked) or any(found[item]['chat_id'] != chat_uuid for item in linked): raise not_found('Вложение не найдено') if any(found[item]['status'] == 'failed' for item in linked): raise conflict('Нельзя прикрепить повреждённое вложение') await conn.execute( ''' INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5) ''', uuid.UUID(message.id), chat_uuid, sender_uuid, text, _parse_stamp(message.created_at), ) if linked: await conn.executemany( ''' INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1, $2, $3) ''', [(uuid.UUID(message.id), item, index) for index, item in enumerate(linked)], ) return message async def _replay( self, conn: asyncpg.Connection, sender_uuid: uuid.UUID, path: str, key: str, request_hash: str, ) -> Message: row = await conn.fetchrow( ''' SELECT request_hash, response FROM idempotency_keys WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3 ''', sender_uuid, path, key, ) if row is None: raise unavailable('Повторите запрос с тем же Idempotency-Key') if row['request_hash'] != request_hash: raise conflict('Idempotency-Key уже использован с другим сообщением') data = json.loads(row['response']) return Message( data['id'], data['chat_id'], data['sender_id'], data['text'], data['created_at'], tuple(data.get('attachment_ids') or ()), ) 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] links = await self._attachment_ids(conn, [row['id'] for row in page]) messages = [ Message( str(row['id']), str(row['chat_id']), str(row['sender_id']), row['text'], _stamp(row['created_at']), links.get(row['id'], ()), ) for row in page ] return messages, len(rows) > limit async def _attachment_ids( self, conn: asyncpg.Connection, message_ids: Sequence[uuid.UUID], ) -> Dict[uuid.UUID, Tuple[str, ...]]: if not message_ids: return {} rows = await conn.fetch( ''' SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY($1::uuid[]) ORDER BY message_id, position ''', list(message_ids), ) grouped: Dict[uuid.UUID, List[str]] = {} for row in rows: grouped.setdefault(row['message_id'], []).append(str(row['attachment_id'])) return {message_id: tuple(ids) for message_id, ids in grouped.items()} 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