forked from mtusi2026/mtusi2026lab2
add code for level 4
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
|
||||
class HistoryCache:
|
||||
"""Кэш только первой страницы истории; PostgreSQL остаётся источником истины."""
|
||||
|
||||
def __init__(self, url: str | None, ttl_seconds: int) -> None:
|
||||
self._url = url
|
||||
self._ttl_seconds = ttl_seconds
|
||||
self._client: Redis | None = None
|
||||
self._disabled = not bool(url)
|
||||
|
||||
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=10,
|
||||
)
|
||||
await client.ping()
|
||||
self._client = client
|
||||
except RedisError:
|
||||
self._disabled = True
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
|
||||
@staticmethod
|
||||
def _key(chat_id: UUID, version: int, limit: int) -> str:
|
||||
return f"history:first:{chat_id}:v{version}:l{limit}"
|
||||
|
||||
async def get(self, chat_id: UUID, version: int, limit: int) -> list[dict] | None:
|
||||
if self._disabled or self._client is None:
|
||||
return None
|
||||
try:
|
||||
value = await self._client.get(self._key(chat_id, version, limit))
|
||||
return json.loads(value) if value else None
|
||||
except (RedisError, ValueError, TypeError):
|
||||
self._disabled = True
|
||||
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:
|
||||
return
|
||||
try:
|
||||
encoded = json.dumps(items, default=str, separators=(",", ":"))
|
||||
await self._client.set(
|
||||
self._key(chat_id, version, limit), encoded, ex=self._ttl_seconds
|
||||
)
|
||||
except RedisError:
|
||||
self._disabled = True
|
||||
Reference in New Issue
Block a user