level 4: redis cache etc
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
"""Session lookup cache. 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:'
|
||||
|
||||
|
||||
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 close(self) -> None:
|
||||
await self._client.aclose()
|
||||
Reference in New Issue
Block a user