more before level3 changes

This commit is contained in:
2026-11-09 18:25:54 +03:00
parent 1686d51bca
commit 0346937847
8 changed files with 239 additions and 32 deletions
+69 -24
View File
@@ -1,5 +1,7 @@
import asyncio
import hashlib
import json
import logging
import secrets
import threading
import uuid
@@ -11,9 +13,12 @@ import asyncpg
from .errors import conflict, invalid_request, not_found, unavailable
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:
@@ -132,10 +137,21 @@ def _db_down(exc: BaseException) -> bool:
class Store:
"""PostgreSQL is the only state shared by replicas: users, chats, sessions, messages and attachment bytes."""
"""PostgreSQL holds users, chats, sessions, messages and attachment metadata.
def __init__(self, pool: asyncpg.Pool, session_ttl_seconds: int = 3600, idempotency_ttl_seconds: int = 86400) -> None:
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()
@@ -152,7 +168,7 @@ class Store:
return moment
async def ready(self) -> None:
"""Ready only when PostgreSQL answers and the separate migrator has applied this build's schema."""
"""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(
@@ -163,6 +179,10 @@ class Store:
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)
@@ -362,27 +382,37 @@ class Store:
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
owner_uuid = _as_uuid(owner_id, 'Некорректный user_id')
attachment_id = uuid.uuid4()
# The key is not derived from filename. A crash after PUT and before INSERT leaves an
# unreferenced object; a failed INSERT deletes it. 201 is returned only after both succeed.
object_key = 'originals/%s' % attachment_id
created = self._now()
async with self._pool.acquire() as conn:
await conn.execute(
'''
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, body, created_at, updated_at
try:
await asyncio.to_thread(self._objects.put, object_key, body, content_type)
except StorageError:
raise unavailable('Хранилище недоступно') from None
try:
async with self._pool.acquire() as conn:
await conn.execute(
'''
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $9)
''',
attachment_id,
chat_uuid,
owner_uuid,
filename,
content_type,
len(body),
sha256,
object_key,
created,
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10)
''',
attachment_id,
chat_uuid,
owner_uuid,
filename,
content_type,
len(body),
sha256,
uuid.uuid4().hex,
body,
created,
)
except Exception:
await self._discard_object(object_key)
raise
stamp = _stamp(created)
return Attachment(
str(attachment_id),
@@ -432,7 +462,7 @@ class Store:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
'''
SELECT a.content_type, a.body
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
@@ -442,7 +472,22 @@ class Store:
)
if row is None:
return None
return row['content_type'], bytes(row['body'])
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 _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,