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>
This commit is contained in:
2026-10-01 21:17:55 +03:00
co-authored by Claude Opus 5.5
parent c7681b0e18
commit cae4b09147
46 changed files with 1769 additions and 210 deletions
+6
View File
@@ -0,0 +1,6 @@
from src.infra.cache.client import Cache, create_cache
__all__ = [
"Cache",
"create_cache",
]
+113
View File
@@ -0,0 +1,113 @@
"""Клиент 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,
)
+13
View File
@@ -0,0 +1,13 @@
"""Кэш процесса API (Valkey).
Создаётся при импорте по `settings.cache`, соединения пул открывает
лениво. Импортируют модуль только `src/main.py` (закрытие в lifespan) и
`src/api/dependencies.py`, как `src/infra/db/session.py`. Ключи — по
имени базы из `settings.database`: `make test_isolated` с базой
`test_<db>` не видит карточек рабочей.
"""
from src.config import settings
from src.infra.cache.client import create_cache
cache = create_cache(settings.cache, namespace=settings.database.name)