import time from redis.asyncio import BlockingConnectionPool, Redis from redis.asyncio.retry import Retry from redis.backoff import NoBackoff from starlette.requests import HTTPConnection from config import ( LOGGER, VALKEY_HOST, VALKEY_PASS, VALKEY_POOL_MAX_SIZE, VALKEY_PORT, VALKEY_RETRY_AFTER_SEC, VALKEY_TIMEOUT_SEC, ) class CacheManager: """ Клиент Valkey: ограниченный пул, короткие таймауты, без встроенных повторов. """ def __init__( self, host: str, port: int, password: str, max_size: int, timeout: float, retry_after: float, ) -> None: self._host = host self._port = port self._password = password self.max_size = max_size self.timeout = timeout self.retry_after = retry_after self.client: Redis | None = None self._disabled_until = 0.0 def create_client(self) -> Redis: """Создание клиента; соединения открываются лениво при первом запросе""" if self.client is None: pool = BlockingConnectionPool( host=self._host, port=self._port, password=self._password, max_connections=self.max_size, timeout=self.timeout, socket_timeout=self.timeout, socket_connect_timeout=self.timeout, retry=Retry(NoBackoff(), 0), ) self.client = Redis(connection_pool=pool) LOGGER.info( f"Клиент Valkey создан: {self._host}:{self._port}, " f"pool: {self.max_size}, timeout: {self.timeout} с" ) return self.client @property def is_available(self) -> bool: return time.monotonic() >= self._disabled_until def mark_failed(self, error: Exception) -> None: """Обход кэша на retry_after секунд после ошибки Valkey""" if self.is_available: LOGGER.warning( f"Valkey недоступен ({type(error).__name__}): кэш сессий " f"обходится {self.retry_after} с, запросы идут в PostgreSQL" ) self._disabled_until = time.monotonic() + self.retry_after async def close(self) -> None: if self.client is not None: await self.client.aclose() self.client = None def get_cache(connection: HTTPConnection) -> CacheManager: """Получение менеджера кэша, созданного в lifespan.""" cache: CacheManager = connection.app.state.cache return cache cache_manager = CacheManager( host=VALKEY_HOST, port=VALKEY_PORT, password=VALKEY_PASS, max_size=VALKEY_POOL_MAX_SIZE, timeout=VALKEY_TIMEOUT_SEC, retry_after=VALKEY_RETRY_AFTER_SEC, )