Files
mtusi2026lab6/src/infra/cache/client.py
T
ricoromaandClaude Opus 5.5 9cc6c0c7a6 chore: port lab 5 solution into the lab 6 skeleton
Source: mtusi2026lab5-safronov, solution/bvt2301-safronov, 046ec9e.
Contracts, public tests and evidence of lab 5 are not carried over.
The compose project, image and CI prefix are renamed to lab6; the first
broker start defect is recorded in KNOWN_ISSUES.md; PLAN.md outlines the
OpenSpec changes of lab 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 04:46:56 +03:00

128 lines
5.4 KiB
Python

"""Клиент Valkey со сроком на команду и обходом при отказе.
redis-py по умолчанию повторяет команду с backoff: замороженный Valkey
задерживал запрос на 6 с вместо таймаута клиента (design change
`membership-cache`, Context). Здесь повтор один и только на обрыв
соединения (`ConnectionError`): старое соединение пула после рестарта
Valkey переоткрывается сразу, а таймаут не повторяется. Вся команда —
ожидание пула, соединение, повтор и ответ — ограничена
`[cache] timeout_seconds`. После отказа кэш пропускается на
`[cache] retry_after_seconds`: запросы идут сразу в PostgreSQL, не
дожидаясь таймаута каждый раз.
"""
import asyncio
import time
from redis.asyncio import BlockingConnectionPool, Redis
from redis.asyncio.retry import Retry
from redis.backoff import NoBackoff
from redis.exceptions import ConnectionError as RedisConnectionError
from redis.exceptions import RedisError
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,
timeout_seconds: float,
retry_after_seconds: float,
) -> None:
self.namespace = namespace
self._client = client
self._timeout_seconds = timeout_seconds
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:
async with asyncio.timeout(self._timeout_seconds):
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:
async with asyncio.timeout(self._timeout_seconds):
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 — один на отказ: неудачные пробы после пропуска молчат.
# TimeoutError от asyncio.timeout без текста — тогда repr
if self._skip_until is None:
logger.warning(
"Cache is unavailable",
error=str(error) or repr(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 пропускался бы как отказавший.
# Retry — из redis.asyncio: синхронный класс асинхронное соединение
# вызывает через await, и повтор молча не выполняется
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(), 1, supported_errors=(RedisConnectionError,)),
decode_responses=True,
)
return Cache(
Redis.from_pool(pool),
namespace=namespace,
timeout_seconds=cache.timeout_seconds,
retry_after_seconds=cache.retry_after_seconds,
)