add code for level 5

This commit is contained in:
Матвей
2026-10-08 19:48:18 +03:00
parent 13fa322ca2
commit 744e941d55
11 changed files with 384 additions and 114 deletions
+49 -2
View File
@@ -1,4 +1,6 @@
import json
from asyncio import sleep
from secrets import token_urlsafe
from uuid import UUID
from redis.asyncio import Redis
@@ -8,11 +10,12 @@ from redis.exceptions import RedisError
class HistoryCache:
"""Кэш только первой страницы истории; PostgreSQL остаётся источником истины."""
def __init__(self, url: str | None, ttl_seconds: int) -> None:
def __init__(self, url: str | None, ttl_seconds: int, stampede_protection: bool) -> None:
self._url = url
self._ttl_seconds = ttl_seconds
self._client: Redis | None = None
self._disabled = not bool(url)
self._stampede_protection = stampede_protection
async def connect(self) -> None:
if self._disabled:
@@ -23,7 +26,7 @@ class HistoryCache:
decode_responses=True,
socket_connect_timeout=1,
socket_timeout=1,
max_connections=10,
max_connections=50,
)
await client.ping()
self._client = client
@@ -38,6 +41,10 @@ class HistoryCache:
def _key(chat_id: UUID, version: int, limit: int) -> str:
return f"history:first:{chat_id}:v{version}:l{limit}"
@classmethod
def _lock_key(cls, chat_id: UUID, version: int, limit: int) -> str:
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:
return None
@@ -58,3 +65,43 @@ class HistoryCache:
)
except RedisError:
self._disabled = True
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:
return None
token = token_urlsafe(16)
try:
locked = await self._client.set(
self._lock_key(chat_id, version, limit), token, nx=True, ex=2
)
return token if locked else ""
except RedisError:
self._disabled = True
return None
async def wait_for_fill(
self, chat_id: UUID, version: int, limit: int
) -> list[dict] | None:
for _ in range(20):
await sleep(0.05)
cached = await self.get(chat_id, version, limit)
if cached is not None or self._disabled:
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:
return
try:
await self._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