restore Redis cache after outage
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Матвей
2026-10-09 20:38:43 +03:00
parent 744e941d55
commit 7cda433085
4 changed files with 119 additions and 40 deletions
+66 -32
View File
@@ -1,5 +1,6 @@
import json
from asyncio import sleep
from asyncio import Lock, sleep
from time import monotonic
from secrets import token_urlsafe
from uuid import UUID
@@ -14,28 +15,55 @@ class HistoryCache:
self._url = url
self._ttl_seconds = ttl_seconds
self._client: Redis | None = None
self._disabled = not bool(url)
self._reconnect_lock = Lock()
self._next_reconnect_at = 0.0
self._stampede_protection = stampede_protection
async def connect(self) -> None:
if self._disabled:
return
try:
client = Redis.from_url(
self._url,
decode_responses=True,
socket_connect_timeout=1,
socket_timeout=1,
max_connections=50,
)
await client.ping()
self._client = client
except RedisError:
self._disabled = True
await self._client_or_none()
async def _client_or_none(self) -> Redis | None:
"""Возвращает рабочий клиент или временно обходит кэш при отказе Redis."""
if not self._url:
return None
if self._client is not None:
return self._client
if monotonic() < self._next_reconnect_at:
return None
async with self._reconnect_lock:
if self._client is not None:
return self._client
if monotonic() < self._next_reconnect_at:
return None
try:
client = Redis.from_url(
self._url,
decode_responses=True,
socket_connect_timeout=1,
socket_timeout=1,
max_connections=50,
)
await client.ping()
self._client = client
return client
except RedisError:
self._next_reconnect_at = monotonic() + 1
return None
async def _mark_unavailable(self, client: Redis) -> None:
"""Отбрасывает сломанное соединение и разрешает повторное подключение."""
async with self._reconnect_lock:
if self._client is client:
self._client = None
self._next_reconnect_at = monotonic() + 1
await client.aclose()
async def close(self) -> None:
if self._client is not None:
await self._client.aclose()
if self._client is None:
return
await self._client.aclose()
self._client = None
@staticmethod
def _key(chat_id: UUID, version: int, limit: int) -> str:
@@ -46,39 +74,44 @@ class HistoryCache:
return cls._key(chat_id, version, limit) + ":lock"
async def get(self, chat_id: UUID, version: int, limit: int) -> list[dict] | None:
if self._disabled or self._client is None:
client = await self._client_or_none()
if client is None:
return None
try:
value = await self._client.get(self._key(chat_id, version, limit))
value = await client.get(self._key(chat_id, version, limit))
return json.loads(value) if value else None
except (RedisError, ValueError, TypeError):
self._disabled = True
except RedisError:
await self._mark_unavailable(client)
return None
except (ValueError, TypeError):
return None
async def set(self, chat_id: UUID, version: int, limit: int, items: list[dict]) -> None:
if self._disabled or self._client is None:
client = await self._client_or_none()
if client is None:
return
try:
encoded = json.dumps(items, default=str, separators=(",", ":"))
await self._client.set(
await client.set(
self._key(chat_id, version, limit), encoded, ex=self._ttl_seconds
)
except RedisError:
self._disabled = True
await self._mark_unavailable(client)
async def acquire_load_lock(
self, chat_id: UUID, version: int, limit: int
) -> str | None:
if self._disabled or self._client is None or not self._stampede_protection:
client = await self._client_or_none()
if client is None or not self._stampede_protection:
return None
token = token_urlsafe(16)
try:
locked = await self._client.set(
locked = await client.set(
self._lock_key(chat_id, version, limit), token, nx=True, ex=2
)
return token if locked else ""
except RedisError:
self._disabled = True
await self._mark_unavailable(client)
return None
async def wait_for_fill(
@@ -87,21 +120,22 @@ class HistoryCache:
for _ in range(20):
await sleep(0.05)
cached = await self.get(chat_id, version, limit)
if cached is not None or self._disabled:
if cached is not None or self._client is None:
return cached
return None
async def release_load_lock(
self, chat_id: UUID, version: int, limit: int, token: str
) -> None:
if self._disabled or self._client is None:
client = await self._client_or_none()
if client is None:
return
try:
await self._client.eval(
await client.eval(
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0",
1,
self._lock_key(chat_id, version, limit),
token,
)
except RedisError:
self._disabled = True
await self._mark_unavailable(client)