This commit is contained in:
+43
-1
@@ -1,4 +1,4 @@
|
||||
"""Session lookup cache. PostgreSQL remains the source of truth."""
|
||||
"""Lookup cache for sessions and the first history page. PostgreSQL remains the source of truth."""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
@@ -8,6 +8,8 @@ from redis.asyncio import Redis
|
||||
logger = logging.getLogger('messenger')
|
||||
|
||||
_PREFIX = 'session:'
|
||||
_VERSION_PREFIX = 'hver:'
|
||||
_PAGE_TTL_SECONDS = 30
|
||||
|
||||
|
||||
def open_cache(url: str) -> Redis:
|
||||
@@ -66,5 +68,45 @@ class SessionCache:
|
||||
except Exception as exc:
|
||||
logger.warning('session cache delete skipped (%s)', type(exc).__name__)
|
||||
|
||||
async def history_version(self, chat_id: str) -> Optional[int]:
|
||||
"""Published chat version, or None on a miss and when Redis cannot be reached."""
|
||||
try:
|
||||
raw = await self._client.get(_VERSION_PREFIX + chat_id)
|
||||
except Exception as exc:
|
||||
logger.warning('history version read skipped (%s)', type(exc).__name__)
|
||||
return None
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
async def publish_history_version(self, chat_id: str, version: int) -> None:
|
||||
"""Point readers at version. A failed write drops the key so the next read uses PostgreSQL."""
|
||||
key = _VERSION_PREFIX + chat_id
|
||||
try:
|
||||
await self._client.set(key, str(version))
|
||||
except Exception as exc:
|
||||
logger.warning('history version write skipped (%s)', type(exc).__name__)
|
||||
try:
|
||||
await self._client.delete(key)
|
||||
except Exception as drop_exc:
|
||||
logger.warning('history version delete skipped (%s)', type(drop_exc).__name__)
|
||||
|
||||
async def get_history_page(self, key: str) -> Optional[str]:
|
||||
try:
|
||||
return await self._client.get(key)
|
||||
except Exception as exc:
|
||||
logger.warning('history cache read skipped (%s)', type(exc).__name__)
|
||||
return None
|
||||
|
||||
async def set_history_page(self, key: str, payload: str) -> None:
|
||||
"""TTL only drops abandoned version keys. Freshness comes from the version in the key."""
|
||||
try:
|
||||
await self._client.set(key, payload, ex=_PAGE_TTL_SECONDS)
|
||||
except Exception as exc:
|
||||
logger.warning('history cache write skipped (%s)', type(exc).__name__)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._client.aclose()
|
||||
|
||||
@@ -13,6 +13,7 @@ class Settings:
|
||||
session_ttl_seconds: int
|
||||
database_url: str
|
||||
redis_url: str
|
||||
history_cache: str
|
||||
|
||||
|
||||
def _secret(file_var: str, value_var: str) -> str:
|
||||
@@ -32,6 +33,13 @@ def _secret(file_var: str, value_var: str) -> str:
|
||||
return value
|
||||
|
||||
|
||||
def _history_cache() -> str:
|
||||
mode = os.getenv('HISTORY_CACHE', 'protected').strip().lower() or 'protected'
|
||||
if mode not in ('protected', 'naive', 'off'):
|
||||
raise RuntimeError('HISTORY_CACHE must be protected, naive or off')
|
||||
return mode
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
return Settings(
|
||||
host=os.getenv('APP_HOST', '0.0.0.0'),
|
||||
@@ -42,4 +50,5 @@ def load_settings() -> Settings:
|
||||
session_ttl_seconds=int(os.getenv('SESSION_TTL_SECONDS', '3600')),
|
||||
database_url=_secret('DATABASE_URL_FILE', 'DATABASE_URL'),
|
||||
redis_url=_secret('CACHE_URL_FILE', 'REDIS_URL'),
|
||||
history_cache=_history_cache(),
|
||||
)
|
||||
|
||||
+6
-1
@@ -62,7 +62,12 @@ async def lifespan(app: FastAPI):
|
||||
cache = SessionCache(open_cache(settings.redis_url))
|
||||
try:
|
||||
await apply_migrations(pool)
|
||||
app.state.store = Store(pool, cache, settings.session_ttl_seconds)
|
||||
app.state.store = Store(
|
||||
pool,
|
||||
cache,
|
||||
settings.session_ttl_seconds,
|
||||
settings.history_cache,
|
||||
)
|
||||
yield
|
||||
finally:
|
||||
try:
|
||||
|
||||
+147
-16
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import threading
|
||||
import uuid
|
||||
@@ -9,7 +11,7 @@ from typing import Dict, List, Optional, Sequence, Tuple
|
||||
import asyncpg
|
||||
|
||||
from .cache import SessionCache
|
||||
from .errors import conflict, invalid_request, unavailable
|
||||
from .errors import conflict, invalid_request, not_found, unavailable
|
||||
from .pagination import Key
|
||||
from .passwords import hash_password, password_matches
|
||||
|
||||
@@ -72,6 +74,27 @@ def _stamp(moment: datetime) -> str:
|
||||
return moment.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def _encode_page(messages: Sequence[Message], has_more: bool) -> str:
|
||||
return json.dumps(
|
||||
{'items': [message.to_dict() for message in messages], 'has_more': has_more},
|
||||
separators=(',', ':'),
|
||||
)
|
||||
|
||||
|
||||
def _decode_page(payload: Optional[str]) -> Optional[Tuple[List[Message], bool]]:
|
||||
if not payload:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
messages = [
|
||||
Message(item['id'], item['chat_id'], item['sender_id'], item['text'], item['created_at'])
|
||||
for item in data['items']
|
||||
]
|
||||
return messages, bool(data['has_more'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _parse_stamp(value: str) -> datetime:
|
||||
if value.endswith('Z'):
|
||||
value = value[:-1] + '+00:00'
|
||||
@@ -99,15 +122,29 @@ def _db_down(exc: BaseException) -> bool:
|
||||
))
|
||||
|
||||
|
||||
class Store:
|
||||
"""PostgreSQL is the source of truth. Redis only caches the session lookup."""
|
||||
_FIRST_PAGE_LIMIT = 50
|
||||
# Opens the unguarded fill long enough for concurrent misses to each run their own SELECT.
|
||||
_NAIVE_FILL_HOLD_SECONDS = 0.2
|
||||
|
||||
def __init__(self, pool: asyncpg.Pool, cache: SessionCache, session_ttl_seconds: int = 3600) -> None:
|
||||
|
||||
class Store:
|
||||
"""PostgreSQL is the source of truth. Redis caches session lookup and the first history page."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pool: asyncpg.Pool,
|
||||
cache: SessionCache,
|
||||
session_ttl_seconds: int = 3600,
|
||||
history_mode: str = 'protected',
|
||||
) -> None:
|
||||
self._pool = pool
|
||||
self._cache = cache
|
||||
self._session_ttl = timedelta(seconds=session_ttl_seconds)
|
||||
self._history_mode = history_mode
|
||||
self._lock = threading.Lock()
|
||||
self._last_moment: Optional[datetime] = None
|
||||
self._flights: Dict[str, asyncio.Future] = {}
|
||||
self._flight_lock = asyncio.Lock()
|
||||
|
||||
def _now(self) -> datetime:
|
||||
"""Strictly increasing server time, so append order always equals sort order."""
|
||||
@@ -328,23 +365,117 @@ class Store:
|
||||
async def add_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
||||
message_id = uuid.uuid4()
|
||||
created = self._now()
|
||||
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
|
||||
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))
|
||||
async with conn.transaction():
|
||||
version = await conn.fetchval(
|
||||
'''
|
||||
UPDATE chats
|
||||
SET history_version = history_version + 1
|
||||
WHERE id = $1
|
||||
RETURNING history_version
|
||||
''',
|
||||
chat_uuid,
|
||||
)
|
||||
if version is None:
|
||||
raise not_found('Чат не найден')
|
||||
await conn.execute(
|
||||
'''
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
''',
|
||||
message_id,
|
||||
chat_uuid,
|
||||
_as_uuid(sender_id, 'Некорректный user_id'),
|
||||
text,
|
||||
created,
|
||||
)
|
||||
if self._history_mode == 'protected':
|
||||
await self._cache.publish_history_version(str(chat_uuid), int(version))
|
||||
return Message(str(message_id), str(chat_uuid), sender_id, text, _stamp(created))
|
||||
|
||||
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)
|
||||
if after_at is None and limit == _FIRST_PAGE_LIMIT and self._history_mode != 'off':
|
||||
if self._history_mode == 'protected':
|
||||
return await self._protected_first_page(chat_uuid, limit)
|
||||
return await self._naive_first_page(chat_uuid, limit)
|
||||
return await self._fetch_messages(chat_uuid, limit, after_at, after_id)
|
||||
|
||||
async def _protected_first_page(self, chat_uuid: uuid.UUID, limit: int) -> Tuple[List[Message], bool]:
|
||||
chat_id = str(chat_uuid)
|
||||
version = await self._cache.history_version(chat_id)
|
||||
if version is None:
|
||||
version = await self._load_history_version(chat_uuid)
|
||||
await self._cache.publish_history_version(chat_id, version)
|
||||
key = 'history:%s:%s' % (chat_id, version)
|
||||
cached = _decode_page(await self._cache.get_history_page(key))
|
||||
if cached is not None:
|
||||
return cached
|
||||
return await self._singleflight(key, lambda: self._fill_page(key, chat_uuid, limit))
|
||||
|
||||
async def _naive_first_page(self, chat_uuid: uuid.UUID, limit: int) -> Tuple[List[Message], bool]:
|
||||
key = 'history:%s' % chat_uuid
|
||||
cached = _decode_page(await self._cache.get_history_page(key))
|
||||
if cached is not None:
|
||||
return cached
|
||||
messages, has_more = await self._fetch_messages(chat_uuid, limit, None, None)
|
||||
await asyncio.sleep(_NAIVE_FILL_HOLD_SECONDS)
|
||||
await self._cache.set_history_page(key, _encode_page(messages, has_more))
|
||||
return messages, has_more
|
||||
|
||||
async def _fill_page(self, key: str, chat_uuid: uuid.UUID, limit: int) -> Tuple[List[Message], bool]:
|
||||
cached = _decode_page(await self._cache.get_history_page(key))
|
||||
if cached is not None:
|
||||
return cached
|
||||
messages, has_more = await self._fetch_messages(chat_uuid, limit, None, None)
|
||||
await self._cache.set_history_page(key, _encode_page(messages, has_more))
|
||||
return messages, has_more
|
||||
|
||||
async def _singleflight(self, key: str, loader):
|
||||
async with self._flight_lock:
|
||||
flight = self._flights.get(key)
|
||||
if flight is None:
|
||||
flight = asyncio.get_running_loop().create_future()
|
||||
self._flights[key] = flight
|
||||
leader = True
|
||||
else:
|
||||
leader = False
|
||||
if not leader:
|
||||
return await flight
|
||||
try:
|
||||
value = await loader()
|
||||
except Exception as exc:
|
||||
if not flight.done():
|
||||
flight.set_exception(exc)
|
||||
raise
|
||||
else:
|
||||
if not flight.done():
|
||||
flight.set_result(value)
|
||||
return value
|
||||
finally:
|
||||
async with self._flight_lock:
|
||||
if self._flights.get(key) is flight:
|
||||
del self._flights[key]
|
||||
|
||||
async def _load_history_version(self, chat_uuid: uuid.UUID) -> int:
|
||||
async with self._pool.acquire() as conn:
|
||||
version = await conn.fetchval(
|
||||
'SELECT history_version FROM chats WHERE id = $1',
|
||||
chat_uuid,
|
||||
)
|
||||
if version is None:
|
||||
raise not_found('Чат не найден')
|
||||
return int(version)
|
||||
|
||||
async def _fetch_messages(
|
||||
self,
|
||||
chat_uuid: uuid.UUID,
|
||||
limit: int,
|
||||
after_at: Optional[datetime],
|
||||
after_id: Optional[uuid.UUID],
|
||||
) -> Tuple[List[Message], bool]:
|
||||
async with self._pool.acquire() as conn:
|
||||
if after_at is None:
|
||||
rows = await conn.fetch(
|
||||
|
||||
Reference in New Issue
Block a user