Завершить уровень 4: проверить отказы, поочерёдную замену и ограничить ожидания кэша
This commit is contained in:
+19
-2
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user