"""History pages are disposable; PostgreSQL owns both data and their version.""" import hashlib import json import os from redis.exceptions import RedisError from .auth import sessions class HistoryCache: def __init__(self, client, ttl=30, prefix='history'): self.client = client self.ttl = ttl self.prefix = prefix if ttl < 1: raise ValueError('CACHE_TTL_SECONDS must be positive') def key(self, chat_id, version, limit, after): page = json.dumps([limit, after], separators=(',', ':')) digest = hashlib.sha256(page.encode()).hexdigest() return f'{self.prefix}:{chat_id}:{version}:{digest}' def get_or_load(self, chat_id, version, limit, after, load): key = self.key(chat_id, version, limit, after) try: cached = self.client.get(key) except RedisError: return load() if cached is not None: return json.loads(cached) page = load() try: self.client.set(key, json.dumps(page, ensure_ascii=False), ex=self.ttl) except RedisError: pass return page history_cache = HistoryCache(sessions.client, int(os.getenv('CACHE_TTL_SECONDS', '30')))