forked from mtusi2026/mtusi2026lab2
60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
import json
|
|
from typing import Optional
|
|
|
|
import redis.asyncio as redis
|
|
|
|
from app.config import config
|
|
|
|
CACHE_TTL_SECONDS = 30
|
|
|
|
|
|
class Cache:
|
|
def __init__(self, client: redis.Redis) -> None:
|
|
self._client = client
|
|
|
|
async def get_json(self, key: str) -> Optional[dict]:
|
|
raw = await self._client.get(key)
|
|
if raw is None:
|
|
return None
|
|
try:
|
|
return json.loads(raw)
|
|
except json.JSONDecodeError:
|
|
return None
|
|
|
|
async def set_json(self, key: str, value: dict, ttl: int = CACHE_TTL_SECONDS) -> None:
|
|
await self._client.set(key, json.dumps(value), ex=ttl)
|
|
|
|
async def delete(self, key: str) -> None:
|
|
await self._client.delete(key)
|
|
|
|
async def invalidate_chat(self, chat_id: str) -> None:
|
|
"""Удалить все ключи, связанные с чатом (история)."""
|
|
pattern = f"messages:{chat_id}:*"
|
|
cursor = 0
|
|
while True:
|
|
cursor, keys = await self._client.scan(cursor=cursor, match=pattern, count=100)
|
|
if keys:
|
|
await self._client.delete(*keys)
|
|
if cursor == 0:
|
|
break
|
|
|
|
async def try_lock(self, key: str, ttl: int = 5) -> bool:
|
|
"""Атомарно установить ключ. True — если установили мы."""
|
|
result = await self._client.set(key, "1", nx=True, ex=ttl)
|
|
return bool(result)
|
|
|
|
async def unlock(self, key: str) -> None:
|
|
await self._client.delete(key)
|
|
|
|
async def close(self) -> None:
|
|
await self._client.aclose()
|
|
|
|
|
|
def make_cache() -> Cache:
|
|
client = redis.from_url(
|
|
config.CACHE_URL,
|
|
decode_responses=True,
|
|
socket_connect_timeout=10,
|
|
socket_timeout=10,
|
|
)
|
|
return Cache(client) |