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()
|
||||
|
||||
Reference in New Issue
Block a user