lab2 fix
This commit is contained in:
+34
-35
@@ -1,42 +1,41 @@
|
||||
APP_ENV=dev
|
||||
|
||||
APP_SERVER_HOST=0.0.0.0
|
||||
APP_SERVER_PORT=8080
|
||||
APP_SERVER_READ_HEADER_TIMEOUT=10s
|
||||
APP_SERVER_SHUTDOWN_TIMEOUT=10s
|
||||
SERVER_HOST=0.0.0.0
|
||||
SERVER_PORT=8080
|
||||
SERVER_READ_HEADER_TIMEOUT=10s
|
||||
SERVER_SHUTDOWN_TIMEOUT=10s
|
||||
|
||||
APP_LOG_LEVEL=info
|
||||
APP_LOG_FORMAT=json
|
||||
LOG_LEVEL=info
|
||||
LOG_FORMAT=json
|
||||
|
||||
APP_POSTGRES_HOST=localhost
|
||||
APP_POSTGRES_PORT=5432
|
||||
APP_POSTGRES_DATABASE=messenger
|
||||
APP_POSTGRES_USER=messenger
|
||||
APP_POSTGRES_PASSWORD=messenger
|
||||
APP_POSTGRES_SSL_MODE=disable
|
||||
APP_POSTGRES_MAX_CONNS=10
|
||||
APP_POSTGRES_MIN_CONNS=1
|
||||
APP_POSTGRES_MAX_CONN_LIFETIME=1h
|
||||
APP_POSTGRES_MAX_CONN_IDLE_TIME=30m
|
||||
APP_POSTGRES_CONNECT_TIMEOUT=5s
|
||||
APP_POSTGRES_QUERY_TIMEOUT=5s
|
||||
POSTGRES_HOST=localhost
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_DATABASE=messenger
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=messenger
|
||||
POSTGRES_SSL_MODE=disable
|
||||
POSTGRES_MAX_CONNS=10
|
||||
POSTGRES_MIN_CONNS=1
|
||||
POSTGRES_MAX_CONN_LIFETIME=1h
|
||||
POSTGRES_MAX_CONN_IDLE_TIME=30m
|
||||
POSTGRES_CONNECT_TIMEOUT=5s
|
||||
POSTGRES_QUERY_TIMEOUT=5s
|
||||
|
||||
APP_REDIS_ENABLED=true
|
||||
APP_REDIS_HOST=localhost
|
||||
APP_REDIS_PORT=6379
|
||||
APP_REDIS_PASSWORD=
|
||||
APP_REDIS_DB=0
|
||||
APP_REDIS_MAX_RETRIES=3
|
||||
APP_REDIS_DIAL_TIMEOUT=5s
|
||||
APP_REDIS_READ_TIMEOUT=3s
|
||||
APP_REDIS_WRITE_TIMEOUT=3s
|
||||
APP_REDIS_POOL_SIZE=10
|
||||
REDIS_ENABLED=true
|
||||
REDIS_HOST=localhost
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=
|
||||
REDIS_DB=0
|
||||
# -1 disables go-redis retries; 0 keeps the library default (3 retries).
|
||||
REDIS_MAX_RETRIES=-1
|
||||
REDIS_DIAL_TIMEOUT=300ms
|
||||
REDIS_READ_TIMEOUT=200ms
|
||||
REDIS_WRITE_TIMEOUT=200ms
|
||||
REDIS_POOL_SIZE=10
|
||||
|
||||
APP_CACHE_ENABLED=true
|
||||
APP_CACHE_CHAT_LIST_TTL=5m
|
||||
APP_CACHE_SESSION_TTL=5m
|
||||
APP_CACHE_LOCK_TTL=10s
|
||||
APP_CACHE_LOCK_WAIT_TIMEOUT=2s
|
||||
APP_CACHE_LOCK_TIMEOUT_POLICY=error
|
||||
CACHE_ENABLED=true
|
||||
CACHE_CHAT_LIST_TTL=5m
|
||||
CACHE_LOCK_TTL=10s
|
||||
CACHE_LOCK_WAIT_TIMEOUT=2s
|
||||
|
||||
APP_SESSION_TTL_SECONDS=3600
|
||||
SESSION_TTL_SECONDS=3600
|
||||
|
||||
+1
-1
@@ -36,6 +36,6 @@ USER 10001:10001
|
||||
EXPOSE 8080
|
||||
STOPSIGNAL SIGTERM
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget -q -O /dev/null "http://127.0.0.1:${APP_SERVER_PORT}/health/live" || exit 1
|
||||
CMD wget -q -O /dev/null "http://127.0.0.1:${SERVER_PORT:-8080}/health/live" || exit 1
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||
|
||||
@@ -104,32 +104,41 @@ docker rm -f mtusi-messenger-lab1
|
||||
|
||||
### Источник истины и роли Redis
|
||||
|
||||
PostgreSQL — источник истины для пользователей, чатов, членства, сообщений и сессий. Redis 7.4 — вспомогательный слой с двумя ролями:
|
||||
PostgreSQL — источник истины для пользователей, чатов, членства, сообщений и сессий. Сессии хранятся только в PostgreSQL: `Resolve` по `token_hash` — это дешёвый lookup по первичному ключу, поэтому отдельный кэш сессий не используется, а отзыв всегда авторитетен (нет рассогласования кэша и БД). Redis 7.4 используется для двух задач:
|
||||
|
||||
1. **Кэш сессий** (read-through): `Resolve` сначала читает Redis, при промахе/ошибке идёт в PostgreSQL и заполняет кэш на срок `min(остаток TTL сессии, cache.session_ttl)`. `Credentials` и `Revoke` всегда идут в PostgreSQL; `Revoke` дополнительно evict'ит запись из Redis.
|
||||
2. **Кэш первой страницы списка чатов** (read-through + stampede protection): кэшируется только `ListVisible(after == nil)`; более глубокие страницы обслуживаются напрямую из PostgreSQL.
|
||||
1. **Кэш первой страницы списка чатов** (read-through + stampede protection): кэшируется только `ListVisible(after == nil)`; более глубокие страницы обслуживаются напрямую из PostgreSQL.
|
||||
2. **Распределённая координация загрузки** (distributed lock), чтобы при нескольких репликах холодный ключ грузила только одна.
|
||||
|
||||
Реализация — декораторы `internal/storage/redis/{session,chat}_repository.go` над интерфейсами `session.Repository`/`chat.Repository`.
|
||||
Реализация — декоратор `internal/storage/redis/chat_repository.go` над интерфейсом `chat.Repository`.
|
||||
|
||||
### Конфигурация и отключение
|
||||
|
||||
- `APP_REDIS_ENABLED=false` — Redis не подключается, сессии и список чатов полностью на PostgreSQL (`cache.NoOpCache`).
|
||||
- `APP_CACHE_ENABLED=false` — сессии кэшируются, кэш списка чатов выключен.
|
||||
- `APP_CACHE_CHAT_LIST_TTL` (по умолчанию `5m`) — TTL записей списка чатов.
|
||||
- `APP_CACHE_SESSION_TTL` (по умолчанию `5m`) — максимальный TTL записи сессии в Redis; он ограничивает окно при сбое eviction во время logout.
|
||||
- `APP_CACHE_LOCK_TTL` (по умолчанию `10s`), `APP_CACHE_LOCK_WAIT_TIMEOUT` (по умолчанию `2s`) и `APP_CACHE_LOCK_TIMEOUT_POLICY` (по умолчанию `error`, альтернатива `load`) — TTL распределённой блокировки, бюджет ожидания и поведение при таймауте ожидания.
|
||||
- `REDIS_ENABLED=false` — Redis не подключается; список чатов обслуживается напрямую из PostgreSQL.
|
||||
- `CACHE_ENABLED=false` — кэш списка чатов выключен. `CACHE_ENABLED=true` при `REDIS_ENABLED=false` даёт ошибку конфигурации.
|
||||
- `CACHE_CHAT_LIST_TTL` (по умолчанию `5m`) — TTL записей списка чатов.
|
||||
- `CACHE_LOCK_TTL` (по умолчанию `10s`) и `CACHE_LOCK_WAIT_TIMEOUT` (по умолчанию `2s`) — TTL распределённой блокировки и бюджет ожидания лидера.
|
||||
- `REDIS_DIAL_TIMEOUT` (по умолчанию `300ms`), `REDIS_READ_TIMEOUT`/`REDIS_WRITE_TIMEOUT` (по умолчанию `200ms`), `REDIS_MAX_RETRIES` (по умолчанию `-1`). Короткие таймауты и отсутствие ретраев (`-1`, а не `0` — у go-redis `0` включает дефолтные 3 ретрая) не дают «замороженному» Redis подвешивать API.
|
||||
- Бюджет кэш-фазы `500ms` (константа декоратора) ограничивает ожидание вызывающего; по истечении — fallback в PostgreSQL.
|
||||
- `SESSION_TTL_SECONDS` (по умолчанию `3600`) — TTL серверной сессии; контрактное имя переменной, читается напрямую.
|
||||
- Redis настроен с `--appendonly yes --appendfsync everysec --save 60 1` и named volume, поэтому переживает рестарт хранилища.
|
||||
- Переменные окружения без префикса (`SERVER_*`, `LOG_*`, `POSTGRES_*`, `REDIS_*`, `CACHE_*`, `SESSION_TTL_SECONDS`), что соответствует 12-factor.
|
||||
|
||||
### Инвалидация
|
||||
|
||||
Вместо точечного удаления ключей используется **поколение на пользователя**: ключ записи — `chat_list:<user>:<gen>:<limit>`, где `<gen>` читается из `chat_gen:<user>`. При создании чата декоратор записывает новый случайный `<gen>` каждому участнику, после чего все прежние записи становятся недостижимыми и истекают по TTL. Это race-safe: медленное чтение в полёте может заполнить только устаревшее поколение, которое уже никем не читается. Поколение также позволяет не удалять ключи для каждого возможного `limit`.
|
||||
Версия списка чатов хранится в **PostgreSQL** (`user_chat_versions`) и увеличивается в **той же транзакции**, что и вставка чата и участников. Ключ кэша — `chat_list:<user>:<version>:<limit>`, где версия читается из источника перед обращением к кэшу (`ListVersion`). Сигнал об устаревании больше не живёт в Redis, поэтому его потеря невозможна: даже если Redis недоступен в момент создания чата, версия в PostgreSQL уже увеличена, и следующий `ListVisible` читает новый ключ (промах → свежий список). Старые записи под прежней версией становятся недостижимыми и истекают по TTL; персистентность Redis на корректность не влияет.
|
||||
|
||||
Порядок «сначала версия, потом данные»: данные под ключом версии v загружаются после чтения v, поэтому могут быть свежее v, но не старше. Гонка даёт лишний промах на следующем запросе, но не устаревшую выдачу.
|
||||
|
||||
Для защиты от deadlock вход `BumpChatListVersions` сортируется (`ORDER BY m` и Go-сортировка) и дедуплицируется (`DISTINCT`/`slices.Compact`): параллельные транзакции с пересекающимися участниками берут эксклюзивные блокировки строк `user_chat_versions` в одном порядке. В `AddChatMembers` передаётся исходный список участников, поэтому дубликаты по-прежнему дают `409 conflict`, как и раньше.
|
||||
|
||||
### Деградация при потере Redis
|
||||
|
||||
- `SessionRepository.Resolve`: ошибка Redis (не «miss») → чтение из PostgreSQL, запрос обслуживается.
|
||||
- `ChatRepository.ListVisible`: ошибка Redis → `loader` выполняет запрос к PostgreSQL, кэш не используется.
|
||||
- `ChatRepository.ListVisible`: ошибка **кэша** (Redis недоступен, таймаут ожидания, битая запись) → прямой запрос в PostgreSQL; 503 от кэша не возвращается.
|
||||
- Ошибка **источника** (PostgreSQL) пробрасывается клиенту без повторного запроса — декоратор различает ошибку источника и ошибку кэша, поэтому упавшая БД не получает удвоенную нагрузку.
|
||||
- `GET /health/ready` проверяет PostgreSQL через агрегатор `internal/health`. Redis не является критичной зависимостью: при его потере кэш обходится через PostgreSQL, а readiness остаётся успешным.
|
||||
- Неверный/отозванный/анонимный токен по-прежнему даёт `401`, даже если Redis недоступен: `Resolve` идёт в PostgreSQL и возвращает `ErrUnauthenticated`.
|
||||
- Сессии и авторизация не зависят от Redis: `Resolve` всегда читает PostgreSQL, поэтому отозванный, истёкший или анонимный токен даёт `401` независимо от состояния Redis.
|
||||
|
||||
**Проверка деградации** (`scripts/redis_outage_check.sh` → `evidence/cache/redis-outage.txt`): скрипт останавливает и «замораживает» (`docker pause`) Redis, проверяет бюджет по времени и статусы, создаёт чат во время `pause` и подтверждает, что после `unpause` список содержит новый чат. Результат прогона: baseline 6 ms; после `docker stop` 476 ms; 30 параллельных `GET /chats` при `docker pause` — max 215 ms, p95 214 ms (бюджет 2000 ms); создание чата при `pause` = 201; после восстановления новый чат виден за 5 ms; зависших `lock:*` без TTL нет.
|
||||
|
||||
### Трек 1: согласованность кэша
|
||||
|
||||
@@ -142,13 +151,13 @@ PostgreSQL — источник истины для пользователей,
|
||||
|
||||
**Дедлайн загрузки.** `loader` выполняется с дедлайном `lock_ttl − 1s`; `ReleaseLock` возвращает признак «лок был наш», поэтому если загрузка превысила TTL, в лог пишется предупреждение `lock expired before release: loader slower than lock ttl`. Конструктор отвергает конфигурацию с `lock_ttl ≤ 1s` и `wait_timeout > lock_ttl`.
|
||||
|
||||
**Ожидание и таймаут.** Проигравшие сначала проверяют кэш без сна, затем опрашивают его с экспоненциальным backoff и jitter (50, 100, 200, 400, 500 ms, cap 500). Исход ожидания явный: `waitHit`, `waitRetry` (лок исчез без значения → повторить захват), `waitDegraded` (Redis недоступен → прямая загрузка), `waitTimeout` (держатель держит лок дольше `cache.lock_wait_timeout`). Поведение на `waitTimeout` — конфигурируемая политика `cache.lock_timeout_policy`: `error` (по умолчанию, отдаёт `503 unavailable`, не нагружая БД) или `load` (прямая загрузка, важно для авторизации).
|
||||
**Ожидание и таймаут.** Проигравшие сначала проверяют кэш без сна, затем опрашивают его с экспоненциальным backoff и jitter (50, 100, 200, 400, 500 ms, cap 500). Исход ожидания явный: `waitHit`, `waitRetry` (лок исчез без значения → повторить захват), `waitDegraded` (Redis недоступен → прямая загрузка), `waitTimeout` (держатель держит лок дольше `cache.lock_wait_timeout`). И `waitDegraded`, и `waitTimeout` ведут к прямой загрузке из источника: кэш не должен ронять чтение, когда источник истины доступен.
|
||||
|
||||
Параметры координации задаются через конфиг (`cache.lock_ttl`, `cache.lock_wait_timeout`, `cache.lock_timeout_policy`) и env `APP_CACHE_LOCK_TTL`, `APP_CACHE_LOCK_WAIT_TIMEOUT`, `APP_CACHE_LOCK_TIMEOUT_POLICY`, что соответствует 12-factor.
|
||||
Параметры координации задаются через конфиг (`cache.lock_ttl`, `cache.lock_wait_timeout`) и env `CACHE_LOCK_TTL`, `CACHE_LOCK_WAIT_TIMEOUT`, что соответствует 12-factor.
|
||||
|
||||
Реализация: `internal/platform/cache/distributed.go` (`DistributedCache`), примитивы блокировки — `AcquireLock`/`ReleaseLock`/`LockHeld` в `RedisCache` (`internal/platform/cache/redis.go`).
|
||||
|
||||
**Методика.** Интеграционный тест `internal/storage/redis/chat_repository_test.go` использует реальный Redis и источник с учётом вызовов. Замеряется число обращений к источнику (`source.listCalls()`), которое для запроса списка чатов взаимно однозначно соответствует числу SQL-запросов.
|
||||
**Методика.** Интеграционный тест `internal/storage/redis/chat_repository_test.go` использует реальный Redis и сгенерированный мок источника; ожидания мока фиксируют, что источник вызван ровно один раз.
|
||||
|
||||
**Результат** (`evidence/cache/consistency.txt`):
|
||||
|
||||
@@ -160,9 +169,9 @@ PostgreSQL — источник истины для пользователей,
|
||||
|
||||
Строка с тремя экземплярами — доказательство координации через Redis: три независимых объекта `DistributedCache` (каждый со своим токеном блокировки) работают с общим Redis и дают ровно одну загрузку из PostgreSQL. Это тест нескольких логических инстансов в одном процессе; координация вынесена в Redis, поэтому она не зависит от локальной памяти процесса и работает для реальных реплик. Отдельный cross-process сценарий с несколькими контейнерами API не запускался.
|
||||
|
||||
**Read-after-write.** `TestCreateInvalidatesMemberCaches`: после `POST /chats` и создатель, и остальные участники немедленно видят новый чат в `GET /chats` — инвалидация поколения исключает stale read.
|
||||
**Read-after-write.** `TestCreateInvalidatesMemberCaches` (декоратор) и `TestCreateBumpsMemberListVersions` (Postgres): после `POST /chats` версия списка увеличивается у создателя и всех участников в той же транзакции, поэтому следующий `GET /chats` у обоих сразу видит новый чат — и на прогретом кэше, и после недоступности Redis.
|
||||
|
||||
**Восстановление после сброса кэша.** `TestEvictedCacheEntryReloadsFromSource`: после удаления записи из Redis следующее чтение перезагружает данные из PostgreSQL. `TestSessionRepositorySuite/TestExpiredSessionIsRejected` подтверждает, что истёкшая сессия отклоняется.
|
||||
**Восстановление после сброса кэша.** `TestEvictedCacheEntryReloadsFromSource` в `chat_repository_test.go`: после удаления записи из Redis следующее чтение перезагружает данные из PostgreSQL. `TestResolveRejectsExpiredToken` (postgres) подтверждает, что истёкшая сессия отклоняется.
|
||||
|
||||
**Persistence.** `make test-persistence ACTION_SCRIPT=scripts/restart.sh` проходит: API и все хранилища (PostgreSQL, Redis) перезапускаются с сохранением volumes, подтверждённые данные и действующая сессия сохраняются.
|
||||
|
||||
@@ -174,9 +183,9 @@ PostgreSQL — источник истины для пользователей,
|
||||
|
||||
| Режим | SQL-запросов | RPS | p50 | p95 | p99 |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| Baseline (no cache) | 10,000 | 7,985 | 6.14ms | 7.24ms | 8.71ms |
|
||||
| Redis cache (cold) | 1 | 25,374 | 1.90ms | 2.73ms | 3.53ms |
|
||||
| Redis cache (hot) | 0 | 25,564 | 1.91ms | 2.66ms | 3.31ms |
|
||||
| Baseline (no cache) | 10,000 | 6,742 | 7.23ms | 9.14ms | 11.26ms |
|
||||
| Redis cache (cold) | 1 | 11,886 | 4.07ms | 5.67ms | 6.56ms |
|
||||
| Redis cache (hot) | 0 | 12,600 | 3.87ms | 5.02ms | 5.84ms |
|
||||
|
||||
Таблица показывает арифметические средние метрик трёх прогонов из `performance.txt`; средние p95/p99 не являются процентилями объединённой выборки.
|
||||
|
||||
@@ -184,24 +193,30 @@ PostgreSQL — источник истины для пользователей,
|
||||
|
||||
Команда: `./scripts/api_cache_performance.sh`. Сырые результаты: `evidence/cache/api-performance.txt`.
|
||||
|
||||
Создаются 4 пользователя и 60 чатов: каждый пользователь владеет 15 чатами и входит ещё в чаты соседнего пользователя. Для каждого режима выполняется 1000 GET-запросов `GET /api/v1/chats?limit=50` с 8 конкурентными worker'ами. Перед запросами пользователи проходят регистрацию и Basic → Bearer-аутентификацию. API пересоздаётся с `APP_CACHE_ENABLED=false` и `APP_CACHE_ENABLED=true`; PostgreSQL, Redis и volumes сохраняются. Выполнено два последовательных прогона каждого режима.
|
||||
Создаются 4 пользователя и 60 чатов: каждый пользователь владеет 15 чатами и входит ещё в чаты соседнего пользователя. Для каждого режима выполняется 1000 GET-запросов `GET /api/v1/chats?limit=50` с 8 конкурентными worker'ами. Перед запросами пользователи проходят регистрацию и Basic → Bearer-аутентификацию. API пересоздаётся с `CACHE_ENABLED=false` и `CACHE_ENABLED=true`; PostgreSQL, Redis и volumes сохраняются. Выполнено два последовательных прогона каждого режима.
|
||||
|
||||
| Прогон | Режим | Requests | Workers | RPS | p50 | p95 | p99 |
|
||||
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 1 | Cache disabled | 1000 | 8 | 2,691 | 2.70ms | 4.31ms | 10.30ms |
|
||||
| 1 | Redis cache | 1000 | 8 | 3,024 | 2.41ms | 3.97ms | 5.21ms |
|
||||
| 2 | Cache disabled | 1000 | 8 | 2,774 | 2.64ms | 4.28ms | 6.42ms |
|
||||
| 2 | Redis cache | 1000 | 8 | 3,257 | 2.30ms | 3.69ms | 4.84ms |
|
||||
| 1 | Cache disabled | 1000 | 8 | 2,193 | 3.34ms | 5.24ms | 7.38ms |
|
||||
| 1 | Redis cache | 1000 | 8 | 2,353 | 3.08ms | 5.36ms | 6.62ms |
|
||||
| 2 | Cache disabled | 1000 | 8 | 1,971 | 3.68ms | 6.22ms | 8.55ms |
|
||||
| 2 | Redis cache | 1000 | 8 | 2,430 | 2.92ms | 5.48ms | 7.25ms |
|
||||
|
||||
Среднее: RPS вырос с **2,733 до 3,141 (+15%)**; p50 снизился с **2.67 до 2.36ms (-12%)**; p95 — с **4.29 до 3.83ms (-11%)**; p99 — с **8.36 до 5.03ms (-40%)**. Это black-box измерение полного HTTP-пути: маршрутизация, Bearer-аутентификация, PostgreSQL/Redis, сериализация JSON и сеть. Результат подтверждает прирост именно на уровне API, а не только внутренних репозиториев. Оба режима продолжают использовать Redis для кэша сессий; переключается только кэш списка чатов, координация которого идёт через распределённую блокировку Redis.
|
||||
Среднее: RPS вырос с **2,082 до 2,391 (+15%)**; p50 снизился с **3.51 до 3.00ms (-15%)**; p95 — с **5.73 до 5.42ms (-5%)**; p99 — с **7.97 до 6.93ms (-13%)**. Это black-box измерение полного HTTP-пути: маршрутизация, Bearer-аутентификация, PostgreSQL/Redis, сериализация JSON и сеть. Прирост меньше, чем в repo-эксперименте, потому что кэшированный путь теперь делает один дополнительный indexed-read версии списка в PostgreSQL на запрос. Сессии в обоих режимах хранятся в PostgreSQL; переключается только кэш списка чатов.
|
||||
|
||||
### Ограничения
|
||||
|
||||
- `cache.lock_wait_timeout` — бюджет ожидания для одного вызова. Перед polling выполняется немедленная проверка кэша; если значение ещё не появилось, следующий опрос происходит через 50 ms со случайным jitter.
|
||||
- Исход `waitTimeout` управляется `cache.lock_timeout_policy`: `error` возвращает `503 unavailable` без обращения к БД (защита от усиления нагрузки), `load` уходит в прямую загрузку (доступность). Для списка чатов выбран `error`.
|
||||
- Бюджет кэш-фазы `500ms` ограничивает ожидание вызывающего в `GetOrLoad`; по истечении клиент уходит в PostgreSQL, а фоновая загрузка (`context.WithoutCancel`) всё равно дорабатывает и заполняет кэш. Цена: при обрыве бюджета возможен второй запрос в PostgreSQL (дублирование). Бюджет заметно больше типичной латентности загрузки (<100 ms), поэтому на штатном пути не срабатывает.
|
||||
- Хвост `fill` после получения данных (синхронные `Set` ≤200 ms + `ReleaseLock` ≤300 ms) при blackhole может удерживать ответ до 500 ms; горутины для отложенного релиза не вводятся, чтобы не усложнять остановку сервиса.
|
||||
- Худший случай Redis-таймаутов на один запрос при частичной деградации — порядка `Get + AcquireLock + fill Get + Set + Release` (≈1.4 s); при полном blackhole первый же `Get` упирается в `read_timeout` (200 ms) и уходит в PostgreSQL.
|
||||
- Ошибки кэша (недоступный Redis, таймаут ожидания, битая запись) деградируют в прямой запрос к PostgreSQL; 503 от кэша не возвращается. Ошибка самого PostgreSQL пробрасывается клиенту без повторного запроса, чтобы не удваивать нагрузку на упавшую БД.
|
||||
- Битая запись кэша удаляется сразу при `Unmarshal`-ошибке, чтобы не гонять мусор до истечения TTL.
|
||||
- Ошибки источника не кэшируются. Внутри пода их раздаёт `singleflight`, поэтому усиление ограничено одним обращением на под; между подами распределённая блокировка не заменяет circuit breaker, и при недоступности БД возможно дополнительное обращение на реплику.
|
||||
- Каждый `ListVisible(after == nil)` читает версию списка из PostgreSQL (один indexed-read); это цена согласованности кэша с источником истины.
|
||||
- Кэшируется только первая страница списка чатов; это осознанный компромисс (основная доля чтений).
|
||||
- Ключ включает `limit`, поэтому разные `limit` не переиспользуют запись.
|
||||
- Дедупликация загрузок (`DistributedCache`) не зависит от локальной памяти процесса: координация вынесена в Redis. При недоступности Redis она теряется: каждый под загружает данные самостоятельно (stampede возвращается), но запросы продолжают обслуживаться — осознанный graceful degradation.
|
||||
- Если загрузка лидера превышает `cache.lock_ttl`, блокировка истекает и другая реплика может начать параллельную загрузку. Продление блокировки (watchdog) и fencing не реализованы; `loader` ограничен дедлайном `lock_ttl − 1s`, и превышение фиксируется предупреждением `lock expired before release`.
|
||||
- Кэш сессий оставлен без распределённой блокировки: поиск по `token_hash` — это дешёвый lookup по первичному ключу, а авторизация лежит на горячем пути, где polling-задержка недопустима. При необходимости сюда применяется политика `cache.lock_timeout_policy=load`.
|
||||
- Сессии хранятся только в PostgreSQL и не кэшируются: `Resolve` по `token_hash` — дешёвый lookup по первичному ключу, а отзыв всегда авторитетен (нет рассогласования кэша и БД).
|
||||
- Ключи старой схемы `chat_gen:*` (писались без TTL) больше не читаются; их можно удалить разово. Все актуальные ключи (`chat_list:*`, `lock:*`) создаются с TTL и самоочищаются.
|
||||
|
||||
+2
-18
@@ -70,18 +70,10 @@ func run(cfg config.Config, log *slog.Logger) error {
|
||||
pingers := []health.Pinger{store}
|
||||
|
||||
if cfg.Redis.Enabled {
|
||||
sessionRepo = storageredis.NewSessionRepository(
|
||||
store.Sessions(),
|
||||
redisCache,
|
||||
cfg.Cache.SessionTTL,
|
||||
log,
|
||||
)
|
||||
|
||||
if cfg.Cache.Enabled {
|
||||
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{
|
||||
LockTTL: cfg.Cache.LockTTL,
|
||||
WaitTimeout: cfg.Cache.LockWaitTimeout,
|
||||
TimeoutPolicy: timeoutPolicy(cfg.Cache.LockTimeoutPolicy),
|
||||
LockTTL: cfg.Cache.LockTTL,
|
||||
WaitTimeout: cfg.Cache.LockWaitTimeout,
|
||||
}, log)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build distributed cache: %w", err)
|
||||
@@ -180,11 +172,3 @@ func connectRedis(cfg config.Redis) (cache.LockStore, error) {
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func timeoutPolicy(value string) cache.TimeoutPolicy {
|
||||
if value == "load" {
|
||||
return cache.TimeoutLoad
|
||||
}
|
||||
|
||||
return cache.TimeoutError
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ postgres:
|
||||
port: 5432
|
||||
database: messenger
|
||||
user: messenger
|
||||
password: ${APP_POSTGRES_PASSWORD}
|
||||
password: ${POSTGRES_PASSWORD}
|
||||
ssl_mode: disable
|
||||
max_conns: 10
|
||||
min_conns: 1
|
||||
@@ -29,19 +29,18 @@ redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
db: 0
|
||||
max_retries: 3
|
||||
dial_timeout: 5s
|
||||
read_timeout: 3s
|
||||
write_timeout: 3s
|
||||
# -1 disables go-redis retries; 0 keeps the library default (3 retries).
|
||||
max_retries: -1
|
||||
dial_timeout: 300ms
|
||||
read_timeout: 200ms
|
||||
write_timeout: 200ms
|
||||
pool_size: 10
|
||||
|
||||
cache:
|
||||
enabled: true
|
||||
chat_list_ttl: 5m
|
||||
session_ttl: 5m
|
||||
lock_ttl: 10s
|
||||
lock_wait_timeout: 2s
|
||||
lock_timeout_policy: error
|
||||
|
||||
session:
|
||||
ttl_seconds: 3600
|
||||
|
||||
+17
-17
@@ -52,12 +52,12 @@ services:
|
||||
command: ["up"]
|
||||
environment:
|
||||
APP_CONFIG: /etc/messenger/dev/config.yaml
|
||||
APP_POSTGRES_HOST: postgres
|
||||
APP_POSTGRES_PORT: "5432"
|
||||
APP_POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
APP_POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
APP_POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
APP_POSTGRES_SSL_MODE: disable
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_SSL_MODE: disable
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -67,18 +67,18 @@ services:
|
||||
<<: *app
|
||||
environment:
|
||||
APP_CONFIG: /etc/messenger/dev/config.yaml
|
||||
APP_POSTGRES_HOST: postgres
|
||||
APP_POSTGRES_PORT: "5432"
|
||||
APP_POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
APP_POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
APP_POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
APP_POSTGRES_SSL_MODE: disable
|
||||
APP_REDIS_ENABLED: "${APP_REDIS_ENABLED:-true}"
|
||||
APP_REDIS_HOST: redis
|
||||
APP_REDIS_PORT: "6379"
|
||||
APP_CACHE_ENABLED: "${APP_CACHE_ENABLED:-true}"
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_SSL_MODE: disable
|
||||
REDIS_ENABLED: "${REDIS_ENABLED:-true}"
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: "6379"
|
||||
CACHE_ENABLED: "${CACHE_ENABLED:-true}"
|
||||
ports:
|
||||
- "127.0.0.1:${APP_SERVER_PORT:-8080}:8080"
|
||||
- "127.0.0.1:${SERVER_PORT:-8080}:8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
Vendored
+6
-6
@@ -1,11 +1,11 @@
|
||||
# API cache performance experiment
|
||||
# generated: 2026-10-06T14:45:30Z
|
||||
# generated: 2026-10-09T21:41:31Z
|
||||
running trial 1, cache=False, requests=1000
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.37162104109302163, "rps": 2690.9132945184524, "p50_ms": 2.7035834500566125, "p95_ms": 4.306332906708121, "p99_ms": 10.301249916665256, "trial": 1, "cache_enabled": false}
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.455918375053443, "rps": 2193.375074831716, "p50_ms": 3.3378750667907298, "p95_ms": 5.237665958702564, "p99_ms": 7.377958972938359, "trial": 1, "cache_enabled": false}
|
||||
running trial 1, cache=True, requests=1000
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.3306667919969186, "rps": 3024.1924021488035, "p50_ms": 2.4096459965221584, "p95_ms": 3.9726250106468797, "p99_ms": 5.2115831058472395, "trial": 1, "cache_enabled": true}
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.424924207967706, "rps": 2353.360861182094, "p50_ms": 3.075250016991049, "p95_ms": 5.355541012249887, "p99_ms": 6.619499996304512, "trial": 1, "cache_enabled": true}
|
||||
running trial 2, cache=False, requests=1000
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.36050741700455546, "rps": 2773.868033864512, "p50_ms": 2.6389374979771674, "p95_ms": 4.281750065274537, "p99_ms": 6.4238749910146, "trial": 2, "cache_enabled": false}
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.5072490000165999, "rps": 1971.4183763147382, "p50_ms": 3.680104040540755, "p95_ms": 6.2174160266295075, "p99_ms": 8.554207975976169, "trial": 2, "cache_enabled": false}
|
||||
running trial 2, cache=True, requests=1000
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.3070590420393273, "rps": 3256.7026633005735, "p50_ms": 2.3015625192783773, "p95_ms": 3.6923339357599616, "p99_ms": 4.840250010602176, "trial": 2, "cache_enabled": true}
|
||||
{"results": [{"requests": 1000, "workers": 8, "duration_seconds": 0.37162104109302163, "rps": 2690.9132945184524, "p50_ms": 2.7035834500566125, "p95_ms": 4.306332906708121, "p99_ms": 10.301249916665256, "trial": 1, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.3306667919969186, "rps": 3024.1924021488035, "p50_ms": 2.4096459965221584, "p95_ms": 3.9726250106468797, "p99_ms": 5.2115831058472395, "trial": 1, "cache_enabled": true}, {"requests": 1000, "workers": 8, "duration_seconds": 0.36050741700455546, "rps": 2773.868033864512, "p50_ms": 2.6389374979771674, "p95_ms": 4.281750065274537, "p99_ms": 6.4238749910146, "trial": 2, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.3070590420393273, "rps": 3256.7026633005735, "p50_ms": 2.3015625192783773, "p95_ms": 3.6923339357599616, "p99_ms": 4.840250010602176, "trial": 2, "cache_enabled": true}], "users": 4, "chats": 60, "sessions_cached_in_both_modes": true}
|
||||
{"requests": 1000, "workers": 8, "duration_seconds": 0.4116047500865534, "rps": 2429.51520795063, "p50_ms": 2.9188335174694657, "p95_ms": 5.480541964061558, "p99_ms": 7.245125016197562, "trial": 2, "cache_enabled": true}
|
||||
{"results": [{"requests": 1000, "workers": 8, "duration_seconds": 0.455918375053443, "rps": 2193.375074831716, "p50_ms": 3.3378750667907298, "p95_ms": 5.237665958702564, "p99_ms": 7.377958972938359, "trial": 1, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.424924207967706, "rps": 2353.360861182094, "p50_ms": 3.075250016991049, "p95_ms": 5.355541012249887, "p99_ms": 6.619499996304512, "trial": 1, "cache_enabled": true}, {"requests": 1000, "workers": 8, "duration_seconds": 0.5072490000165999, "rps": 1971.4183763147382, "p50_ms": 3.680104040540755, "p95_ms": 6.2174160266295075, "p99_ms": 8.554207975976169, "trial": 2, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.4116047500865534, "rps": 2429.51520795063, "p50_ms": 2.9188335174694657, "p95_ms": 5.480541964061558, "p99_ms": 7.245125016197562, "trial": 2, "cache_enabled": true}], "users": 4, "chats": 60, "sessions_cached_in_both_modes": true}
|
||||
|
||||
Vendored
+19
-22
@@ -1,39 +1,36 @@
|
||||
# Cache consistency evidence (track 1)
|
||||
# generated: 2026-10-06T14:43:46Z
|
||||
# generated: 2026-10-09T21:38:43Z
|
||||
# redis: localhost:6379 db=1
|
||||
|
||||
=== RUN TestChatRepositorySuite
|
||||
=== RUN TestChatRepositorySuite/TestBrokenCacheEntryIsDroppedAndRepopulated
|
||||
=== RUN TestChatRepositorySuite/TestCacheUnavailableFallsBackToSource
|
||||
=== RUN TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated
|
||||
chat_repository_test.go:167: distributed lock: 100 concurrent cold reads -> 1 source loads
|
||||
chat_repository_test.go:226: distributed lock: 100 concurrent cold reads -> 1 source load
|
||||
=== RUN TestChatRepositorySuite/TestConcurrentColdReadsWithoutProtectionStampede
|
||||
chat_repository_test.go:265: stampede demonstration: 100 concurrent reads -> 100 source loads
|
||||
chat_repository_test.go:427: stampede demonstration: 100 concurrent reads -> 100 source loads
|
||||
=== RUN TestChatRepositorySuite/TestCreateInvalidatesMemberCaches
|
||||
=== RUN TestChatRepositorySuite/TestDeeperPagesBypassCache
|
||||
=== RUN TestChatRepositorySuite/TestEvictedCacheEntryReloadsFromSource
|
||||
=== RUN TestChatRepositorySuite/TestFirstPageIsCached
|
||||
=== RUN TestChatRepositorySuite/TestLimitIsPartOfCacheKey
|
||||
=== RUN TestChatRepositorySuite/TestMultipleInstancesShareDistributedLock
|
||||
chat_repository_test.go:215: multi-instance distributed lock: 3 instances x 30 reads -> 1 source loads
|
||||
--- PASS: TestChatRepositorySuite (0.14s)
|
||||
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated (0.04s)
|
||||
chat_repository_test.go:276: multi-instance distributed lock: 3 instances x 30 reads -> 1 source load
|
||||
=== RUN TestChatRepositorySuite/TestSlowLoaderBeyondCacheBudgetReturnsData
|
||||
=== RUN TestChatRepositorySuite/TestSourceErrorIsNotRetried
|
||||
--- PASS: TestChatRepositorySuite (0.83s)
|
||||
--- PASS: TestChatRepositorySuite/TestBrokenCacheEntryIsDroppedAndRepopulated (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestCacheUnavailableFallsBackToSource (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated (0.03s)
|
||||
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsWithoutProtectionStampede (0.02s)
|
||||
--- PASS: TestChatRepositorySuite/TestCreateInvalidatesMemberCaches (0.01s)
|
||||
--- PASS: TestChatRepositorySuite/TestDeeperPagesBypassCache (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestEvictedCacheEntryReloadsFromSource (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestFirstPageIsCached (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestLimitIsPartOfCacheKey (0.01s)
|
||||
--- PASS: TestChatRepositorySuite/TestLimitIsPartOfCacheKey (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestMultipleInstancesShareDistributedLock (0.05s)
|
||||
=== RUN TestSessionRepositorySuite
|
||||
=== RUN TestSessionRepositorySuite/TestCacheTTLCapAndSessionExpiry
|
||||
=== RUN TestSessionRepositorySuite/TestEvictedCacheEntryReloadsFromSource
|
||||
=== RUN TestSessionRepositorySuite/TestExpiredSessionIsRejected
|
||||
=== RUN TestSessionRepositorySuite/TestResolveFallsBackToSourceOnMiss
|
||||
=== RUN TestSessionRepositorySuite/TestResolvePopulatesCacheAndServesFromIt
|
||||
=== RUN TestSessionRepositorySuite/TestRevokeEvictsCacheAndSource
|
||||
--- PASS: TestSessionRepositorySuite (0.01s)
|
||||
--- PASS: TestSessionRepositorySuite/TestCacheTTLCapAndSessionExpiry (0.00s)
|
||||
--- PASS: TestSessionRepositorySuite/TestEvictedCacheEntryReloadsFromSource (0.00s)
|
||||
--- PASS: TestSessionRepositorySuite/TestExpiredSessionIsRejected (0.00s)
|
||||
--- PASS: TestSessionRepositorySuite/TestResolveFallsBackToSourceOnMiss (0.00s)
|
||||
--- PASS: TestSessionRepositorySuite/TestResolvePopulatesCacheAndServesFromIt (0.00s)
|
||||
--- PASS: TestSessionRepositorySuite/TestRevokeEvictsCacheAndSource (0.00s)
|
||||
--- PASS: TestChatRepositorySuite/TestSlowLoaderBeyondCacheBudgetReturnsData (0.70s)
|
||||
--- PASS: TestChatRepositorySuite/TestSourceErrorIsNotRetried (0.00s)
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/redis 0.418s
|
||||
ok mtusi-messenger/internal/storage/redis 1.338s
|
||||
? mtusi-messenger/internal/storage/redis/mocks [no test files]
|
||||
|
||||
Vendored
+17
-16
@@ -1,25 +1,26 @@
|
||||
# Cache performance experiment
|
||||
# generated: 2026-10-06T15:53:01Z
|
||||
# generated: 2026-10-09T21:41:14Z
|
||||
go version go1.27.1 darwin/arm64
|
||||
Darwin arm64
|
||||
2026/10/06 18:53:02 OK 00001_init.sql (10.14ms)
|
||||
2026/10/06 18:53:02 goose: successfully migrated database to version: 1
|
||||
2026/10/10 00:41:15 OK 00001_init.sql (10.03ms)
|
||||
2026/10/10 00:41:15 OK 00002_user_chat_versions.sql (2.17ms)
|
||||
2026/10/10 00:41:15 goose: successfully migrated database to version: 2
|
||||
=== RUN TestCachePerformanceExperiment
|
||||
cache_performance_experiment_test.go:111: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.247s rps=8017 p50=6.073542ms p95=7.541167ms p99=9.156083ms
|
||||
cache_performance_experiment_test.go:112: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=434ms rps=23022 p50=2.045375ms p95=3.3065ms p99=4.115042ms
|
||||
cache_performance_experiment_test.go:113: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=399ms rps=25055 p50=1.948541ms p95=2.716833ms p99=3.293792ms
|
||||
--- PASS: TestCachePerformanceExperiment (2.38s)
|
||||
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.528s rps=6542 p50=7.490875ms p95=9.302792ms p99=10.779ms
|
||||
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=851ms rps=11749 p50=4.192709ms p95=5.318916ms p99=5.905625ms
|
||||
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=751ms rps=13320 p50=3.670958ms p95=4.644958ms p99=5.21475ms
|
||||
--- PASS: TestCachePerformanceExperiment (3.50s)
|
||||
=== RUN TestCachePerformanceExperiment
|
||||
cache_performance_experiment_test.go:111: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.275s rps=7844 p50=6.254833ms p95=7.301042ms p99=9.071333ms
|
||||
cache_performance_experiment_test.go:112: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=375ms rps=26668 p50=1.822291ms p95=2.375625ms p99=3.260166ms
|
||||
cache_performance_experiment_test.go:113: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=372ms rps=26890 p50=1.826083ms p95=2.368833ms p99=3.16875ms
|
||||
--- PASS: TestCachePerformanceExperiment (2.26s)
|
||||
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.415s rps=7066 p50=6.901958ms p95=8.697666ms p99=10.560416ms
|
||||
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=846ms rps=11815 p50=4.033083ms p95=6.0305ms p99=6.963417ms
|
||||
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=817ms rps=12234 p50=3.999959ms p95=5.060959ms p99=5.802042ms
|
||||
--- PASS: TestCachePerformanceExperiment (3.39s)
|
||||
=== RUN TestCachePerformanceExperiment
|
||||
cache_performance_experiment_test.go:111: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.236s rps=8093 p50=6.084917ms p95=6.878625ms p99=7.891209ms
|
||||
cache_performance_experiment_test.go:112: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=378ms rps=26432 p50=1.832208ms p95=2.499917ms p99=3.223166ms
|
||||
cache_performance_experiment_test.go:113: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=404ms rps=24747 p50=1.95875ms p95=2.878375ms p99=3.453333ms
|
||||
--- PASS: TestCachePerformanceExperiment (2.26s)
|
||||
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.511s rps=6618 p50=7.302667ms p95=9.420708ms p99=12.437917ms
|
||||
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=827ms rps=12093 p50=3.984125ms p95=5.655167ms p99=6.8085ms
|
||||
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=817ms rps=12247 p50=3.946959ms p95=5.363208ms p99=6.508458ms
|
||||
--- PASS: TestCachePerformanceExperiment (3.55s)
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/postgres 7.277s
|
||||
ok mtusi-messenger/internal/storage/postgres 10.978s
|
||||
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
|
||||
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
|
||||
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
baseline: 6ms
|
||||
after stop: 476ms
|
||||
stop: n=1 max=476ms p95=476ms budget=2000ms
|
||||
pause parallel: n=30 max=215ms p95=214ms budget=2000ms
|
||||
create during pause: 201
|
||||
after recovery: new chat visible, 5ms
|
||||
lock keys without TTL: 0
|
||||
PASS: redis outage handled within budget
|
||||
+30
-17
@@ -20,8 +20,8 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
envPrefix = "APP"
|
||||
configEnvKey = "APP_CONFIG"
|
||||
envKey = "APP_ENV"
|
||||
configName = "config"
|
||||
defaultEnv = "dev"
|
||||
configDir = "./config/"
|
||||
@@ -47,7 +47,7 @@ type Redis struct {
|
||||
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
||||
Password string `mapstructure:"password"`
|
||||
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
|
||||
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=0"`
|
||||
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"`
|
||||
DialTimeout time.Duration `mapstructure:"dial_timeout" validate:"omitempty,gt=0"`
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"omitempty,gt=0"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout" validate:"omitempty,gt=0"`
|
||||
@@ -55,12 +55,10 @@ type Redis struct {
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
|
||||
SessionTTL time.Duration `mapstructure:"session_ttl" validate:"required,gt=0"`
|
||||
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
|
||||
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
|
||||
LockTimeoutPolicy string `mapstructure:"lock_timeout_policy" validate:"required,oneof=error load"`
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
|
||||
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
|
||||
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
@@ -123,17 +121,15 @@ var defaults = map[string]any{
|
||||
"redis.host": "localhost",
|
||||
"redis.port": 6379,
|
||||
"redis.db": 0,
|
||||
"redis.max_retries": 3,
|
||||
"redis.dial_timeout": "5s",
|
||||
"redis.read_timeout": "3s",
|
||||
"redis.write_timeout": "3s",
|
||||
"redis.max_retries": -1,
|
||||
"redis.dial_timeout": "300ms",
|
||||
"redis.read_timeout": "200ms",
|
||||
"redis.write_timeout": "200ms",
|
||||
"redis.pool_size": 10,
|
||||
"cache.enabled": false,
|
||||
"cache.chat_list_ttl": "5m",
|
||||
"cache.session_ttl": "5m",
|
||||
"cache.lock_ttl": "10s",
|
||||
"cache.lock_wait_timeout": "2s",
|
||||
"cache.lock_timeout_policy": "error",
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
@@ -143,11 +139,16 @@ func Load() (Config, error) {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
v.SetEnvPrefix(envPrefix)
|
||||
v.AllowEmptyEnv(true)
|
||||
v.AutomaticEnv()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
|
||||
for key := range defaults {
|
||||
if err := v.BindEnv(key); err != nil {
|
||||
return Config{}, fmt.Errorf("bind env %q: %w", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("unmarshal config: %w", err)
|
||||
@@ -157,9 +158,21 @@ func Load() (Config, error) {
|
||||
return Config{}, fmt.Errorf("validate config: %w", err)
|
||||
}
|
||||
|
||||
if err := cfg.validateDependencies(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) validateDependencies() error {
|
||||
if c.Cache.Enabled && !c.Redis.Enabled {
|
||||
return errors.New("validate config: cache.enabled requires redis.enabled")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func configureSource(v *viper.Viper) error {
|
||||
for key, value := range defaults {
|
||||
v.SetDefault(key, value)
|
||||
@@ -170,7 +183,7 @@ func configureSource(v *viper.Viper) error {
|
||||
if path := os.Getenv(configEnvKey); path != "" {
|
||||
v.SetConfigFile(path)
|
||||
} else {
|
||||
env := os.Getenv(envPrefix + "_ENV")
|
||||
env := os.Getenv(envKey)
|
||||
if env == "" {
|
||||
env = defaultEnv
|
||||
}
|
||||
@@ -222,5 +235,5 @@ func envName(field reflect.StructField) string {
|
||||
return field.Name
|
||||
}
|
||||
|
||||
return envPrefix + "_" + strings.ToUpper(key)
|
||||
return strings.ToUpper(key)
|
||||
}
|
||||
|
||||
@@ -28,12 +28,12 @@ func TestDefaults(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestEnvOverridesDefaults(t *testing.T) {
|
||||
t.Setenv("APP_SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("APP_SERVER_PORT", "9090")
|
||||
t.Setenv("APP_SERVER_READ_HEADER_TIMEOUT", "3s")
|
||||
t.Setenv("APP_SERVER_SHUTDOWN_TIMEOUT", "30s")
|
||||
t.Setenv("APP_LOG_LEVEL", "debug")
|
||||
t.Setenv("APP_LOG_FORMAT", "console")
|
||||
t.Setenv("SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("SERVER_PORT", "9090")
|
||||
t.Setenv("SERVER_READ_HEADER_TIMEOUT", "3s")
|
||||
t.Setenv("SERVER_SHUTDOWN_TIMEOUT", "30s")
|
||||
t.Setenv("LOG_LEVEL", "debug")
|
||||
t.Setenv("LOG_FORMAT", "console")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
@@ -132,27 +132,36 @@ postgres:
|
||||
`)
|
||||
|
||||
t.Setenv("APP_CONFIG", path)
|
||||
t.Setenv("APP_SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("APP_POSTGRES_PASSWORD", "env")
|
||||
t.Setenv("SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("POSTGRES_PASSWORD", "env")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "APP_* переопределяет YAML")
|
||||
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "env переопределяет YAML")
|
||||
assert.Equal(t, 9999, cfg.Server.Port)
|
||||
assert.Equal(t, "env", cfg.Postgres.Password)
|
||||
}
|
||||
|
||||
func TestSessionTTLFromContractEnv(t *testing.T) {
|
||||
t.Setenv("SESSION_TTL_SECONDS", "2")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 2, cfg.Session.TTLSeconds)
|
||||
}
|
||||
|
||||
func TestInvalidValues(t *testing.T) {
|
||||
tests := map[string]map[string]string{
|
||||
"пустой server.host": {"APP_SERVER_HOST": ""},
|
||||
"host не адрес и не имя": {"APP_SERVER_HOST": "не адрес"},
|
||||
"порт ниже диапазона": {"APP_SERVER_PORT": "0"},
|
||||
"порт выше диапазона": {"APP_SERVER_PORT": "65536"},
|
||||
"нулевой read header timeout": {"APP_SERVER_READ_HEADER_TIMEOUT": "0s"},
|
||||
"отрицательный shutdown": {"APP_SERVER_SHUTDOWN_TIMEOUT": "-1s"},
|
||||
"неизвестный log level": {"APP_LOG_LEVEL": "trace"},
|
||||
"неизвестный log format": {"APP_LOG_FORMAT": "xml"},
|
||||
"пустой server.host": {"SERVER_HOST": ""},
|
||||
"host не адрес и не имя": {"SERVER_HOST": "не адрес"},
|
||||
"порт ниже диапазона": {"SERVER_PORT": "0"},
|
||||
"порт выше диапазона": {"SERVER_PORT": "65536"},
|
||||
"нулевой read header timeout": {"SERVER_READ_HEADER_TIMEOUT": "0s"},
|
||||
"отрицательный shutdown": {"SERVER_SHUTDOWN_TIMEOUT": "-1s"},
|
||||
"неизвестный log level": {"LOG_LEVEL": "trace"},
|
||||
"неизвестный log format": {"LOG_FORMAT": "xml"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
@@ -184,8 +193,8 @@ postgres:
|
||||
`)
|
||||
|
||||
tests := map[string]map[string]string{
|
||||
"неизвестный ssl mode": {"APP_POSTGRES_SSL_MODE": "bogus"},
|
||||
"отрицательный max_conns": {"APP_POSTGRES_MAX_CONNS": "-1"},
|
||||
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
|
||||
"отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
@@ -207,8 +216,8 @@ postgres:
|
||||
|
||||
func TestUnparsableValues(t *testing.T) {
|
||||
tests := map[string]map[string]string{
|
||||
"порт не число": {"APP_SERVER_PORT": "не-число"},
|
||||
"timeout не duration": {"APP_SERVER_READ_HEADER_TIMEOUT": "быстро"},
|
||||
"порт не число": {"SERVER_PORT": "не-число"},
|
||||
"timeout не duration": {"SERVER_READ_HEADER_TIMEOUT": "быстро"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
@@ -224,8 +233,8 @@ func TestUnparsableValues(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLoggerSettings(t *testing.T) {
|
||||
t.Setenv("APP_LOG_LEVEL", "warn")
|
||||
t.Setenv("APP_LOG_FORMAT", "console")
|
||||
t.Setenv("LOG_LEVEL", "warn")
|
||||
t.Setenv("LOG_FORMAT", "console")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
@@ -240,8 +249,8 @@ func TestLoggerSettings(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAddr(t *testing.T) {
|
||||
t.Setenv("APP_SERVER_HOST", "0.0.0.0")
|
||||
t.Setenv("APP_SERVER_PORT", "8080")
|
||||
t.Setenv("SERVER_HOST", "0.0.0.0")
|
||||
t.Setenv("SERVER_PORT", "8080")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
@@ -250,7 +259,7 @@ func TestAddr(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAddrWithIPv6Host(t *testing.T) {
|
||||
t.Setenv("APP_SERVER_HOST", "::1")
|
||||
t.Setenv("SERVER_HOST", "::1")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
@@ -259,7 +268,7 @@ func TestAddrWithIPv6Host(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLoadIsIndependentOfProcessState(t *testing.T) {
|
||||
t.Setenv("APP_SERVER_PORT", "7070")
|
||||
t.Setenv("SERVER_PORT", "7070")
|
||||
|
||||
first, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
@@ -277,25 +286,24 @@ func TestRedisDefaultsDisabled(t *testing.T) {
|
||||
assert.False(t, cfg.Redis.Enabled)
|
||||
assert.Equal(t, "localhost", cfg.Redis.Host)
|
||||
assert.Equal(t, 6379, cfg.Redis.Port)
|
||||
assert.Equal(t, 5*time.Second, cfg.Redis.DialTimeout)
|
||||
assert.Equal(t, -1, cfg.Redis.MaxRetries)
|
||||
assert.Equal(t, 300*time.Millisecond, cfg.Redis.DialTimeout)
|
||||
assert.Equal(t, 200*time.Millisecond, cfg.Redis.ReadTimeout)
|
||||
assert.Equal(t, 200*time.Millisecond, cfg.Redis.WriteTimeout)
|
||||
assert.False(t, cfg.Cache.Enabled)
|
||||
assert.Equal(t, 5*time.Minute, cfg.Cache.ChatListTTL)
|
||||
assert.Equal(t, 5*time.Minute, cfg.Cache.SessionTTL)
|
||||
assert.Equal(t, 10*time.Second, cfg.Cache.LockTTL)
|
||||
assert.Equal(t, 2*time.Second, cfg.Cache.LockWaitTimeout)
|
||||
assert.Equal(t, "error", cfg.Cache.LockTimeoutPolicy)
|
||||
}
|
||||
|
||||
func TestRedisEnvOverrides(t *testing.T) {
|
||||
t.Setenv("APP_REDIS_ENABLED", "true")
|
||||
t.Setenv("APP_REDIS_HOST", "cache")
|
||||
t.Setenv("APP_REDIS_PORT", "6380")
|
||||
t.Setenv("APP_CACHE_ENABLED", "true")
|
||||
t.Setenv("APP_CACHE_CHAT_LIST_TTL", "1m")
|
||||
t.Setenv("APP_CACHE_SESSION_TTL", "30s")
|
||||
t.Setenv("APP_CACHE_LOCK_TTL", "7s")
|
||||
t.Setenv("APP_CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
|
||||
t.Setenv("APP_CACHE_LOCK_TIMEOUT_POLICY", "load")
|
||||
t.Setenv("REDIS_ENABLED", "true")
|
||||
t.Setenv("REDIS_HOST", "cache")
|
||||
t.Setenv("REDIS_PORT", "6380")
|
||||
t.Setenv("CACHE_ENABLED", "true")
|
||||
t.Setenv("CACHE_CHAT_LIST_TTL", "1m")
|
||||
t.Setenv("CACHE_LOCK_TTL", "7s")
|
||||
t.Setenv("CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
@@ -305,28 +313,15 @@ func TestRedisEnvOverrides(t *testing.T) {
|
||||
assert.Equal(t, 6380, cfg.Redis.Port)
|
||||
assert.True(t, cfg.Cache.Enabled)
|
||||
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
|
||||
assert.Equal(t, 30*time.Second, cfg.Cache.SessionTTL)
|
||||
assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL)
|
||||
assert.Equal(t, 1500*time.Millisecond, cfg.Cache.LockWaitTimeout)
|
||||
assert.Equal(t, "load", cfg.Cache.LockTimeoutPolicy)
|
||||
}
|
||||
|
||||
func TestInvalidLockTimeoutPolicy(t *testing.T) {
|
||||
t.Setenv("APP_CACHE_LOCK_TIMEOUT_POLICY", "bogus")
|
||||
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
|
||||
var validationErrs validator.ValidationErrors
|
||||
require.ErrorAs(t, err, &validationErrs)
|
||||
}
|
||||
|
||||
func TestInvalidCacheTTL(t *testing.T) {
|
||||
for _, key := range []string{
|
||||
"APP_CACHE_CHAT_LIST_TTL",
|
||||
"APP_CACHE_SESSION_TTL",
|
||||
"APP_CACHE_LOCK_TTL",
|
||||
"APP_CACHE_LOCK_WAIT_TIMEOUT",
|
||||
"CACHE_CHAT_LIST_TTL",
|
||||
"CACHE_LOCK_TTL",
|
||||
"CACHE_LOCK_WAIT_TIMEOUT",
|
||||
} {
|
||||
for _, value := range []string{"0s", "-1s"} {
|
||||
t.Run(key+"/"+value, func(t *testing.T) {
|
||||
@@ -339,3 +334,10 @@ func TestInvalidCacheTTL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheRequiresRedis(t *testing.T) {
|
||||
t.Setenv("CACHE_ENABLED", "true")
|
||||
|
||||
_, err := config.Load()
|
||||
require.ErrorContains(t, err, "cache.enabled requires redis.enabled")
|
||||
}
|
||||
|
||||
+16
-27
@@ -20,22 +20,13 @@ const (
|
||||
DefaultLockTTL = 10 * time.Second
|
||||
DefaultWaitTimeout = 2 * time.Second
|
||||
minLockTTL = time.Second
|
||||
releaseTimeout = time.Second
|
||||
)
|
||||
|
||||
var ErrLoadInProgress = errors.New("distributed cache: load already in progress")
|
||||
|
||||
type TimeoutPolicy int
|
||||
|
||||
const (
|
||||
TimeoutError TimeoutPolicy = iota
|
||||
TimeoutLoad
|
||||
redisOpTimeout = 200 * time.Millisecond
|
||||
releaseTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
type DistributedConfig struct {
|
||||
LockTTL time.Duration
|
||||
WaitTimeout time.Duration
|
||||
TimeoutPolicy TimeoutPolicy
|
||||
LockTTL time.Duration
|
||||
WaitTimeout time.Duration
|
||||
}
|
||||
|
||||
type LockStore interface {
|
||||
@@ -49,7 +40,6 @@ type DistributedCache struct {
|
||||
store LockStore
|
||||
lockTTL time.Duration
|
||||
waitTimeout time.Duration
|
||||
policy TimeoutPolicy
|
||||
log *slog.Logger
|
||||
group singleflight.Group
|
||||
}
|
||||
@@ -73,15 +63,10 @@ func NewDistributed(store LockStore, cfg DistributedConfig, log *slog.Logger) (*
|
||||
return nil, fmt.Errorf("cache: wait timeout %s must not exceed lock ttl %s", cfg.WaitTimeout, cfg.LockTTL)
|
||||
}
|
||||
|
||||
if cfg.TimeoutPolicy != TimeoutError && cfg.TimeoutPolicy != TimeoutLoad {
|
||||
return nil, fmt.Errorf("cache: unknown wait-timeout policy %d", cfg.TimeoutPolicy)
|
||||
}
|
||||
|
||||
return &DistributedCache{
|
||||
store: store,
|
||||
lockTTL: cfg.LockTTL,
|
||||
waitTimeout: cfg.WaitTimeout,
|
||||
policy: cfg.TimeoutPolicy,
|
||||
log: log,
|
||||
}, nil
|
||||
}
|
||||
@@ -157,11 +142,7 @@ func (d *DistributedCache) getOrLoad(
|
||||
case waitDegraded:
|
||||
return loader(ctx)
|
||||
case waitTimeout:
|
||||
if d.policy == TimeoutLoad {
|
||||
return loader(ctx)
|
||||
}
|
||||
|
||||
return nil, ErrLoadInProgress
|
||||
return loader(ctx)
|
||||
case waitRetry:
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
@@ -193,19 +174,27 @@ func (d *DistributedCache) fill(
|
||||
}
|
||||
}()
|
||||
|
||||
if value, err := d.store.Get(base, key); err == nil {
|
||||
getCtx, cancelGet := context.WithTimeout(base, redisOpTimeout)
|
||||
value, err := d.store.Get(getCtx, key)
|
||||
cancelGet()
|
||||
|
||||
if err == nil {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
loadCtx, cancel := context.WithTimeout(base, d.lockTTL-minLockTTL)
|
||||
defer cancel()
|
||||
|
||||
value, err := loader(loadCtx)
|
||||
value, err = loader(loadCtx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if setErr := d.store.Set(base, key, value, ttl); setErr != nil {
|
||||
setCtx, cancelSet := context.WithTimeout(base, redisOpTimeout)
|
||||
setErr := d.store.Set(setCtx, key, value, ttl)
|
||||
cancelSet()
|
||||
|
||||
if setErr != nil {
|
||||
d.warn(base, "distributed cache write failed", key, setErr)
|
||||
}
|
||||
|
||||
|
||||
+63
-31
@@ -106,39 +106,11 @@ func TestDistributedDeduplicatesConcurrentMisses(t *testing.T) {
|
||||
require.Equal(t, int32(1), calls.Load(), "one instance must load once for concurrent misses")
|
||||
}
|
||||
|
||||
func TestDistributedTimeoutPolicyError(t *testing.T) {
|
||||
func TestDistributedFallsBackOnWaitTimeout(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{
|
||||
WaitTimeout: 100 * time.Millisecond,
|
||||
TimeoutPolicy: cache.TimeoutError,
|
||||
})
|
||||
ctx := context.Background()
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(false, nil).Once()
|
||||
store.EXPECT().LockHeld(mock.Anything, "lock:key").Return(true, nil).Maybe()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
_, err := dc.GetOrLoad(ctx, "key", time.Minute, func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
|
||||
return []byte("value"), nil
|
||||
})
|
||||
require.ErrorIs(t, err, cache.ErrLoadInProgress)
|
||||
require.Zero(t, calls.Load(), "the error policy must not fall back to a direct load")
|
||||
}
|
||||
|
||||
func TestDistributedTimeoutPolicyLoad(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{
|
||||
WaitTimeout: 100 * time.Millisecond,
|
||||
TimeoutPolicy: cache.TimeoutLoad,
|
||||
})
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{WaitTimeout: 100 * time.Millisecond})
|
||||
ctx := context.Background()
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
|
||||
@@ -154,7 +126,7 @@ func TestDistributedTimeoutPolicyLoad(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("fallback"), value)
|
||||
require.Equal(t, int32(1), calls.Load(), "the load policy must fall back to a direct load")
|
||||
require.Equal(t, int32(1), calls.Load(), "a wait timeout must fall back to a direct load")
|
||||
}
|
||||
|
||||
func TestDistributedSharedLoadSurvivesCallerCancellation(t *testing.T) {
|
||||
@@ -252,3 +224,63 @@ func TestDistributedRetriesWhenLockVanishes(t *testing.T) {
|
||||
require.Equal(t, []byte("recovered"), value)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestFillStoreCallsAreBoundedByDeadline(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
getBudgets []time.Duration
|
||||
setBudget time.Duration
|
||||
setHasDead bool
|
||||
)
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").RunAndReturn(func(ctx context.Context, _ string) ([]byte, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
getBudgets = append(getBudgets, time.Until(deadline))
|
||||
}
|
||||
|
||||
return nil, cache.ErrCacheMiss
|
||||
}).Twice()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, _ string, _ []byte, _ time.Duration) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
deadline, ok := ctx.Deadline()
|
||||
setHasDead = ok
|
||||
if ok {
|
||||
setBudget = time.Until(deadline)
|
||||
}
|
||||
|
||||
return nil
|
||||
}).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
_, err := dc.GetOrLoad(context.Background(), "key", time.Minute, func(context.Context) ([]byte, error) {
|
||||
return []byte("value"), nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
require.True(t, setHasDead, "Set must receive a bounded context")
|
||||
require.LessOrEqual(t, setBudget, 300*time.Millisecond)
|
||||
|
||||
minGetBudget := time.Hour
|
||||
for _, budget := range getBudgets {
|
||||
if budget < minGetBudget {
|
||||
minGetBudget = budget
|
||||
}
|
||||
}
|
||||
|
||||
require.LessOrEqual(t, minGetBudget, 300*time.Millisecond, "fill's Get must receive a bounded context")
|
||||
}
|
||||
|
||||
Vendored
+14
-10
@@ -28,16 +28,7 @@ type RedisCache struct {
|
||||
}
|
||||
|
||||
func NewRedis(cfg RedisConfig) (*RedisCache, error) {
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
MaxRetries: cfg.MaxRetries,
|
||||
DialTimeout: cfg.DialTimeout,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
PoolSize: cfg.PoolSize,
|
||||
})
|
||||
client := redis.NewClient(newClientOptions(cfg))
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
|
||||
defer cancel()
|
||||
@@ -51,6 +42,19 @@ func NewRedis(cfg RedisConfig) (*RedisCache, error) {
|
||||
return &RedisCache{client: client}, nil
|
||||
}
|
||||
|
||||
func newClientOptions(cfg RedisConfig) *redis.Options {
|
||||
return &redis.Options{
|
||||
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
MaxRetries: cfg.MaxRetries,
|
||||
DialTimeout: cfg.DialTimeout,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
PoolSize: cfg.PoolSize,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RedisCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
value, err := r.client.Get(ctx, key).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewClientOptionsAppliesTimeoutsAndRetries(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := redis.NewClient(newClientOptions(RedisConfig{
|
||||
Host: "localhost",
|
||||
Port: 6379,
|
||||
MaxRetries: -1,
|
||||
DialTimeout: 300 * time.Millisecond,
|
||||
ReadTimeout: 200 * time.Millisecond,
|
||||
WriteTimeout: 200 * time.Millisecond,
|
||||
PoolSize: 5,
|
||||
}))
|
||||
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
opts := client.Options()
|
||||
require.Equal(t, 0, opts.MaxRetries, "go-redis: -1 disables retries, 0 would restore the default of 3")
|
||||
require.Equal(t, 300*time.Millisecond, opts.DialTimeout)
|
||||
require.Equal(t, 200*time.Millisecond, opts.ReadTimeout)
|
||||
require.Equal(t, 200*time.Millisecond, opts.WriteTimeout)
|
||||
require.Equal(t, 5, opts.PoolSize)
|
||||
}
|
||||
@@ -51,6 +51,10 @@ func TestCacheLatencyExperiment(t *testing.T) {
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(t)
|
||||
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
return realChats.ListVersion(ctx, userID)
|
||||
}).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
@@ -67,6 +67,10 @@ func TestCachePerformanceExperiment(t *testing.T) {
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(t)
|
||||
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
return realChats.ListVersion(ctx, userID)
|
||||
}).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -44,6 +46,10 @@ func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (do
|
||||
return fmt.Errorf("add chat members: %w", mapError(err))
|
||||
}
|
||||
|
||||
if err := queries.BumpChatListVersions(ctx, sortedUnique(draft.MemberIDs)); err != nil {
|
||||
return fmt.Errorf("bump chat list versions: %w", mapError(err))
|
||||
}
|
||||
|
||||
created = mapChat(row.ID, row.Title, row.CreatedAt, draft.MemberIDs)
|
||||
|
||||
return nil
|
||||
@@ -54,6 +60,27 @@ func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (do
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
version, err := r.store.queries.GetChatListVersion(ctx, userID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("get chat list version: %w", mapError(err))
|
||||
}
|
||||
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func sortedUnique(ids []uuid.UUID) []uuid.UUID {
|
||||
sorted := slices.Clone(ids)
|
||||
slices.SortFunc(sorted, func(a, b uuid.UUID) int {
|
||||
return bytes.Compare(a[:], b[:])
|
||||
})
|
||||
|
||||
return slices.Compact(sorted)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -49,6 +52,85 @@ func (s *ChatRepositorySuite) TestCreateRejectsDuplicateMembers() {
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateBumpsMemberListVersions() {
|
||||
ctx := s.T().Context()
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
carol := s.createUser("carol")
|
||||
|
||||
s.createChat(alice, bob)
|
||||
|
||||
aliceVersion, err := s.store.Chats().ListVersion(ctx, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), aliceVersion, "creator version must be bumped")
|
||||
|
||||
bobVersion, err := s.store.Chats().ListVersion(ctx, bob.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), bobVersion, "member version must be bumped")
|
||||
|
||||
carolVersion, err := s.store.Chats().ListVersion(ctx, carol.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Zero(carolVersion, "non-member version must stay unchanged")
|
||||
|
||||
s.createChat(alice, carol)
|
||||
|
||||
aliceVersion, err = s.store.Chats().ListVersion(ctx, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(2), aliceVersion, "version must grow monotonically")
|
||||
|
||||
carolVersion, err = s.store.Chats().ListVersion(ctx, carol.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), carolVersion)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentCreateNoDeadlock() {
|
||||
ctx := s.T().Context()
|
||||
|
||||
users := make([]domain.User, 0, 8)
|
||||
for i := range 8 {
|
||||
users = append(users, s.createUser(fmt.Sprintf("member%d", i)))
|
||||
}
|
||||
|
||||
const workers = 16
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
errs := make(chan error, workers)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for w := range workers {
|
||||
go func(w int) {
|
||||
defer wg.Done()
|
||||
|
||||
ids := []uuid.UUID{
|
||||
users[w%len(users)].ID,
|
||||
users[(w+1)%len(users)].ID,
|
||||
users[(w+2)%len(users)].ID,
|
||||
}
|
||||
if w%2 == 1 {
|
||||
slices.Reverse(ids)
|
||||
}
|
||||
|
||||
_, err := s.store.Chats().Create(ctx, domain.ChatDraft{
|
||||
Title: fmt.Sprintf("chat-%d", w),
|
||||
MemberIDs: ids,
|
||||
CallerID: ids[0],
|
||||
})
|
||||
if err != nil {
|
||||
errs <- err
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
for err := range errs {
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateStoresAllMembers() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
|
||||
@@ -28,6 +28,19 @@ func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams)
|
||||
return err
|
||||
}
|
||||
|
||||
const bumpChatListVersions = `-- name: BumpChatListVersions :exec
|
||||
INSERT INTO user_chat_versions (user_id, version)
|
||||
SELECT DISTINCT m, 1
|
||||
FROM unnest($1::uuid[]) AS m
|
||||
ORDER BY m
|
||||
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1
|
||||
`
|
||||
|
||||
func (q *Queries) BumpChatListVersions(ctx context.Context, userIds []uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, bumpChatListVersions, userIds)
|
||||
return err
|
||||
}
|
||||
|
||||
const createChat = `-- name: CreateChat :one
|
||||
INSERT INTO chats (title)
|
||||
VALUES ($1)
|
||||
@@ -81,6 +94,19 @@ func (q *Queries) GetChatForMember(ctx context.Context, arg GetChatForMemberPara
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatListVersion = `-- name: GetChatListVersion :one
|
||||
SELECT COALESCE(MAX(version), 0)::bigint AS version
|
||||
FROM user_chat_versions
|
||||
WHERE user_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetChatListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, getChatListVersion, userID)
|
||||
var version int64
|
||||
err := row.Scan(&version)
|
||||
return version, err
|
||||
}
|
||||
|
||||
const listChatsForMember = `-- name: ListChatsForMember :many
|
||||
SELECT
|
||||
c.id,
|
||||
|
||||
@@ -44,3 +44,8 @@ type User struct {
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UserChatVersion struct {
|
||||
UserID uuid.UUID
|
||||
Version int64
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func (q *Queries) DeleteSession(ctx context.Context, arg DeleteSessionParams) er
|
||||
}
|
||||
|
||||
const getSessionUser = `-- name: GetSessionUser :one
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
@@ -62,12 +62,11 @@ WHERE s.token_hash = $1
|
||||
`
|
||||
|
||||
type GetSessionUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
ExpiresAt time.Time
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSessionUserRow, error) {
|
||||
@@ -78,7 +77,6 @@ func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSess
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
&i.ExpiresAt,
|
||||
)
|
||||
return i, err
|
||||
|
||||
@@ -44,6 +44,10 @@ CREATE TABLE sessions (
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE user_chat_versions (
|
||||
user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
|
||||
version bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_id_created_at_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
@@ -54,6 +58,9 @@ CREATE INDEX chat_members_user_id_chat_id_idx
|
||||
CREATE INDEX chats_created_at_id_idx
|
||||
ON chats (created_at, id);
|
||||
|
||||
CREATE INDEX sessions_user_id_idx
|
||||
ON sessions (user_id);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE sessions;
|
||||
@@ -61,3 +68,4 @@ DROP TABLE messages;
|
||||
DROP TABLE chat_members;
|
||||
DROP TABLE chats;
|
||||
DROP TABLE users;
|
||||
DROP TABLE user_chat_versions;
|
||||
|
||||
@@ -14,6 +14,18 @@ FROM unnest(sqlc.arg(user_ids)::uuid[]) AS input(id)
|
||||
LEFT JOIN users u ON u.id = input.id
|
||||
WHERE u.id IS NULL;
|
||||
|
||||
-- name: BumpChatListVersions :exec
|
||||
INSERT INTO user_chat_versions (user_id, version)
|
||||
SELECT DISTINCT m, 1
|
||||
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS m
|
||||
ORDER BY m
|
||||
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1;
|
||||
|
||||
-- name: GetChatListVersion :one
|
||||
SELECT COALESCE(MAX(version), 0)::bigint AS version
|
||||
FROM user_chat_versions
|
||||
WHERE user_id = sqlc.arg(user_id);
|
||||
|
||||
-- name: GetChatForMember :one
|
||||
SELECT
|
||||
c.id,
|
||||
|
||||
@@ -4,7 +4,7 @@ VALUES (sqlc.arg(token_hash), sqlc.arg(user_id), sqlc.arg(expires_at))
|
||||
RETURNING token_hash, user_id, expires_at;
|
||||
|
||||
-- name: GetSessionUser :one
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = sqlc.arg(token_hash)
|
||||
|
||||
@@ -80,14 +80,13 @@ func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (doma
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Revoke is intentionally idempotent: deleting an already absent session is a no-op.
|
||||
// The HTTP contract for DELETE /auth/sessions/current defines only 204/401, so a
|
||||
// missing session must not surface as an error.
|
||||
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := r.store.queries.DeleteSession(ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID}); err != nil {
|
||||
if err := r.store.queries.DeleteSession(
|
||||
ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID},
|
||||
); err != nil {
|
||||
return fmt.Errorf("revoke session: %w", mapError(err))
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
type ChatSource interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
|
||||
ListVersion(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
@@ -42,20 +43,21 @@ func NewChatRepository(
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
chat, err := r.source.Create(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
r.invalidate(ctx, draft.MemberIDs)
|
||||
|
||||
return chat, nil
|
||||
return r.source.Create(ctx, draft)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
return r.source.GetVisible(ctx, chatID, callerID)
|
||||
}
|
||||
|
||||
type sourceError struct{ err error }
|
||||
|
||||
func (e sourceError) Error() string { return e.err.Error() }
|
||||
|
||||
func (e sourceError) Unwrap() error { return e.err }
|
||||
|
||||
const cacheOperationTimeout = 500 * time.Millisecond
|
||||
|
||||
func (r *ChatRepository) ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
@@ -66,58 +68,54 @@ func (r *ChatRepository) ListVisible(
|
||||
return r.source.ListVisible(ctx, callerID, after, limit)
|
||||
}
|
||||
|
||||
key := chatListKey(callerID, r.generation(ctx, callerID), limit)
|
||||
version, err := r.source.ListVersion(ctx, callerID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("chat list version: %w", err)
|
||||
}
|
||||
|
||||
key := chatListKey(callerID, version, limit)
|
||||
|
||||
loader := func(ctx context.Context) ([]byte, error) {
|
||||
page, err := r.source.ListVisible(ctx, callerID, nil, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, sourceError{err}
|
||||
}
|
||||
|
||||
return json.Marshal(newChatPageDTO(page))
|
||||
}
|
||||
|
||||
encoded, err := r.cache.GetOrLoad(ctx, key, r.ttl, loader)
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOperationTimeout)
|
||||
defer cancel()
|
||||
|
||||
encoded, err := r.cache.GetOrLoad(cctx, key, r.ttl, loader)
|
||||
if err != nil {
|
||||
if errors.Is(err, cache.ErrLoadInProgress) {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("load chat list: %w", domain.ErrUnavailable)
|
||||
var sourceErr sourceError
|
||||
switch {
|
||||
case errors.As(err, &sourceErr):
|
||||
return domain.Page[domain.Chat]{}, sourceErr.err
|
||||
case ctx.Err() != nil:
|
||||
return domain.Page[domain.Chat]{}, ctx.Err()
|
||||
}
|
||||
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("load chat list: %w", err)
|
||||
}
|
||||
|
||||
var dto chatPageDTO
|
||||
if err := json.Unmarshal(encoded, &dto); err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("decode cached chat list: %w", err)
|
||||
}
|
||||
|
||||
return dto.toDomain(), nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) generation(ctx context.Context, userID uuid.UUID) string {
|
||||
value, err := r.cache.Get(ctx, chatGenKey(userID))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return string(value)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) invalidate(ctx context.Context, memberIDs []uuid.UUID) {
|
||||
for _, memberID := range memberIDs {
|
||||
if err := r.cache.Set(ctx, chatGenKey(memberID), []byte(uuid.NewString()), 0); err != nil && r.log != nil {
|
||||
r.log.WarnContext(ctx, "chat cache invalidation failed",
|
||||
slog.String("user_id", memberID.String()), slog.Any("error", err))
|
||||
} else {
|
||||
var dto chatPageDTO
|
||||
unmarshalErr := json.Unmarshal(encoded, &dto)
|
||||
if unmarshalErr == nil {
|
||||
return dto.toDomain(), nil
|
||||
}
|
||||
err = unmarshalErr
|
||||
|
||||
_ = r.cache.Delete(ctx, key)
|
||||
}
|
||||
|
||||
if r.log != nil {
|
||||
r.log.WarnContext(ctx, "chat list cache unavailable, falling back to source", slog.Any("error", err))
|
||||
}
|
||||
|
||||
return r.source.ListVisible(ctx, callerID, nil, limit)
|
||||
}
|
||||
|
||||
func chatGenKey(userID uuid.UUID) string {
|
||||
return "chat_gen:" + userID.String()
|
||||
}
|
||||
|
||||
func chatListKey(userID uuid.UUID, generation string, limit int) string {
|
||||
return fmt.Sprintf("chat_list:%s:%s:%d", userID, generation, limit)
|
||||
func chatListKey(userID uuid.UUID, version int64, limit int) string {
|
||||
return fmt.Sprintf("chat_list:%s:%d:%d", userID, version, limit)
|
||||
}
|
||||
|
||||
type chatPageDTO struct {
|
||||
|
||||
@@ -4,6 +4,7 @@ package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -15,8 +16,9 @@ import (
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
cachemocks "mtusi-messenger/internal/platform/cache/mocks"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/storage/redis/mocks"
|
||||
storagemocks "mtusi-messenger/internal/storage/redis/mocks"
|
||||
)
|
||||
|
||||
type ChatRepositorySuite struct {
|
||||
@@ -65,7 +67,8 @@ func (s *ChatRepositorySuite) TestFirstPageIsCached() {
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
@@ -92,10 +95,14 @@ func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
|
||||
}
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{chat}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVersion(mock.Anything, bob).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, bob, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
|
||||
source.EXPECT().Create(mock.Anything, mock.AnythingOfType("domain.ChatDraft")).Return(chat, nil).Once()
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(1), nil).Once()
|
||||
source.EXPECT().ListVersion(mock.Anything, bob).Return(int64(1), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, bob, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
|
||||
|
||||
@@ -122,13 +129,34 @@ func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
|
||||
s.Len(bobPage.Items, 1, "other member must observe the new chat immediately")
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Twice()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
|
||||
// Simulate a Redis flush/restart by dropping all cache entries.
|
||||
s.Require().NoError(flushRedisDB(ctx))
|
||||
|
||||
_, err = repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestDeeperPagesBypassCache() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
cursor := &domain.Cursor{Scope: alice, CreatedAt: time.Now().UTC(), ID: uuid.New()}
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, cursor, 50).Return(empty, nil).Twice()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
@@ -144,7 +172,8 @@ func (s *ChatRepositorySuite) TestLimitIsPartOfCacheKey() {
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 10).Return(empty, nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
|
||||
|
||||
@@ -161,7 +190,8 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
@@ -193,6 +223,7 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
|
||||
wg.Wait()
|
||||
|
||||
s.Require().Zero(failures.Load())
|
||||
s.T().Logf("distributed lock: %d concurrent cold reads -> 1 source load", workers)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
|
||||
@@ -200,7 +231,8 @@ func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
@@ -241,6 +273,108 @@ func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
|
||||
wg.Wait()
|
||||
|
||||
s.Require().Zero(failures.Load())
|
||||
s.T().Logf("multi-instance distributed lock: %d instances x %d reads -> 1 source load",
|
||||
instances, workersPerInstance)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCacheUnavailableFallsBackToSource() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
|
||||
|
||||
lockStore := cachemocks.NewMockLockStore(s.T())
|
||||
lockStore.EXPECT().Get(mock.Anything, mock.Anything).Return(nil, errors.New("redis down")).Maybe()
|
||||
|
||||
distributed, err := cache.NewDistributed(lockStore, cache.DistributedConfig{}, nil)
|
||||
s.Require().NoError(err)
|
||||
|
||||
repo := storageredis.NewChatRepository(source, distributed, time.Minute, nil)
|
||||
|
||||
got, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err, "cache failure must not fail the read")
|
||||
s.Empty(got.Items)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestBrokenCacheEntryIsDroppedAndRepopulated() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Times(3)
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Twice()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
key := "chat_list:" + alice.String() + ":0:50"
|
||||
s.Require().NoError(s.cache.Set(ctx, key, []byte("{not json"), time.Minute))
|
||||
|
||||
// 1st: garbage -> dropped -> source.
|
||||
first, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err, "a corrupted cache entry must not fail the read")
|
||||
|
||||
// 2nd: miss -> source -> repopulate.
|
||||
second, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
|
||||
// 3rd: served from cache, no source call.
|
||||
third, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal(first, second)
|
||||
s.Equal(second, third)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestSlowLoaderBeyondCacheBudgetReturnsData() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
release := make(chan struct{})
|
||||
var calls atomic.Int32
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
|
||||
if calls.Add(1) == 1 {
|
||||
<-release // the loader outlives the caller's cache budget
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}).Maybe()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
started := time.Now()
|
||||
got, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err, "budget expiry must fall back to the source, not fail")
|
||||
s.Empty(got.Items)
|
||||
s.GreaterOrEqual(time.Since(started), 450*time.Millisecond, "the caller must be bounded by the cache budget")
|
||||
|
||||
// Let the background loader finish before the test (and its mock) is torn down.
|
||||
close(release)
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestSourceErrorIsNotRetried() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
sentinel := errors.New("postgres down")
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
Return(domain.Page[domain.Chat]{}, sentinel).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().ErrorIs(err, sentinel, "source error must propagate")
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentColdReadsWithoutProtectionStampede() {
|
||||
@@ -251,7 +385,7 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsWithoutProtectionStampede()
|
||||
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//go:build integration
|
||||
|
||||
package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
)
|
||||
|
||||
const testRedisDB = 1
|
||||
|
||||
func redisEnv(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
func redisEnvInt(key string, fallback int) int {
|
||||
value := os.Getenv(key)
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
func testRedisConfig() cache.RedisConfig {
|
||||
return cache.RedisConfig{
|
||||
Host: redisEnv("TEST_REDIS_HOST", "localhost"),
|
||||
Port: redisEnvInt("TEST_REDIS_PORT", 6379),
|
||||
Password: os.Getenv("TEST_REDIS_PASSWORD"),
|
||||
DB: redisEnvInt("TEST_REDIS_DB", testRedisDB),
|
||||
MaxRetries: 3,
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 5,
|
||||
}
|
||||
}
|
||||
|
||||
func flushRedisDB(ctx context.Context) error {
|
||||
cfg := testRedisConfig()
|
||||
|
||||
client := goredis.NewClient(&goredis.Options{
|
||||
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
return client.FlushDB(ctx).Err()
|
||||
}
|
||||
@@ -186,6 +186,72 @@ func (_c *MockChatSource_GetVisible_Call) RunAndReturn(run func(ctx context.Cont
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVersion provides a mock function for the type MockChatSource
|
||||
func (_mock *MockChatSource) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
ret := _mock.Called(ctx, userID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVersion")
|
||||
}
|
||||
|
||||
var r0 int64
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (int64, error)); ok {
|
||||
return returnFunc(ctx, userID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) int64); ok {
|
||||
r0 = returnFunc(ctx, userID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(int64)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, userID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatSource_ListVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVersion'
|
||||
type MockChatSource_ListVersion_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVersion is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
func (_e *MockChatSource_Expecter) ListVersion(ctx any, userID any) *MockChatSource_ListVersion_Call {
|
||||
return &MockChatSource_ListVersion_Call{Call: _e.mock.On("ListVersion", ctx, userID)}
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVersion_Call) Run(run func(ctx context.Context, userID uuid.UUID)) *MockChatSource_ListVersion_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVersion_Call) Return(n int64, err error) *MockChatSource_ListVersion_Call {
|
||||
_c.Call.Return(n, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVersion_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID) (int64, error)) *MockChatSource_ListVersion_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVisible provides a mock function for the type MockChatSource
|
||||
func (_mock *MockChatSource) ListVisible(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
ret := _mock.Called(ctx, callerID, after, limit)
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockSessionSource creates a new instance of MockSessionSource. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockSessionSource(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockSessionSource {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockSessionSource{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockSessionSource is an autogenerated mock type for the SessionSource type
|
||||
type MockSessionSource struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockSessionSource_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockSessionSource) EXPECT() *MockSessionSource_Expecter {
|
||||
return &MockSessionSource_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockSessionSource
|
||||
func (_mock *MockSessionSource) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, session)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, session)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewSession) error); ok {
|
||||
r1 = returnFunc(ctx, session)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionSource_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockSessionSource_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - session domain.NewSession
|
||||
func (_e *MockSessionSource_Expecter) Create(ctx any, session any) *MockSessionSource_Create_Call {
|
||||
return &MockSessionSource_Create_Call{Call: _e.mock.On("Create", ctx, session)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Create_Call) Run(run func(ctx context.Context, session domain.NewSession)) *MockSessionSource_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.NewSession
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.NewSession)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Create_Call) Return(session1 domain.Session, err error) *MockSessionSource_Create_Call {
|
||||
_c.Call.Return(session1, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Create_Call) RunAndReturn(run func(ctx context.Context, session domain.NewSession) (domain.Session, error)) *MockSessionSource_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Credentials provides a mock function for the type MockSessionSource
|
||||
func (_mock *MockSessionSource) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
|
||||
ret := _mock.Called(ctx, username)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Credentials")
|
||||
}
|
||||
|
||||
var r0 domain.UserCredentials
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.UserCredentials, error)); ok {
|
||||
return returnFunc(ctx, username)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.UserCredentials); ok {
|
||||
r0 = returnFunc(ctx, username)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.UserCredentials)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, username)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionSource_Credentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Credentials'
|
||||
type MockSessionSource_Credentials_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Credentials is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - username string
|
||||
func (_e *MockSessionSource_Expecter) Credentials(ctx any, username any) *MockSessionSource_Credentials_Call {
|
||||
return &MockSessionSource_Credentials_Call{Call: _e.mock.On("Credentials", ctx, username)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Credentials_Call) Run(run func(ctx context.Context, username string)) *MockSessionSource_Credentials_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Credentials_Call) Return(userCredentials domain.UserCredentials, err error) *MockSessionSource_Credentials_Call {
|
||||
_c.Call.Return(userCredentials, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Credentials_Call) RunAndReturn(run func(ctx context.Context, username string) (domain.UserCredentials, error)) *MockSessionSource_Credentials_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Resolve provides a mock function for the type MockSessionSource
|
||||
func (_mock *MockSessionSource) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, tokenHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Resolve")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, tokenHash)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, tokenHash)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok {
|
||||
r1 = returnFunc(ctx, tokenHash)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionSource_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
|
||||
type MockSessionSource_Resolve_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Resolve is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - tokenHash []byte
|
||||
func (_e *MockSessionSource_Expecter) Resolve(ctx any, tokenHash any) *MockSessionSource_Resolve_Call {
|
||||
return &MockSessionSource_Resolve_Call{Call: _e.mock.On("Resolve", ctx, tokenHash)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Resolve_Call) Run(run func(ctx context.Context, tokenHash []byte)) *MockSessionSource_Resolve_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 []byte
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].([]byte)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Resolve_Call) Return(session domain.Session, err error) *MockSessionSource_Resolve_Call {
|
||||
_c.Call.Return(session, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Resolve_Call) RunAndReturn(run func(ctx context.Context, tokenHash []byte) (domain.Session, error)) *MockSessionSource_Resolve_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Revoke provides a mock function for the type MockSessionSource
|
||||
func (_mock *MockSessionSource) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
ret := _mock.Called(ctx, userID, tokenHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Revoke")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []byte) error); ok {
|
||||
r0 = returnFunc(ctx, userID, tokenHash)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockSessionSource_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
|
||||
type MockSessionSource_Revoke_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Revoke is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - tokenHash []byte
|
||||
func (_e *MockSessionSource_Expecter) Revoke(ctx any, userID any, tokenHash any) *MockSessionSource_Revoke_Call {
|
||||
return &MockSessionSource_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, tokenHash)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte)) *MockSessionSource_Revoke_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 []byte
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]byte)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Revoke_Call) Return(err error) *MockSessionSource_Revoke_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionSource_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte) error) *MockSessionSource_Revoke_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
)
|
||||
|
||||
type SessionSource interface {
|
||||
Credentials(ctx context.Context, username string) (domain.UserCredentials, error)
|
||||
Create(ctx context.Context, session domain.NewSession) (domain.Session, error)
|
||||
Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error)
|
||||
Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error
|
||||
}
|
||||
|
||||
type SessionRepository struct {
|
||||
source SessionSource
|
||||
cache cache.Cache
|
||||
ttlCap time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewSessionRepository(
|
||||
source SessionSource,
|
||||
cache cache.Cache,
|
||||
ttlCap time.Duration,
|
||||
log *slog.Logger,
|
||||
) *SessionRepository {
|
||||
return &SessionRepository{source: source, cache: cache, ttlCap: ttlCap, log: log}
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
|
||||
return r.source.Credentials(ctx, username)
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
|
||||
return r.source.Create(ctx, session)
|
||||
}
|
||||
|
||||
type cachedSession struct {
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User cachedUser `json:"user"`
|
||||
}
|
||||
|
||||
type cachedUser struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func newCachedSession(session domain.Session) cachedSession {
|
||||
return cachedSession{
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
User: cachedUser{
|
||||
ID: session.User.ID,
|
||||
Username: session.User.Username,
|
||||
DisplayName: session.User.DisplayName,
|
||||
CreatedAt: session.User.CreatedAt,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c cachedSession) toDomain() domain.Session {
|
||||
return domain.Session{
|
||||
ExpiresAt: c.ExpiresAt,
|
||||
User: domain.User{
|
||||
ID: c.User.ID,
|
||||
Username: c.User.Username,
|
||||
DisplayName: c.User.DisplayName,
|
||||
CreatedAt: c.User.CreatedAt,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
|
||||
key := sessionKey(tokenHash)
|
||||
|
||||
if cached, err := r.cache.Get(ctx, key); err == nil {
|
||||
var session cachedSession
|
||||
if unmarshalErr := json.Unmarshal(cached, &session); unmarshalErr == nil {
|
||||
if session.User.ID != uuid.Nil && time.Now().Before(session.ExpiresAt) {
|
||||
return session.toDomain(), nil
|
||||
}
|
||||
_ = r.cache.Delete(ctx, key)
|
||||
}
|
||||
}
|
||||
|
||||
session, err := r.source.Resolve(ctx, tokenHash)
|
||||
if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
|
||||
if ttl := min(time.Until(session.ExpiresAt), r.ttlCap); ttl > 0 {
|
||||
if encoded, marshalErr := json.Marshal(newCachedSession(session)); marshalErr == nil {
|
||||
if err := r.cache.Set(ctx, key, encoded, ttl); err != nil && r.log != nil {
|
||||
r.log.WarnContext(ctx, "session cache write failed", slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
key := sessionKey(tokenHash)
|
||||
|
||||
if err := r.cache.Delete(ctx, key); err != nil && r.log != nil {
|
||||
r.log.WarnContext(ctx, "session cache eviction failed", slog.Any("error", err))
|
||||
}
|
||||
|
||||
if err := r.source.Revoke(ctx, userID, tokenHash); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func sessionKey(tokenHash []byte) string {
|
||||
return "session:" + hex.EncodeToString(tokenHash)
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/storage/redis/mocks"
|
||||
)
|
||||
|
||||
const testRedisDB = 1
|
||||
|
||||
func redisEnv(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
func redisEnvInt(key string, fallback int) int {
|
||||
value := os.Getenv(key)
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
func testRedisConfig() cache.RedisConfig {
|
||||
return cache.RedisConfig{
|
||||
Host: redisEnv("TEST_REDIS_HOST", "localhost"),
|
||||
Port: redisEnvInt("TEST_REDIS_PORT", 6379),
|
||||
Password: os.Getenv("TEST_REDIS_PASSWORD"),
|
||||
DB: redisEnvInt("TEST_REDIS_DB", testRedisDB),
|
||||
MaxRetries: 3,
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 5,
|
||||
}
|
||||
}
|
||||
|
||||
type SessionRepositorySuite struct {
|
||||
suite.Suite
|
||||
|
||||
cache *cache.RedisCache
|
||||
client *goredis.Client
|
||||
}
|
||||
|
||||
func TestSessionRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(SessionRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) SetupSuite() {
|
||||
cfg := testRedisConfig()
|
||||
|
||||
var err error
|
||||
|
||||
s.cache, err = cache.NewRedis(cfg)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.client = goredis.NewClient(&goredis.Options{
|
||||
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
|
||||
s.Require().NoError(s.client.Ping(s.T().Context()).Err())
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TearDownSuite() {
|
||||
if s.client != nil {
|
||||
s.Require().NoError(s.client.Close())
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
s.Require().NoError(s.cache.Close())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) SetupTest() {
|
||||
s.Require().NoError(s.client.FlushDB(s.T().Context()).Err())
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) newRepo(source storageredis.SessionSource) *storageredis.SessionRepository {
|
||||
s.T().Helper()
|
||||
|
||||
return storageredis.NewSessionRepository(source, s.cache, 5*time.Minute, nil)
|
||||
}
|
||||
|
||||
func testSession(userID uuid.UUID, expiresAt time.Time) domain.Session {
|
||||
return domain.Session{
|
||||
ExpiresAt: expiresAt,
|
||||
User: domain.User{
|
||||
ID: userID,
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestCacheTTLCapAndSessionExpiry() {
|
||||
ctx := s.T().Context()
|
||||
|
||||
for _, remaining := range []time.Duration{time.Hour, time.Minute} {
|
||||
hash := []byte(uuid.NewString())
|
||||
session := testSession(uuid.New(), time.Now().UTC().Add(remaining))
|
||||
|
||||
source := mocks.NewMockSessionSource(s.T())
|
||||
source.EXPECT().Resolve(mock.Anything, hash).Return(session, nil).Once()
|
||||
|
||||
_, err := s.newRepo(source).Resolve(ctx, hash)
|
||||
s.Require().NoError(err)
|
||||
|
||||
ttl, err := s.client.PTTL(ctx, sessionCacheKey(hash)).Result()
|
||||
s.Require().NoError(err)
|
||||
s.Positive(ttl)
|
||||
s.LessOrEqual(ttl, min(remaining, 5*time.Minute))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestResolvePopulatesCacheAndServesFromIt() {
|
||||
ctx := s.T().Context()
|
||||
tokenHash := []byte("hash-populate")
|
||||
session := testSession(uuid.New(), time.Now().UTC().Add(time.Hour))
|
||||
|
||||
source := mocks.NewMockSessionSource(s.T())
|
||||
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
first, err := repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(session.User.ID, first.User.ID)
|
||||
|
||||
second, err := repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(session.User.ID, second.User.ID)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestResolveFallsBackToSourceOnMiss() {
|
||||
ctx := s.T().Context()
|
||||
tokenHash := []byte("unknown")
|
||||
|
||||
source := mocks.NewMockSessionSource(s.T())
|
||||
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
|
||||
|
||||
_, err := s.newRepo(source).Resolve(ctx, tokenHash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestRevokeEvictsCacheAndSource() {
|
||||
ctx := s.T().Context()
|
||||
userID := uuid.New()
|
||||
tokenHash := []byte("hash-revoke")
|
||||
session := testSession(userID, time.Now().UTC().Add(time.Hour))
|
||||
|
||||
source := mocks.NewMockSessionSource(s.T())
|
||||
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Once()
|
||||
source.EXPECT().Revoke(mock.Anything, userID, tokenHash).Return(nil).Once()
|
||||
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().NoError(repo.Revoke(ctx, userID, tokenHash))
|
||||
|
||||
_, err = repo.Resolve(ctx, tokenHash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
|
||||
ctx := s.T().Context()
|
||||
tokenHash := []byte("hash-evicted")
|
||||
session := testSession(uuid.New(), time.Now().UTC().Add(time.Hour))
|
||||
|
||||
source := mocks.NewMockSessionSource(s.T())
|
||||
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Twice()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
|
||||
// Simulate a Redis flush/restart by dropping the cache entry.
|
||||
s.Require().NoError(s.client.Del(ctx, sessionCacheKey(tokenHash)).Err())
|
||||
|
||||
_, err = repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestExpiredSessionIsRejected() {
|
||||
ctx := s.T().Context()
|
||||
tokenHash := []byte("hash-expired")
|
||||
|
||||
source := mocks.NewMockSessionSource(s.T())
|
||||
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
|
||||
|
||||
_, err := s.newRepo(source).Resolve(ctx, tokenHash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func sessionCacheKey(tokenHash []byte) string {
|
||||
return "session:" + hex.EncodeToString(tokenHash)
|
||||
}
|
||||
|
||||
func flushRedisDB(ctx context.Context) error {
|
||||
cfg := testRedisConfig()
|
||||
|
||||
client := goredis.NewClient(&goredis.Options{
|
||||
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
return client.FlushDB(ctx).Err()
|
||||
}
|
||||
Executable
+132
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproducible Redis-outage check: stop and pause, latency budget, create-during-outage.
|
||||
|
||||
Exit code is non-zero when any assertion fails. Always unpauses/starts Redis.
|
||||
"""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import base64
|
||||
|
||||
for proxy in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(proxy, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = os.environ['NO_PROXY']
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://localhost:8080')
|
||||
COMPOSE = os.environ.get('COMPOSE_BIN', 'docker-compose')
|
||||
COMPOSE_FILE = 'docker-compose.local.yaml'
|
||||
BUDGET_MS = int(os.environ.get('OUTAGE_BUDGET_MS', '2000'))
|
||||
PARALLEL = int(os.environ.get('OUTAGE_PARALLEL', '30'))
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run([COMPOSE, '-f', COMPOSE_FILE, *args], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = {'Accept': 'application/json'}
|
||||
if body is not None:
|
||||
h['Content-Type'] = 'application/json'
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=10)
|
||||
return resp.status, resp.read(), (time.monotonic() - started) * 1000
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, exc.read(), (time.monotonic() - started) * 1000
|
||||
|
||||
|
||||
def user(label):
|
||||
username = label + '_' + uuid.uuid4().hex[:8]
|
||||
password = 'T3st-' + uuid.uuid4().hex
|
||||
call('POST', '/api/v1/users', {'username': username, 'display_name': label, 'password': password})
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
_, body, _ = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential})
|
||||
return json.loads(body)
|
||||
|
||||
|
||||
def list_chats(actor):
|
||||
status, body, ms = call('GET', '/api/v1/chats?limit=50', headers={'Authorization': 'Bearer ' + actor['token']})
|
||||
assert status == 200, 'GET /chats expected 200, got %d' % status
|
||||
return json.loads(body)['items'], ms
|
||||
|
||||
|
||||
def assert_budget(label, samples):
|
||||
worst = max(samples)
|
||||
p95 = sorted(samples)[max(0, (len(samples) * 95 + 99) // 100 - 1)]
|
||||
print(' %s: n=%d max=%.0fms p95=%.0fms budget=%dms' % (label, len(samples), worst, p95, BUDGET_MS))
|
||||
assert worst <= BUDGET_MS, '%s exceeded budget: %.0fms > %dms' % (label, worst, BUDGET_MS)
|
||||
|
||||
|
||||
def main():
|
||||
alice = user('alice')
|
||||
bob = user('bob')
|
||||
ah = {'Authorization': 'Bearer ' + alice['token']}
|
||||
|
||||
try:
|
||||
_, ms = list_chats(alice)
|
||||
print('baseline: %.0fms' % ms)
|
||||
|
||||
compose('stop', 'redis')
|
||||
_, ms = list_chats(alice)
|
||||
print('after stop: %.0fms' % ms)
|
||||
assert_budget('stop', [ms])
|
||||
|
||||
compose('start', 'redis')
|
||||
time.sleep(2)
|
||||
compose('pause', 'redis')
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=PARALLEL) as pool:
|
||||
results = [f for f in pool.map(lambda _: list_chats(alice), range(PARALLEL))]
|
||||
assert_budget('pause parallel', [ms for _, ms in results])
|
||||
|
||||
title = 'during-outage-' + uuid.uuid4().hex[:8]
|
||||
status, _, _ = call('POST', '/api/v1/chats', {
|
||||
'title': title,
|
||||
'member_ids': [alice['user']['id'], bob['user']['id']],
|
||||
}, headers=ah)
|
||||
assert status == 201, 'chat create during pause expected 201, got %d' % status
|
||||
print('create during pause: 201')
|
||||
|
||||
compose('unpause', 'redis')
|
||||
time.sleep(2)
|
||||
|
||||
chats, ms = list_chats(alice)
|
||||
assert any(c['title'] == title for c in chats), 'new chat missing after recovery (stale cache)'
|
||||
print('after recovery: new chat visible, %.0fms' % ms)
|
||||
|
||||
stuck = subprocess.run(
|
||||
[COMPOSE, '-f', COMPOSE_FILE, 'exec', '-T', 'redis', 'redis-cli', '--scan', '--pattern', 'lock:*'],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout.split()
|
||||
for key in stuck:
|
||||
ttl = subprocess.run(
|
||||
[COMPOSE, '-f', COMPOSE_FILE, 'exec', '-T', 'redis', 'redis-cli', 'ttl', key],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout.strip()
|
||||
assert ttl != '-1', 'stuck lock without TTL: %s' % key
|
||||
print('lock keys without TTL: 0')
|
||||
print('PASS: redis outage handled within budget')
|
||||
finally:
|
||||
for action in ('unpause', 'start'):
|
||||
subprocess.run([COMPOSE, '-f', COMPOSE_FILE, action, 'redis'],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL: %s' % exc)
|
||||
sys.exit(1)
|
||||
@@ -26,8 +26,8 @@ os.environ['no_proxy'] = os.environ['NO_PROXY']
|
||||
|
||||
def restart_api(cache_enabled):
|
||||
env = dict(os.environ)
|
||||
env['APP_REDIS_ENABLED'] = 'true'
|
||||
env['APP_CACHE_ENABLED'] = 'true' if cache_enabled else 'false'
|
||||
env['REDIS_ENABLED'] = 'true'
|
||||
env['CACHE_ENABLED'] = 'true' if cache_enabled else 'false'
|
||||
subprocess.run(
|
||||
[COMPOSE, '-f', 'docker-compose.local.yaml', 'up', '-d', '--force-recreate', 'api'],
|
||||
cwd=ROOT,
|
||||
|
||||
Reference in New Issue
Block a user