Завершить уровень 4: проверить отказы, поочерёдную замену и ограничить ожидания кэша

This commit is contained in:
2026-10-23 19:09:56 +03:00
parent bdcf00a412
commit d30f418cec
33 changed files with 1962 additions and 40 deletions
+19 -2
View File
@@ -1,6 +1,8 @@
"""Необязательный кэш неизменяемого публичного профиля; ошибки обходятся через БД."""
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
@@ -14,12 +16,27 @@ class ProfileCache:
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.client.get('profile:v1:'+user_id)
value = self._bounded(self.client.get, 'profile:v1:'+user_id)
if value:
user=User.model_validate_json(value)
if user.id != user_id:
@@ -35,7 +52,7 @@ class ProfileCache:
def put(self, user):
if self.client:
try:
self.client.set('profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl)
self._bounded(self.client.set, 'profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl)
except RedisError:
self.errors += 1