Files
mtusi2026lab2-safronov/src/infra/cache/client.py
T
ricoromaandClaude Opus 5.5 cae4b09147 feat: cache chat cards in Valkey
Valkey 9.1 in compose caches the immutable chat card (title, members,
created_at) used by GET /chats/{id} and by the membership check of the
message endpoints. Cache-aside with a write after commit, keys per
database, TTL plus allkeys-lru, persistence off. redis-py runs without
retries; on failure the cache is skipped for a few seconds and requests
go to PostgreSQL. Readiness does not depend on Valkey.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:17:55 +03:00

114 lines
4.3 KiB
Python

"""Клиент Valkey без повторов и с обходом при отказе.
redis-py по умолчанию повторяет команду с backoff: замороженный Valkey
задерживал запрос на 6 с вместо таймаута клиента (design change
`membership-cache`, Context). Здесь повторов нет, а после отказа кэш
пропускается на `[cache] retry_after_seconds`: запросы идут сразу в
PostgreSQL, не дожидаясь таймаута каждый раз.
"""
import time
from redis.asyncio import BlockingConnectionPool, Redis
from redis.backoff import NoBackoff
from redis.exceptions import RedisError
from redis.retry import Retry
from src.config.settings import Cache as CacheSettings
from src.infra.logger import AbstractLogger, get_logger
logger: AbstractLogger = get_logger().bind(module="cache")
class Cache:
"""Кэш поверх клиента Valkey: отказ — промах, а не исключение.
`namespace` — имя базы PostgreSQL, из которой читаются значения: на
одном Valkey ключи разных баз не пересекаются.
"""
def __init__(
self,
client: Redis,
*,
namespace: str,
retry_after_seconds: float,
) -> None:
self.namespace = namespace
self._client = client
self._retry_after_seconds = retry_after_seconds
# monotonic-время конца пропуска; None — кэш работает
self._skip_until: float | None = None
async def get(self, key: str) -> str | None:
"""Значение ключа; `None` — промах, в том числе из-за отказа."""
if self._skipping():
return None
try:
value = await self._client.get(key)
except (RedisError, OSError) as e:
self._failed(e)
return None
self._succeeded()
return value
async def set(self, key: str, value: str, *, ttl_seconds: int) -> bool:
"""Записать со сроком; `False` — не записано из-за отказа."""
if self._skipping():
return False
try:
await self._client.set(key, value, ex=ttl_seconds)
except (RedisError, OSError) as e:
self._failed(e)
return False
self._succeeded()
return True
async def aclose(self) -> None:
await self._client.aclose()
def _skipping(self) -> bool:
return (
self._skip_until is not None
and time.monotonic() < self._skip_until
)
def _failed(self, error: Exception) -> None:
# warning — один на отказ: неудачные пробы после пропуска молчат
if self._skip_until is None:
logger.warning(
"Cache is unavailable",
error=str(error),
error_type=type(error).__name__,
retry_after_seconds=self._retry_after_seconds,
)
self._skip_until = time.monotonic() + self._retry_after_seconds
def _succeeded(self) -> None:
if self._skip_until is not None:
self._skip_until = None
logger.info("Cache is available again")
def create_cache(cache: CacheSettings, *, namespace: str) -> Cache:
"""Кэш с пулом и таймаутами из `[cache]`; соединения — лениво."""
# BlockingConnectionPool: при всплеске запросов ждёт свободное
# соединение, а обычный пул сразу бросал бы MaxConnectionsError, и
# здоровый Valkey пропускался бы как отказавший
pool = BlockingConnectionPool(
host=cache.host,
port=cache.port,
password=cache.password.get_secret_value() or None,
max_connections=cache.max_connections,
timeout=cache.timeout_seconds,
socket_timeout=cache.timeout_seconds,
socket_connect_timeout=cache.timeout_seconds,
retry=Retry(NoBackoff(), 0),
decode_responses=True,
)
return Cache(
Redis.from_pool(pool),
namespace=namespace,
retry_after_seconds=cache.retry_after_seconds,
)