forked from mtusi2026/mtusi2026lab2
113 lines
3.8 KiB
Python
113 lines
3.8 KiB
Python
"""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
|
|
|
|
from redis.asyncio import Redis
|
|
|
|
logger = logging.getLogger('messenger')
|
|
|
|
_PREFIX = 'session:'
|
|
_VERSION_PREFIX = 'hver:'
|
|
_PAGE_TTL_SECONDS = 30
|
|
|
|
|
|
def open_cache(url: str) -> Redis:
|
|
return Redis.from_url(
|
|
url,
|
|
socket_connect_timeout=1,
|
|
socket_timeout=1,
|
|
max_connections=10,
|
|
decode_responses=True,
|
|
)
|
|
|
|
|
|
def _stamp(moment: datetime) -> str:
|
|
return moment.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
|
|
|
|
|
class SessionCache:
|
|
"""Stores sha256(token) -> expires_at. A read never refreshes the TTL."""
|
|
|
|
def __init__(self, client: Redis) -> None:
|
|
self._client = client
|
|
|
|
async def get(self, token_hash: str) -> Optional[str]:
|
|
"""Cached expiry, or None on a miss and when Redis cannot be reached."""
|
|
try:
|
|
return await self._client.get(_PREFIX + token_hash)
|
|
except Exception as exc:
|
|
logger.warning('session cache read skipped (%s)', type(exc).__name__)
|
|
return None
|
|
|
|
async def remember(
|
|
self,
|
|
token_hash: str,
|
|
expires_at: datetime,
|
|
now: datetime,
|
|
*,
|
|
only_if_absent: bool,
|
|
) -> None:
|
|
remaining_ms = int((expires_at - now).total_seconds() * 1000)
|
|
if remaining_ms <= 0:
|
|
await self.drop(token_hash)
|
|
return
|
|
try:
|
|
await self._client.set(
|
|
_PREFIX + token_hash,
|
|
_stamp(expires_at),
|
|
px=remaining_ms,
|
|
nx=only_if_absent,
|
|
)
|
|
except Exception as exc:
|
|
logger.warning('session cache write skipped (%s)', type(exc).__name__)
|
|
|
|
async def drop(self, token_hash: str) -> None:
|
|
try:
|
|
await self._client.delete(_PREFIX + token_hash)
|
|
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()
|