Files
mtusi2026lab3/src/cache.py
T

61 lines
2.5 KiB
Python

"""Необязательный кэш неизменяемого публичного профиля; ошибки обходятся через БД."""
import logging
import os
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
import threading
from redis import Redis, RedisError
from pydantic import ValidationError
from src.config import setting
from src.models import User
class ProfileCache:
def __init__(self):
url = setting('CACHE_URL')
self.client = Redis.from_url(url, decode_responses=True, socket_connect_timeout=0.2,
socket_timeout=0.2, max_connections=16) if url else None
self.ttl = int(os.getenv('PROFILE_CACHE_TTL_SECONDS','60'))
self.hits = self.misses = self.errors = 0
# DNS может ждать дольше socket timeout; один фоновый вызов ограничивает и время, и очередь.
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='profile-cache')
self._pending = None
self._guard = threading.Lock()
def _bounded(self, action, *args, **kwargs):
with self._guard:
if self._pending is not None and not self._pending.done():
raise RedisError('кэш занят')
self._pending = self._executor.submit(action, *args, **kwargs)
future = self._pending
try:
return future.result(timeout=0.25)
except FutureTimeout:
raise RedisError('истекло время ожидания кэша') from None
def get(self, user_id):
if not self.client:
return None
try:
value = self._bounded(self.client.get, 'profile:v1:'+user_id)
if value:
user=User.model_validate_json(value)
if user.id != user_id:
raise ValueError('неверный ключ кэша')
self.hits += 1
return user
self.misses += 1
except (RedisError, ValidationError, ValueError):
self.errors += 1
logging.getLogger(__name__).warning('Кэш профиля недоступен; чтение из PostgreSQL')
return None
def put(self, user):
if self.client:
try:
self._bounded(self.client.set, 'profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl)
except RedisError:
self.errors += 1
profile_cache = ProfileCache()