Не доверять кэшу сессий после рестарта API

Флаг очистки кэша жил только в памяти процесса. Сценарий: logout при
недоступном Valkey (отзыв записан в PostgreSQL, tombstone нет) -> рестарт
API -> Valkey вернулся. Новый процесс читал устаревшую положительную запись,
и отозванный токен получал 200 на /users/me и 201 на отправку сообщения
до истечения TTL записи (до 60 s).

Теперь процесс стартует с включённым флагом и выполняет FLUSHDB перед
первым использованием кэша. Добавлен регрессионный тест
test_logout_during_outage_then_api_restart, evidence и отчёт обновлены.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-03 10:31:12 +03:00
co-authored by Claude Opus 5.5
parent 8e97518120
commit ed012ba09d
9 changed files with 126 additions and 81 deletions
+10 -5
View File
@@ -10,9 +10,10 @@ lived copy of "token hash -> user" to avoid a SQL lookup on every request:
population uses SET ... NX, so a concurrent request cannot resurrect a
revoked session in the cache;
- any Valkey error or timeout is a cache miss: requests go to PostgreSQL and
the cache is skipped for CACHE_RETRY_AFTER_SECONDS. After such an error the
cache is flushed before its next use, because an invalidation may have
been lost while Valkey was unreachable.
the cache is skipped for CACHE_RETRY_AFTER_SECONDS. After such an error,
and on every API process start, the cache is flushed before its next use,
because an invalidation may have been lost while Valkey was unreachable
(also by a previous API process).
"""
from __future__ import annotations
@@ -76,7 +77,11 @@ class SessionCache:
def __init__(self, url: str | None) -> None:
self._client: Redis | None = None
self._unavailable_until = 0.0
self._needs_flush = False
# A process never trusts a cache it has not flushed itself: an
# earlier process may have lost an invalidation (logout while
# Valkey was unreachable) and that knowledge died with it.
# Cleared only after a successful FLUSHDB.
self._needs_flush = True
if url:
pool = ConnectionPool.from_url(
@@ -105,7 +110,7 @@ class SessionCache:
if self._needs_flush:
await self._client.flushdb()
self._needs_flush = False
logger.warning("session cache recovered and was flushed")
logger.warning("session cache flushed before use")
return True, await operation(self._client)
except (RedisError, OSError, TimeoutError) as exc:
self._unavailable_until = (