Files
2026-10-23 19:30:08 +03:00

52 lines
1.3 KiB
Python

"""Тонкая обёртка над Redis/Valkey."""
import logging
import threading
import time
import redis
from . import config
log = logging.getLogger("cache")
_client = None
_down_until = 0.0
_lock = threading.Lock()
def _get_client():
global _client
if not config.CACHE_URL:
return None
if _client is None:
with _lock:
if _client is None:
_client = redis.Redis.from_url(
config.CACHE_URL, socket_timeout=config.CACHE_TIMEOUT,
socket_connect_timeout=config.CACHE_TIMEOUT, max_connections=20,
decode_responses=True, retry_on_timeout=False)
return _client
def _call(fn):
global _down_until
client = _get_client()
if client is None or time.monotonic() < _down_until:
return None
try:
return fn(client)
except redis.RedisError as exc:
_down_until = time.monotonic() + config.CACHE_BACKOFF
log.warning("cache unavailable (%s); bypassing for %.0fs", type(exc).__name__, config.CACHE_BACKOFF)
return None
def get(key):
return _call(lambda c: c.get(key))
def set_if_absent(key, value, ttl_ms):
return _call(lambda c: c.set(key, value, nx=True, px=ttl_ms))
def set_always(key, value, ttl_ms):
return _call(lambda c: c.set(key, value, px=ttl_ms))