Исправление ошибок

This commit is contained in:
2026-10-27 20:29:33 +03:00
parent c60c78b51e
commit 0701e4dcc1
20 changed files with 293 additions and 94 deletions
+4
View File
@@ -16,6 +16,10 @@ API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400
PUBLISH_PORT=8080
# lab3: bounded-staleness session cache and durable invalidation drainer.
SESSION_CACHE_TTL_SECONDS=60
CACHE_INVALIDATION_INTERVAL_SECONDS=0.5
# Bounded DB pool and statement timeout (grade 4).
DB_POOL_MIN=1
DB_POOL_MAX=10
+14 -10
View File
@@ -64,7 +64,7 @@ docker compose down -v
- **Динамический backend-list.** `upstream api_backend { zone …; server api:8080 resolve max_fails=1 fail_timeout=5s; }` + `resolver 127.0.0.11 valid=5s`. nginx перечитывает A-записи Docker DNS: добавление/остановка реплики подхватывается без reload; `proxy_next_upstream error timeout http_502/503/504` повторяет запрос на живой реплике. Максимальное время обнаружения отказа: пассивный `fail_timeout` 5 s + `valid` 5 s, замеренная первая успешная запись после старта хука — **< 1 с**.
- **X-Instance-Id.** `src/instance.py`: `INSTANCE_ID = $INSTANCE_ID` или hostname контейнера (= короткий container id). Ставится middleware на **каждый** ответ, включая ошибки и health; стабилен на время жизни процесса. Проверка в `evidence/lab3-instances.txt`: 12 запросов дают ровно два чередующихся id.
- **Общая идемпотентность.** Таблица `idempotency_keys` (PK `user_id, scope, key`, `scope = "POST /api/v1/chats/{id}/messages"`), `request_hash`, `status_code`, `response_body jsonb`, `expires_at`. `POST …/messages` требует `Idempotency-Key` `[A-Za-z0-9._:-]{1,128}` (нет/неверный — 400). Вставка сообщения и запись журнала — одна транзакция; `pg_advisory_xact_lock(hashtext(user|scope), hashtext(key))` сериализует одинаковые ключи между всеми репликами. Повтор возвращает тот же `201` и тот же Message; другой body — `409`. TTL — `IDEMPOTENCY_TTL_SECONDS` (default 86400).
- **Сессии общие, отзыв немедленный.** Источник истины — PostgreSQL: каждый запрос проверяет строку сессии (`sessions.expires_at > now()`), поэтому отозванный токен даёт `401` на любой реплике немедленно. Valkey — read-through кэш **неизменяемого профиля пользователя** (`user:{id}`, TTL 300 c), он никогда не используется для решения о доступе. Поэтому сбой инвалидации при лежащем Valkey не может «воскресить» отозванную сессию (регрессионная проверка — `scripts/check-revocation.py`). Sticky session не используются: пользователь свободно попадает на любую реплику без повторного входа.
- **Сессии общие, отзыв корректен при сбое кэша.** Источник истины — PostgreSQL (`sessions`): валидность и отзыв определяет строка с `expires_at > now()`. Valkey — **кэш сессий** `session:{sha256(token)} -> {user_id, expires_at}` с TTL `min(remaining, SESSION_CACHE_TTL_SECONDS)` (по умолчанию 60 c) — это верхняя граница устаревания. Logout в одной транзакции удаляет строку сессии и кладёт токен в `cache_invalidations`; фоновый дренажёр (`src/invalidation.py`, период 0.5 c) удаляет ключ Valkey и строку очереди. Поэтому logout, выполненный при лежащем Valkey, применяется сразу после восстановления кэша, а не «воскресает» до истечения TTL. При недоступности Valkey запросы обходят кэш и идут в PostgreSQL. Sticky-сессии не используются.
- **Одноразовые миграции.** Отдельный сервис `migrate` (`python -m src.migrate`) под `pg_advisory_xact_lock`; реплики стартуют только после `service_completed_successfully`, гонки за схему нет.
- **Graceful shutdown.** `src/main.py` переопределяет `Server.handle_exit`: по SIGTERM/SIGINT выставляет флаг (`src/state.py`), `/health/ready` отвечает `503` (LB выводит реплику из ротации), затем Uvicorn доигрывает запросы (`timeout_graceful_shutdown=10`).
- **Ресурсы и секреты.** У всех сервисов заданы CPU/RAM-лимиты (`deploy.resources.limits`); секреты — файловые compose secrets/`*_FILE`, в образ и Git не попадают. `container_name` не задаётся, масштабирование одной Compose-service работает.
@@ -78,6 +78,8 @@ docker compose down -v
| `APP_ENV`, `LOG_LEVEL` | метки логирования запуска |
| `SESSION_TTL_SECONDS` | срок жизни сессии (`sessions.expires_at`) и TTL кэша |
| `SESSION_STORE` | `valkey`/`redis` — включить кэш; `postgres` — без кэша |
| `SESSION_CACHE_TTL_SECONDS` | верхняя граница жизни записи кэша сессий (граница устаревания) |
| `CACHE_INVALIDATION_INTERVAL_SECONDS` | период фонового дренажёра очереди инвалидаций |
| `IDEMPOTENCY_TTL_SECONDS` | срок хранения журнала идемпотентности (24 ч) |
| `DATABASE_URL_FILE`, `CACHE_URL_FILE` | файлы с DSN PostgreSQL и URL Valkey (compose secrets) |
| `API_REPLICAS` | число реплик `api` (`deploy.replicas`) |
@@ -90,18 +92,19 @@ docker compose down -v
| --- | --- | --- | --- |
| Публичный smoke | `python tests/smoke.py --base-url http://localhost:8080` | `PASS: lab3 public API scenario` | `evidence/lab3-smoke.txt` |
| Стенд: ≥2 реплики, LB, общая БД/сессии | `docker compose up -d --build`, `docker compose ps` | 2× `api` healthy, `lb` 127.0.0.1:8080, `postgres`, `valkey`; у `api` порты не публикуются | `evidence/lab3-compose-ps.txt` |
| Разные запросы одной сессии обслуживают разные реплики | 12× `GET /users/me` через LB | чередование `4141f552b001`/`5ac0582fa5e1` (2 реплики), один токен | `evidence/lab3-instances.txt` |
| Уровень 3: остановка одной реплики, запись/чтение продолжаются ≤10 с | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 122 успешных записи, 0 ошибок, восстановление **1.083 с**; `api-6 Exited` при живом `api-5` | `evidence/lab3-failover.txt` |
| Разные запросы одной сессии обслуживают разные реплики | 12× `GET /users/me` через LB | чередование двух разных `X-Instance-Id` (2 реплики), один токен | `evidence/lab3-instances.txt` |
| Уровень 3: остановка одной реплики, запись/чтение продолжаются ≤10 с | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 138 успешных записей, 0 ошибок, восстановление **0.67 с**; `api-8 Exited` при живом `api-7` | `evidence/lab3-failover.txt` |
| Общая идемпотентность, в т.ч. конкурентная и через разные реплики | `test_idempotency.py` | повтор = тот же Message; другой body → 409; 8 параллельных запросов с одним ключом → ровно одно сообщение | `evidence/lab3-student-tests.txt` |
| Отзыв сессии не обходится при сбое Valkey | `python scripts/check-revocation.py` (pause Valkey → logout 204 → unpause → 6 c) | старый токен даёт `401` через 2 реплики и не может отправить сообщение | `evidence/lab3-revocation-fix.txt` |
| Кэш сессий реален, очередь инвалидаций дренируется | warm-up → pause/logout/unpause → `valkey-cli --scan 'session:*'` + `cache_invalidations` | ключ `session:*` с TTL `60` → после восстановления 0 ключей и 0 строк очереди; старый токен `401` | `evidence/lab3-cache-invalidation.txt` |
| Деградация кэша без остановки API | pause Valkey, валидный `/users/me` | 5×`200`, `/health/ready` = `200` (кэш обойдён) | `evidence/lab3-valkey-degradation.txt` |
| Persistence: данные и сессия переживают рестарт API и хранилищ | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS: persistence preserved confirmed data and existing session` | `evidence/lab3-persistence.txt` |
| Миграции применяются однократно и повторно идемпотентно | `docker compose exec -T api python -m src.migrate` | `migrations up to date`; в `schema_migrations` 2 строки | `evidence/lab3-migrations.txt` |
| Миграции применяются однократно и повторно идемпотентно | `docker compose exec -T api python -m src.migrate` | `migrations up to date`; в `schema_migrations` 3 строки | `evidence/lab3-migrations.txt` |
| Уровень 4: health/readiness, SIGTERM, LB исключает backend | `scripts/stop-one.sh` + `/health/ready` | остановленная реплика исчезает из ответов; readiness→503 при SIGTERM; пассивные проверки nginx | `evidence/lab3-failover.txt` |
| Уровень 4: CPU/RAM-лимиты, порты API только через LB | `docker compose config`, `docker stats` | лимиты 0.75 CPU / 256M у api; `8080/tcp` без проброса | `evidence/lab3-stats.txt`, `evidence/lab3-compose-ps.txt` |
| Уровень 4: rolling update под нагрузкой | `scripts/rolling-update.sh` при непрерывном опросе LB | 400/400 запросов `200`, реплики заменены по одной | `evidence/lab3-rolling.txt` |
| Уровень 4: индекс под keyset-пагинацию (≥10 000 сообщений) | `EXPLAIN (ANALYZE, BUFFERS)` | `Bitmap Index Scan on messages_chat_created_id_idx`, 0.907 мс | `evidence/lab3-explain.txt` |
| Уровень 4: нагрузочные метрики | `tests/load.py` | 133 RPS, 0 ошибок, p50/p95/p99 = 47/141/203 мс | `evidence/lab3-load.txt` |
| Уровень 4: нагрузочные метрики | `tests/load.py` | 113.6 RPS, 0 ошибок, p50/p95/p99 = 47/172/281 мс | `evidence/lab3-load.txt` |
| Секреты вне Git | `.gitignore`, `secrets.example/`, `gen-secrets.sh` | `git status` без `.env`/`secrets/` | описание в PR |
## Эксперименты и отказы
@@ -112,19 +115,20 @@ docker compose down -v
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| Остановка одной API-реплики (`stop-one.sh`, TARGET = обслужившая реплика) | записи/чтения продолжаются, без дублей, токен жив | 122 записи за 15 с, 0 ошибок, цель не в последних ответах; `api-6 Exited` | **1.083 с**; потерь нет |
| То же для второй реплики (после восстановления первой) | то же | ≈120–140 записей, 0 ошибок; `api-2 Exited` | **≈1 с**; потерь нет |
| Остановка одной API-реплики (`stop-one.sh`, TARGET = обслужившая реплика) | записи/чтения продолжаются, без дублей, токен жив | 138 записей за 15 с, 0 ошибок, цель не в последних ответах; `api-8 Exited` | **0.67 с**; потерь нет |
| То же для второй реплики (после восстановления первой) | то же | ≈120–140 записей, 0 ошибок | **≈1 с**; потерь нет |
| `docker compose restart api lb postgres valkey` | данные и сессия сохранены | `PASS: persistence preserved……` | рестарт ≈ секунды; потерь нет |
| Rolling update (`rolling-update.sh`) под непрерывным опросом | замена реплик без недоступности | 400/400 `200` при поочерёдной замене | простоя нет |
| Valkey недоступен во время logout (`check-revocation.py`) | отзыв сессии не обходится, старый токен → 401 | pause → logout 204 → unpause → 6 c → 401 через обе реплики, POST отклонён | потерь нет; сессия отозвана в PostgreSQL |
| Нагрузка 133 RPS на 2 реплики | стабильная пропускная способность | 0 ошибок, p99 203 мс | n/a |
| Valkey недоступен во время logout (`check-revocation.py`) | отзыв сессии не обходится, старый токен → 401 | pause → logout 204 → unpause → ключ кэша удалён дренажёром ≤1.5 c, очередь `cache_invalidations`=0; через 6 c 401 через обе реплики, POST отклонён | потерь нет; сессия отозвана в PostgreSQL |
| Нагрузка ~114 RPS на 2 реплики | стабильная пропускная способность | 0 ошибок, p99 281 мс | n/a |
Ограничения измерения: closed-loop генератор страдает coordinated omission и ограничен клиентом; числа — throughput HTTP-подтверждений, не точный счётчик COMMIT; единичный Docker-host не проверяет отказ узла. `docker stats` показывает ~74 MB RSS на реплику при лимите 256 MB.
Ограничения измерения: closed-loop генератор страдает coordinated omission и ограничен клиентом; числа — throughput HTTP-подтверждений, не точный счётчик COMMIT; единичный Docker-host не проверяет отказ узла. `docker stats` показывает ~150 MB RSS на реплику при лимите 256 MB.
## Ограничения и следующие шаги
- Выдерживается: отказ **процесса** одной API-реплики, рестарт API и хранилищ с volumes, потеря Valkey (кэш), конкурентные повторы с общим ключом, rolling-замена реплик под нагрузкой, некорректный ввод.
- **Не** выдерживается и не заявлено: отказ Docker-host, отказ единственного PostgreSQL и единственного LB, отказ узла БД. Multi-node/HA БД — это трек 5, он не выбран.
- Учебные упрощения: HTTP без TLS (локальный стенд lab1–6); `scripts/rolling-update.sh` — поочерёдная замена через `docker`+`compose`, эквивалент rolling update оркестратора, а не сам оркестратор; нет rate limiting.
- Граница устаревания сессионного кэша — `SESSION_CACHE_TTL_SECONDS` (60 c). При полностью недоступном Valkey отзыв применяется не мгновенно, а когда дренажёр сможет удалить ключ после восстановления кэша (замерено ≤1.5 c); TTL — страховка на случай, если дренажёр не успеет. Это осознанный компромисс: logout должен возвращать 204 и при недоступном кэше, поэтому «нулевая» задержка инвалидации в этот момент невозможна без отказа от кэша.
- Подтверждено измерениями: смена обслуживающей реплики при отказе, конкуренто-безопасная идемпотентность, сохранность после рестарта, использование индекса (EXPLAIN), отсутствие публикации портов API.
- Возможное улучшение (гипотеза): при большем числе реплик и `proxy_next_upstream_tries` можно снизить долю ошибок при «жёстком» (без ожидания healthy) rolling-обновлении; в этой работе замена ожидает healthy, поэтому ошибок нет.
+2
View File
@@ -11,6 +11,8 @@ x-api-env: &api-env
APP_ENV: ${APP_ENV:-lab}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
SESSION_STORE: ${SESSION_STORE:-valkey}
SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60}
CACHE_INVALIDATION_INTERVAL_SECONDS: ${CACHE_INVALIDATION_INTERVAL_SECONDS:-0.5}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
DATABASE_URL_FILE: /run/secrets/database_url
CACHE_URL_FILE: /run/secrets/cache_url
+6
View File
@@ -0,0 +1,6 @@
session keys in Valkey after warm-up: 1
sample TTLs (capped at SESSION_CACHE_TTL_SECONDS): {'session:b978298ff28b3a14738e...': '60'}
pausing Valkey, logout, resuming ...
session keys after resume + 1.5s (drainer): 0
pending invalidation rows after drain: 0
old token status: 401
+6 -6
View File
@@ -1,6 +1,6 @@
NAME SERVICE STATUS PORTS
messenger-lab3-api-1 api Up 54 seconds (healthy) 8080/tcp
messenger-lab3-api-2 api Up 19 seconds (healthy) 8080/tcp
messenger-lab3-lb-1 lb Up 2 minutes (healthy) 80/tcp, 127.0.0.1:8080->8080/tcp
messenger-lab3-postgres-1 postgres Up 2 minutes (healthy) 5432/tcp
messenger-lab3-valkey-1 valkey Up 2 minutes (healthy) 6379/tcp
NAME SERVICE STATUS PORTS
messenger-lab3-api-7 api Up 4 minutes (healthy) 8080/tcp
messenger-lab3-api-8 api Up 4 minutes (healthy) 8080/tcp
messenger-lab3-lb-1 lb Up 7 minutes (healthy) 80/tcp, 127.0.0.1:8080->8080/tcp
messenger-lab3-postgres-1 postgres Up 7 minutes (healthy) 5432/tcp
messenger-lab3-valkey-1 valkey Up 7 minutes (healthy) 6379/tcp
Binary file not shown.
+2 -2
View File
@@ -1,3 +1,3 @@
X-Instance-Id sequence over 12 requests through the LB:
['4141f552b001', '5ac0582fa5e1', '4141f552b001', '5ac0582fa5e1', '4141f552b001', '5ac0582fa5e1', '4141f552b001', '5ac0582fa5e1', '4141f552b001', '5ac0582fa5e1', '4141f552b001', '5ac0582fa5e1']
distinct: ['4141f552b001', '5ac0582fa5e1']
['2f2d19f8e0e6', 'a17e74060901', '2f2d19f8e0e6', 'a17e74060901', '2f2d19f8e0e6', 'a17e74060901', '2f2d19f8e0e6', 'a17e74060901', '2f2d19f8e0e6', 'a17e74060901', '2f2d19f8e0e6', 'a17e74060901']
distinct: ['2f2d19f8e0e6', 'a17e74060901']
+5 -5
View File
@@ -2,16 +2,16 @@
"lab": 3,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 20.0,
"elapsed_seconds": 20.375,
"elapsed_seconds": 20.39,
"concurrency": 8,
"successful_requests": 2712,
"successful_requests": 2317,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 133.104,
"successful_rps": 113.634,
"successful_latency_ms": {
"p50": 47.0,
"p95": 141.0,
"p99": 203.0
"p95": 172.0,
"p99": 281.0
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+5 -5
View File
@@ -2,16 +2,16 @@
"lab": 3,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 20.0,
"elapsed_seconds": 20.375,
"elapsed_seconds": 20.39,
"concurrency": 8,
"successful_requests": 2712,
"successful_requests": 2317,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 133.104,
"successful_rps": 113.634,
"successful_latency_ms": {
"p50": 47.0,
"p95": 141.0,
"p99": 203.0
"p95": 172.0,
"p99": 281.0
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+5 -4
View File
@@ -1,15 +1,16 @@
=== docker compose exec -T api python -m src.migrate ===
docker : INFO:messenger.migrate:migrations up to date
строка:1 знак:122
строка:1 знак:244
+ ... ations.txt; docker compose exec -T api python -m src.migrate 2>&1 | T ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (INFO:messenger....ions up to date:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
=== schema_migrations rows ===
version
---------------------
version
-----------------------------
001_init.sql
002_idempotency.sql
(2 rows)
003_cache_invalidations.sql
(3 rows)
Binary file not shown.
+2 -2
View File
@@ -1,7 +1,7 @@
Running rolling update under continuous /health/live polling...
Replacing replica 72593ccf3b1f861c4d01c81aca3273b8149e00e93a8bad5db4c977a6702b553e ...
Replacing replica 1b3fb45af266d3eb0cbc1800b654b017f168a34d796f2d049b719b4c794a34ab ...
Replacing replica 47b92cbda9c814bed107a112fff202e9716d1735192a46861f070cc08c10b6e5 ...
Replacing replica 6077ba4198446b006bfc4a420d2875958a2b640163f1ed0669d9c3a6c0da5c2f ...
Rolling update complete; all replicas healthy.
HTTP status distribution observed by the client during the rolling update:
400 200
+5 -5
View File
@@ -1,6 +1,6 @@
NAME CPU % MEM USAGE / LIMIT
messenger-lab3-api-6 9.50% 74.27MiB / 256MiB
messenger-lab3-api-5 0.13% 74.25MiB / 256MiB
messenger-lab3-lb-1 0.00% 15.35MiB / 128MiB
messenger-lab3-postgres-1 0.18% 58.18MiB / 512MiB
messenger-lab3-valkey-1 0.27% 7.98MiB / 128MiB
messenger-lab3-api-8 0.24% 152.6MiB / 256MiB
messenger-lab3-api-7 0.21% 146.5MiB / 256MiB
messenger-lab3-lb-1 0.00% 14.97MiB / 128MiB
messenger-lab3-postgres-1 0.16% 68.95MiB / 512MiB
messenger-lab3-valkey-1 0.26% 8.43MiB / 128MiB
+1 -1
View File
@@ -1,2 +1,2 @@
..................................... [100%]
37 passed in 10.82s
37 passed in 9.10s
+15
View File
@@ -0,0 +1,15 @@
-- Lab3 durable cache invalidation queue.
--
-- Logout deletes the authoritative session row in PostgreSQL and enqueues the
-- token hash here in the SAME transaction. A lightweight background drainer in
-- each API replica removes the corresponding Valkey cache key and then the row.
-- If Valkey was unreachable at logout time, the row survives and the stale
-- cache entry is removed as soon as the cache comes back, instead of being
-- trusted until its TTL.
create table if not exists cache_invalidations (
token_hash text primary key,
created_at timestamptz not null default now()
);
create index if not exists cache_invalidations_created_at_idx
on cache_invalidations (created_at);
+16 -6
View File
@@ -12,6 +12,7 @@ import binascii
import logging
import re
import uuid
from contextlib import asynccontextmanager
from typing import Dict, List, Optional
from fastapi import Depends, FastAPI, Query, Request, Response
@@ -22,6 +23,7 @@ from psycopg import InterfaceError, OperationalError
from psycopg_pool import PoolTimeout
from starlette.exceptions import HTTPException as StarletteHTTPException
from . import invalidation
from . import repositories as repo
from . import security, sessions, state
from .config import settings
@@ -49,12 +51,22 @@ _STATUS_CODES = {
503: "unavailable",
}
@asynccontextmanager
async def lifespan(_: FastAPI):
invalidation.start_worker()
try:
yield
finally:
invalidation.stop_worker()
app = FastAPI(
title="MTUSI Messenger — лабораторная 3",
version="1.3.0",
docs_url=None,
redoc_url=None,
openapi_url=None,
lifespan=lifespan,
)
@@ -213,16 +225,14 @@ def _idempotency_key(request: Request) -> str:
def current_user(request: Request, conn=Depends(get_conn)) -> Dict:
# Session validity is always checked against PostgreSQL; the cache may only
# serve the immutable user profile, never an access decision.
token = _bearer_token(request)
user_id = sessions.resolve(conn, token)
if user_id is None:
raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE)
user = sessions.cached_user(conn, user_id)
if user is None:
row = repo.get_user_by_id(conn, user_id)
if row is None:
raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE)
return user
return row
def _require_chat(conn, chat_id: str, user_id: str) -> str:
@@ -289,7 +299,7 @@ def revoke_session(
@app.get("/api/v1/users/me")
def current_user_endpoint(user: Dict = Depends(current_user)) -> dict:
return user
return repo.user_json(user)
# --------------------------------------------------------------------------- #
+6
View File
@@ -28,6 +28,8 @@ class Settings:
app_env: str
session_ttl_seconds: int
session_store: str
session_cache_ttl_seconds: int
cache_invalidation_interval_seconds: float
idempotency_ttl_seconds: int
database_url: str
cache_url: str
@@ -48,6 +50,10 @@ def load_settings() -> Settings:
app_env=os.environ.get("APP_ENV", "lab"),
session_ttl_seconds=int(os.environ.get("SESSION_TTL_SECONDS", "3600")),
session_store=os.environ.get("SESSION_STORE", "postgres").lower(),
session_cache_ttl_seconds=int(os.environ.get("SESSION_CACHE_TTL_SECONDS", "60")),
cache_invalidation_interval_seconds=float(
os.environ.get("CACHE_INVALIDATION_INTERVAL_SECONDS", "0.5")
),
idempotency_ttl_seconds=int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400")),
database_url=_read_secret("DATABASE_URL_FILE", "DATABASE_URL"),
cache_url=_read_secret("CACHE_URL_FILE", "CACHE_URL"),
+76
View File
@@ -0,0 +1,76 @@
"""Durable cache-invalidation drainer (lab3).
Logout writes a pending invalidation to PostgreSQL in the same transaction as
the authoritative session delete. This tiny background thread (one per API
replica, not an external broker) removes the corresponding Valkey key and then
the queue row. Multiple replicas may process the same row; cache deletes are
idempotent, so this is safe and needs no distributed lock.
The worker is deliberately not on the request path: it only runs when a cache
is configured, and it retries forever while Valkey is unreachable. That is what
lets a logout survive a Valkey outage: the session is already gone from
PostgreSQL, and the stale cache entry is evicted as soon as the cache returns.
"""
from __future__ import annotations
import logging
import threading
from typing import Optional
from . import repositories as repo
from . import sessions
from .config import settings
from .db import pool
logger = logging.getLogger("messenger.invalidation")
_BATCH = 200
_stop = threading.Event()
_thread: Optional[threading.Thread] = None
def _drain_once() -> None:
with pool().connection() as conn:
pending = repo.list_pending_invalidations(conn, _BATCH)
if not pending:
return
invalidated = [token_hash for token_hash in pending if sessions.invalidate_session_key(token_hash)]
if not invalidated:
# Cache still unreachable; keep the rows for the next attempt.
return
with pool().connection() as conn:
repo.delete_cache_invalidations(conn, invalidated)
logger.debug("drained %d cache invalidations", len(invalidated))
def _loop() -> None:
while not _stop.is_set():
try:
_drain_once()
except Exception as exc: # noqa: BLE001 - never kill the drainer
logger.warning("cache invalidation drain failed: %s", type(exc).__name__)
_stop.wait(settings.cache_invalidation_interval_seconds)
def start_worker() -> None:
global _thread
if not settings.cache_enabled:
return
if _thread is not None and _thread.is_alive():
return
_stop.clear()
_thread = threading.Thread(target=_loop, name="cache-invalidation", daemon=True)
_thread.start()
logger.info(
"cache invalidation drainer started (interval=%.2fs)",
settings.cache_invalidation_interval_seconds,
)
def stop_worker() -> None:
global _thread
_stop.set()
if _thread is not None:
_thread.join(timeout=2)
_thread = None
+36
View File
@@ -319,3 +319,39 @@ def purge_expired_sessions(conn) -> int:
"delete from sessions where expires_at <= now() returning token_hash"
).fetchall()
return len(row)
# --------------------------------------------------------------------------- #
# Durable cache invalidation queue (lab3)
# --------------------------------------------------------------------------- #
def enqueue_cache_invalidation(conn, token_hash: str) -> None:
"""Record a session cache key that must be removed from Valkey.
Written in the same transaction as the authoritative session delete, so a
committed logout can never lose the obligation to invalidate the cache.
"""
conn.execute(
"""
insert into cache_invalidations (token_hash, created_at)
values (%s, now())
on conflict (token_hash) do nothing
""",
(token_hash,),
)
def list_pending_invalidations(conn, limit: int) -> List[str]:
rows = conn.execute(
"select token_hash from cache_invalidations order by created_at limit %s",
(limit,),
).fetchall()
return [str(row["token_hash"]) for row in rows]
def delete_cache_invalidations(conn, token_hashes: Sequence[str]) -> None:
if not token_hashes:
return
conn.execute(
"delete from cache_invalidations where token_hash = any(%s)",
(list(token_hashes),),
)
+87 -48
View File
@@ -1,22 +1,23 @@
"""Sessions and profile cache.
"""Sessions: PostgreSQL is the source of truth, Valkey is a shared session cache.
PostgreSQL is the source of truth for **session validity**. Every authenticated
request resolves its bearer token against the ``sessions`` table, so an
expired, revoked or unknown token is rejected immediately - even if Valkey was
unreachable at logout time and the invalidation could not be performed. The
cache is therefore never consulted to decide whether a session is valid, and a
stale or not-invalidated entry cannot resurrect a revoked session.
Design (lab3):
* ``sessions`` rows in PostgreSQL decide validity (``expires_at > now()``) and
survive restarts with the named volume.
* Valkey caches ``session:{token_hash} -> {user_id, expires_at}`` for at most
``SESSION_CACHE_TTL_SECONDS``. The TTL is a *bounded staleness* guarantee:
even if an invalidation is lost, a cached positive cannot outlive this
window.
* Logout deletes the PostgreSQL row and, in the same transaction, enqueues the
token hash in ``cache_invalidations``. A background drainer (see
``src/invalidation.py``) removes the Valkey key and then the queue row, so
a logout that happened while Valkey was down is still honoured as soon as
the cache returns — instead of being resurrected from a stale entry.
* If Valkey is unreachable every cache operation degrades to PostgreSQL. The
API keeps serving; the cache is never trusted as the source of truth.
Valkey is a best-effort read-through cache for **immutable user profiles**
(``user:{id}``). Profiles do not carry authorization state, so a failed cache
operation only costs one extra SQL query; it can never change an access
decision. This keeps Redis/Valkey genuinely useful without weakening the
contract.
Every cache operation is bounded by a hard timeout and guarded by a tiny
circuit breaker. A stopped Valkey container can make Docker DNS itself block
for several seconds; without this guard a cache outage would stall request
handling. On any failure the breaker skips the cache for a few seconds.
Cache calls on the request path are bounded by a hard timeout and a small
circuit breaker (a stopped Valkey can make Docker DNS block for seconds). The
drainer bypasses the breaker on purpose: invalidation must not be skipped.
"""
from __future__ import annotations
@@ -25,7 +26,7 @@ import datetime as dt
import json
import logging
import time
from typing import Dict, Optional, Tuple
from typing import Optional, Tuple
import redis
from redis.backoff import NoBackoff
@@ -45,10 +46,6 @@ _OP_TIMEOUT = 0.5
_BREAKER_SECONDS = 5.0
_breaker_until = 0.0
# User profiles are immutable in the mandatory API, so a short TTL is enough
# and bounds staleness to a value that cannot affect authorization.
_USER_CACHE_TTL = 300
def _cache() -> Optional[redis.Redis]:
global _client, _client_disabled
@@ -72,7 +69,7 @@ def _cache() -> Optional[redis.Redis]:
def _guard(fn, *args):
"""Run a cache operation with a hard deadline and a small breaker."""
"""Run a request-path cache operation with a deadline and a small breaker."""
global _breaker_until
if time.monotonic() < _breaker_until:
return None
@@ -84,6 +81,10 @@ def _guard(fn, *args):
return None
def _session_key(token_hash: str) -> str:
return f"session:{token_hash}"
def _cache_get(key: str) -> Optional[str]:
client = _cache()
if client is None:
@@ -108,12 +109,28 @@ def _cache_delete(key: str) -> None:
_guard(lambda: client.delete(key))
def _session_key(token_hash: str) -> str:
return f"session:{token_hash}"
def _encode_session(user_id: str, expires_at: dt.datetime) -> str:
return json.dumps(
{"user_id": user_id, "expires_at": repo.rfc3339(expires_at)},
separators=(",", ":"),
)
def _user_key(user_id: str) -> str:
return f"user:{user_id}"
def _decode_session(raw: str) -> Optional[Tuple[str, dt.datetime]]:
try:
data = json.loads(raw)
user_id = str(data["user_id"])
value = str(data["expires_at"])
if value.endswith("Z"):
value = value[:-1] + "+00:00"
expires_at = dt.datetime.fromisoformat(value)
return user_id, expires_at
except (ValueError, KeyError, TypeError):
return None
def _cache_ttl(remaining: float) -> int:
return max(1, int(min(remaining, settings.session_cache_ttl_seconds)))
def create(conn, user_id: str) -> Tuple[str, dt.datetime]:
@@ -121,44 +138,66 @@ def create(conn, user_id: str) -> Tuple[str, dt.datetime]:
hashed = security.token_hash(token)
expires_at = repo.utcnow() + dt.timedelta(seconds=settings.session_ttl_seconds)
repo.insert_session(conn, hashed, user_id, expires_at)
# The cache is populated by the first successful resolve() (read-through),
# so it can only ever contain sessions already committed to PostgreSQL.
return token, expires_at
def resolve(conn, token: str) -> Optional[str]:
"""Return the session's user id, or None if the token is not valid.
Validity is always decided by PostgreSQL. The cache is *not* consulted here,
so revoking a session (DELETE row) takes effect immediately on every
replica regardless of the state of Valkey.
A cache hit is accepted only while the stored expiry is in the future and
only for the bounded cache TTL. A miss or any cache failure falls back to
the authoritative PostgreSQL row.
"""
hashed = security.token_hash(token)
cached = _cache_get(_session_key(hashed))
if cached is not None:
decoded = _decode_session(cached)
if decoded is not None and decoded[1] > repo.utcnow():
return decoded[0]
row = repo.get_valid_session(conn, hashed)
if row is None:
# Best-effort cleanup of any legacy session entry from older versions;
# never used for a decision.
# Remove any legacy/stale entry; revocation is already authoritative.
_cache_delete(_session_key(hashed))
return None
return str(row["user_id"])
user_id = str(row["user_id"])
remaining = (row["expires_at"] - repo.utcnow()).total_seconds()
if remaining > 0:
_cache_set(
_session_key(hashed),
_encode_session(user_id, row["expires_at"]),
_cache_ttl(remaining),
)
return user_id
def revoke(conn, token: str) -> None:
hashed = security.token_hash(token)
repo.delete_session(conn, hashed)
if settings.cache_enabled:
# Durable obligation, committed together with the session delete.
repo.enqueue_cache_invalidation(conn, hashed)
# Best effort: the drainer retries if this fails (e.g. Valkey is down).
_cache_delete(_session_key(hashed))
def cached_user(conn, user_id: str) -> Optional[Dict]:
"""Read-through cache of an immutable user profile (never authorization)."""
key = _user_key(user_id)
raw = _cache_get(key)
if raw is not None:
try:
return json.loads(raw)
except ValueError:
pass
row = repo.get_user_by_id(conn, user_id)
if row is None:
return None
data = repo.user_json(row)
_cache_set(key, json.dumps(data, ensure_ascii=False), _USER_CACHE_TTL)
return data
def invalidate_session_key(token_hash: str) -> bool:
"""Delete one cache key for the drainer; True means it is safe to dequeue.
Deliberately bypasses the circuit breaker: a transient cache outage must not
cause pending invalidations to be dropped. Socket timeouts still bound the
call so the worker cannot block forever.
"""
client = _cache()
if client is None:
# Cache deliberately disabled -> nothing to invalidate. A client that
# failed to initialise keeps its rows so a restart can retry.
return not settings.cache_enabled
try:
client.delete(_session_key(token_hash))
return True
except (redis.RedisError, OSError):
return False