From 09b4b1d49d7ad7d8a26415addfb1f02765db2679 Mon Sep 17 00:00:00 2001 From: d1frend Date: Thu, 15 Oct 2026 20:12:22 +0300 Subject: [PATCH] =?UTF-8?q?=D1=80=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BD=20=D1=83=D1=80=D0=BE=D0=B2=D0=B5=D0=BD=D1=8C?= =?UTF-8?q?=204?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 10 +- Makefile | 59 +++++- REPORT.md | 119 +++++++++--- cmd/server/main.go | 39 +++- compose.yaml | 41 ++++ docs/database.md | 82 +++++++- evidence/level3.md | 8 +- evidence/level4.md | 236 +++++++++++++++++++++++ go.mod | 3 + go.sum | 25 ++- internal/cache/chat.go | 175 +++++++++++++++++ internal/config/config.go | 79 ++++++++ internal/store/cached_repository.go | 98 ++++++++++ internal/store/cached_repository_test.go | 181 +++++++++++++++++ internal/store/postgres_chats.go | 58 ++---- scripts/explain_history.sh | 11 ++ scripts/postgres_outage.sh | 20 ++ scripts/redis_outage.sh | 20 ++ scripts/restart.sh | 8 +- scripts/session_ttl.sh | 29 +++ tests/cache_resilience.py | 105 ++++++++++ tests/database_resilience.py | 120 ++++++++++++ tests/explain_history.sql | 114 +++++++++++ tests/level4_transactions.py | 130 +++++++++++++ tests/session_security.py | 115 +++++++++++ 25 files changed, 1794 insertions(+), 91 deletions(-) create mode 100644 evidence/level4.md create mode 100644 internal/cache/chat.go create mode 100644 internal/store/cached_repository.go create mode 100644 internal/store/cached_repository_test.go create mode 100755 scripts/explain_history.sh create mode 100755 scripts/postgres_outage.sh create mode 100755 scripts/redis_outage.sh create mode 100755 scripts/session_ttl.sh create mode 100755 tests/cache_resilience.py create mode 100755 tests/database_resilience.py create mode 100755 tests/explain_history.sql create mode 100755 tests/level4_transactions.py create mode 100755 tests/session_security.py diff --git a/.env.example b/.env.example index 343fa6d..bfa93db 100644 --- a/.env.example +++ b/.env.example @@ -25,5 +25,11 @@ DB_QUERY_TIMEOUT=3s READINESS_TIMEOUT=2s SHUTDOWN_TIMEOUT=10s -# Redis will be added for grade 4. -CACHE_URL_FILE=/run/secrets/cache_url \ No newline at end of file +# Redis stores a disposable cache; PostgreSQL remains the source of truth. +CACHE_URL=redis://redis:6379/0 +CACHE_TTL=5m +CACHE_OPERATION_TIMEOUT=250ms +CACHE_POOL_SIZE=10 + +# Optional Redis Insight profile binds its UI only to localhost. +REDIS_INSIGHT_PORT=5540 diff --git a/Makefile b/Makefile index 407f419..def7947 100644 --- a/Makefile +++ b/Makefile @@ -25,9 +25,16 @@ COMPOSE_CMD = $(COMPOSE) --env-file "$(ENV_FILE)" test \ load \ test-persistence \ + test-level4-transactions \ + test-session-security \ + test-cache-fallback \ + test-database-failure \ + explain-history \ + test-level4 \ compose-config \ compose-build \ compose-up \ + compose-tools-up \ compose-down \ compose-ps \ compose-logs @@ -46,9 +53,16 @@ help: @echo "test: run public smoke test against a running API" @echo "load: run synthetic load against a running API" @echo "test-persistence: run persistence test with ACTION_SCRIPT" + @echo "test-level4-transactions: verify username race and chat rollback" + @echo "test-session-security: verify short TTL, wrong password and logout" + @echo "test-cache-fallback: verify API fallback while Redis is stopped" + @echo "test-database-failure: verify bounded errors while PostgreSQL is stopped" + @echo "explain-history: run EXPLAIN on a rolled-back 10000-message fixture" + @echo "test-level4: run the complete cumulative level 4 verification" @echo "compose-config: validate resolved Compose configuration" @echo "compose-build: build application images" @echo "compose-up: start the stack" + @echo "compose-tools-up: start optional Redis Insight" @echo "compose-down: stop the stack without deleting volumes" @echo "compose-ps: show stack containers" @echo "compose-logs: follow stack logs" @@ -108,6 +122,46 @@ test-persistence: --base-url "$(BASE_URL)" \ $(TLS_ARGS) +test-level4-transactions: + $(PYTHON) tests/level4_transactions.py \ + --base-url "$(BASE_URL)" \ + $(TLS_ARGS) + +test-session-security: + $(PYTHON) tests/session_security.py \ + --action-script "scripts/session_ttl.sh" \ + --ttl-seconds 2 \ + --base-url "$(BASE_URL)" \ + $(TLS_ARGS) + +test-cache-fallback: + $(PYTHON) tests/cache_resilience.py \ + --action-script "scripts/redis_outage.sh" \ + --base-url "$(BASE_URL)" \ + $(TLS_ARGS) + +test-database-failure: + $(PYTHON) tests/database_resilience.py \ + --action-script "scripts/postgres_outage.sh" \ + --base-url "$(BASE_URL)" \ + $(TLS_ARGS) + +explain-history: + scripts/explain_history.sh + +test-level4: + $(MAKE) go-check + $(MAKE) check + $(MAKE) validate + $(MAKE) compose-config + $(MAKE) test + $(MAKE) test-level4-transactions + $(MAKE) test-session-security + $(MAKE) test-cache-fallback + $(MAKE) test-database-failure + $(MAKE) test-persistence ACTION_SCRIPT=scripts/restart.sh + $(MAKE) explain-history + compose-config: @test -f "$(ENV_FILE)" || \ (echo "$(ENV_FILE) is missing; run: make init-env"; exit 2) @@ -119,6 +173,9 @@ compose-build: compose-up: $(COMPOSE_CMD) up -d --build +compose-tools-up: + $(COMPOSE_CMD) --profile tools up -d redis-insight + compose-down: $(COMPOSE_CMD) down @@ -126,4 +183,4 @@ compose-ps: $(COMPOSE_CMD) ps compose-logs: - $(COMPOSE_CMD) logs --follow \ No newline at end of file + $(COMPOSE_CMD) logs --follow diff --git a/REPORT.md b/REPORT.md index 06c0a7c..7c6994a 100644 --- a/REPORT.md +++ b/REPORT.md @@ -2,14 +2,22 @@ - Автор, группа: Чурилин, БВТ2301 - Целевая оценка: 5; выбран Track 2 «План запроса и восстановление» -- Commit/PR: уровень 3 подготовлен в рабочем дереве поверх `10b5842`; итоговые ссылки будут добавлены после публикации -- Использованные библиотеки: `pgx/v5`, `google/uuid`, `x/crypto/argon2`, `golang-migrate` +- Commit/PR: уровень 3 — commit `158fed1`; уровень 4 — ветка `solution/bvt2301-churilin`, итоговые ссылки указываются в MR +- Использованные библиотеки: `pgx/v5`, `go-redis/v9`, `google/uuid`, `x/crypto/argon2`, `golang-migrate` - Использованные источники: документация PostgreSQL, Go, Docker Compose и Redis; при проектировании, реализации и проверке использовался ИИ-ассистент ## Запуск из чистого clone Проверенное окружение: Ubuntu 26.04 в WSL2, Go 1.27.1, Python 3.14.4, -Docker Engine 29.7.2, Docker Compose 5.5.0, PostgreSQL 16.15. +Docker Engine 29.7.2, Docker Compose 5.5.0, PostgreSQL 16.15, +Redis 8.10.2 и Redis Insight 3.8.0. + +Измерения уровня 4 выполнены в WSL2 на Intel Core i5-1135G7: Docker видел +8 логических CPU и 3.724 GiB RAM. Отдельные CPU/RAM quotas для API и PostgreSQL +в Compose не задавались, поэтому они использовали лимиты Docker Desktop/WSL; +Redis дополнительно ограничен `maxmemory=64mb`. Перед проверками стенд ожидался +до состояния `healthy`, отдельный искусственный прогрев для SQL-плана не +использовался. Создать локальную конфигурацию и секреты с синтетическими значениями: @@ -49,9 +57,15 @@ python3 -m venv .venv .venv/bin/python -m pip install -r requirements-dev.txt make validate PYTHON=.venv/bin/python -make test +# Полная накопительная проверка уровня 4: +make test-level4 PYTHON=.venv/bin/python + +# Отдельная повторная проверка идемпотентности миграций: docker compose run --rm migrate -make test-persistence ACTION_SCRIPT=scripts/restart.sh + +# Необязательный web-интерфейс Redis Insight: +make compose-tools-up +# Открыть http://localhost:5540 и добавить redis:6379, database 0. ``` Безопасная остановка сохраняет named volume: @@ -74,20 +88,26 @@ HTTP client -> request ID / logger / recovery -> Basic login или Bearer authentication -> HTTP handler - -> Repository - -> PostgreSQL + -> CachedRepository + |-> Redis: необязательная копия карточки чата + `-> PostgreSQL: источник истины и все остальные операции ``` PostgreSQL является источником истины для пользователей, password hashes, -чатов, участников, сообщений и действующих сессий. `MemoryStore` сохранён -только для быстрых unit/regression-тестов и не используется production-сервером. +чатов, участников, сообщений и действующих сессий. Redis содержит только +восстанавливаемую копию карточек чатов. `MemoryStore` сохранён только для +быстрых unit/regression-тестов и не используется production-сервером. -Стенд состоит из трёх Compose-сервисов: +Стенд по умолчанию состоит из четырёх Compose-сервисов: - `postgres` — PostgreSQL 16.15 с named volume `postgres_data`; +- `redis` — Redis 8.10.2 без host-порта и persistence; - `migrate` — одноразовое применение версионированных миграций; - `api` — собранное из исходников Go-приложение без постоянного локального состояния. +Опциональный профиль `tools` запускает Redis Insight 3.8.0. Только его UI +доступен на `127.0.0.1:5540`; сам Redis остаётся внутри Compose-сети. + Образы закреплены одновременно версией и digest. Dockerfile использует multi-stage build, а runtime-процесс запускается от непривилегированного пользователя. @@ -99,8 +119,10 @@ multi-stage build, а runtime-процесс запускается от неп валидные длины строк, максимум 100 участников, внешние ключи и членство отправителя в чате. -Создание чата и всех строк членства выполняется одной транзакцией. Любая ошибка -до `COMMIT` приводит к rollback. Сообщение вставляется через +Создание чата и всех строк членства выполняется одной транзакцией. После вставки +чата участники добавляются через `INSERT ... SELECT FROM users`; отсутствие +пользователя даёт `RowsAffected() == 0` и выход до `COMMIT`. Deferred rollback +удаляет уже вставленный чат и предыдущие строки членства. Сообщение вставляется через `INSERT ... SELECT ... WHERE EXISTS`, поэтому проверка членства и вставка не разделены окном гонки. @@ -108,6 +130,12 @@ multi-stage build, а runtime-процесс запускается от неп версию, timestamp, UUID объекта и UUID владельца запроса/чата. Запрос читает `limit + 1`, чтобы определить `next_cursor` без отдельного `COUNT(*)`. +`make explain-history` внутри откатываемой транзакции создаёт 10 000 +синтетических сообщений, выполняет `ANALYZE` и два +`EXPLAIN (ANALYZE, BUFFERS)`. Первая страница и страница после курсора используют +`messages_chat_created_at_id_idx`, читают из индекса только требуемые 101 строку, +а не всю историю. Наблюдаемые времена одного запуска: 0.068 и 0.111 мс. + ### Аутентификация и сессии Регистрация требует пароль длиной 12–128 Unicode code points. Пароль хранится @@ -124,6 +152,28 @@ digest токена. Сессия имеет абсолютный `expires_at`, игнорируется. Неизвестный или чужой чат возвращает одинаковый 404, чтобы не раскрывать существование объекта. +### Redis cache-aside + +Ключ имеет вид `chat:v1:`, а значением является JSON с `id`, +`title`, упорядоченным `member_ids` и `created_at`. Версия в префиксе +позволяет сменить формат без неоднозначного чтения старых значений. + +`POST /chats` сначала подтверждает транзакцию PostgreSQL, затем best-effort +записывает созданный чат в Redis. `GET /chats/{id}` сначала читает Redis: +при hit проверяет членство вызывающего пользователя по `member_ids`; при miss +читает PostgreSQL и заполняет Redis. При сетевой ошибке Redis выполняется +fallback в PostgreSQL без второй попытки заполнения в том же запросе. + +Карточка и состав участников в контракте неизменяемы, поэтому отдельных +update/delete-инвалидаций сейчас нет. TTL равен 5 минутам и ограничивает время +жизни производной копии. Повреждённое или несовместимое значение удаляется и +считается ошибкой кеша. Неизвестные чаты не кешируются. + +Redis настроен с лимитом 64 MiB и `allkeys-lru`. RDB/AOF и volume намеренно +отключены: потеря кеша допустима, а после рестарта он лениво восстанавливается +из PostgreSQL. Сессии остаются в PostgreSQL, поэтому очистка Redis их не +отзывает. Пул Redis ограничен 10 соединениями, timeout операции — 250 мс. + ### Надёжность и конфигурация `pgxpool` ограничен параметрами `DB_MIN_CONNS`/`DB_MAX_CONNS`; запросы, @@ -135,9 +185,17 @@ digest токена. Сессия имеет абсолютный `expires_at`, PostgreSQL. Request ID присутствует в успешных ответах и ошибках, а logger не записывает body, пароль, Bearer-токен или заголовок Authorization. -`scripts/restart.sh` перезапускает PostgreSQL с сохранением volume, ждёт его -healthcheck и затем перезапускает API. Миграции при этом не выполняются заново и -данные не seed-ятся. +Автоматические action hooks останавливают ровно одну зависимость и всегда +восстанавливают её в `finally`. При отказе Redis API использует PostgreSQL. При +отказе обязательной PostgreSQL liveness остаётся 200, readiness и запросы к БД +возвращают ограниченный 503 `unavailable`, а запрос без Bearer отклоняется 401 +до обращения к БД. Отдельный сценарий пересоздаёт API с +`SESSION_TTL_SECONDS=2`, проверяет expiry, неверный пароль и logout, затем +возвращает обычное значение из `.env` (в проверенном стенде — 3600 секунд). + +`scripts/restart.sh` перезапускает PostgreSQL и Redis, ждёт оба healthcheck и +затем перезапускает API. PostgreSQL volume сохраняется, а Redis начинает с +пустого кеша. Миграции при этом не выполняются заново и данные не seed-ятся. ## Доказательства критериев @@ -152,28 +210,35 @@ healthcheck и затем перезапускает API. Миграции пр | Persistence данных и сессии | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS с прежним Bearer-токеном | `evidence/level3.md` | | Схема PostgreSQL | запросы к `pg_catalog` | 5 прикладных таблиц, 12 индексов, 23 ограничения | `evidence/level3.md` | | Защита локальных секретов | `git check-ignore` и `git ls-files` | `.env`, `.venv/`, `secrets/` игнорируются и не отслеживаются | `evidence/level3.md` | +| Redis cache-aside и TTL | `redis-cli`, повторный GET | Ключ `chat:v1:*`, JSON-карточка, TTL около 300 с | `evidence/level4.md` | +| Отказ Redis | `make test-cache-fallback` | PASS: readiness, Bearer-сессия, чтение и запись работают через PostgreSQL | `evidence/level4.md` | +| Конкурентная регистрация и rollback | `make test-level4-transactions` | PASS: один 201, три 409; неуспешный чат не оставил данных | `evidence/level4.md` | +| Короткий TTL, неверный пароль, logout | `make test-session-security` | PASS при `SESSION_TTL_SECONDS=2`; обычная конфигурация восстановлена | `evidence/level4.md` | +| Отказ PostgreSQL | `make test-database-failure` | PASS: live=200, ready/DB=503, anonymous=401, восстановление старой сессии | `evidence/level4.md` | +| Индекс истории | `make explain-history` | 10 000 строк; Index Scan, 101 строка, 0.068/0.111 мс | `evidence/level4.md` | +| Redis Insight | `make compose-tools-up` и `/api/health/` | `{"status":"up"}`, UI только на localhost | `evidence/level4.md` | ## Эксперименты и отказы | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | | Повторное применение мигратора | Схема и данные не дублируются | `no change`, migration version 1, `dirty=false` | Без простоя API; потерь нет | -| Restart API и PostgreSQL | Сохранить пользователей, чат, сообщение и действующую сессию | Public persistence test завершился PASS с токеном, хранившимся только в памяти теста | В пределах 90-секундного бюджета теста; потерь подтверждённых данных нет | +| Restart API, PostgreSQL и Redis | Сохранить пользователей, чат, сообщение и действующую сессию; пустой кеш восстановить | Persistence test завершился PASS с прежним токеном; последующее чтение снова создало ключ | В пределах 90-секундного бюджета; потерь подтверждённых данных нет | +| Stop Redis | Не менять readiness и не отдавать 5xx для доступных из PostgreSQL операций | Автотест подтвердил чтение старого чата, создание нового, сохранение Bearer-auth и 401 для неверного токена | Fallback GET около 254 мс при timeout 250 мс; потерь нет | +| Stop PostgreSQL | Оставить liveness, снять readiness и не раскрывать внутренние ошибки | Автотест получил live 200, ready 503, DB-запросы 503 и anonymous 401; после start прежняя сессия снова работает | Ответы ограничены DB/readiness timeout; подтверждённые данные не потеряны | +| API с TTL сессии 2 с | Быстро отозвать токен по времени и сохранить logout | Автотест получил 401 после 3.25 с, затем подтвердил новый login и немедленный отзыв logout | API автоматически возвращён к TTL 3600 с | -Проверка выполнялась на синтетических данных. После нескольких smoke и -persistence-запусков PostgreSQL содержал 18 пользователей, 6 чатов, 12 строк -членства, 9 сообщений и 15 действующих/неочищенных строк сессий. +Проверка выполнялась только на синтетических данных. Зафиксированные количества +уровня 3 приведены в `evidence/level3.md`; последующие Redis-тесты добавляли +новые синтетические строки, поэтому эти значения не выдаются за актуальный +production-снимок. ## Ограничения и следующие шаги -- Уровень 4 ещё не реализован: Redis будет добавлен как необязательный - cache-aside кэш неизменяемых данных чата; PostgreSQL останется источником истины. -- Redis failure должен приводить к fallback в PostgreSQL, а не к потере данных - или отказу readiness. -- Нужны отдельные интеграционные проверки конкурентной регистрации, rollback - создания чата, короткого expiry и отказов Redis/PostgreSQL. -- Для уровня 4 требуется `EXPLAIN (ANALYZE, BUFFERS)` минимум на 10 000 - сообщениях. +- Все обязательные критерии уровня 4 реализованы и имеют автоматические или + воспроизводимые проверки. Это не доказывает промышленную отказоустойчивость, + корректность при произвольных сетевых partition или максимальную пропускную + способность. - Track 2 уровня 5 ещё не выполнен: нужны не менее 100 000 неравномерно распределённых сообщений, сравнение вариантов индексов/запросов, стоимость записи и проверенный backup/restore. diff --git a/cmd/server/main.go b/cmd/server/main.go index 04ec744..3c9f7c9 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -10,6 +10,7 @@ import ( "syscall" "time" + applicationCache "mtusi2026lab2/internal/cache" "mtusi2026lab2/internal/config" "mtusi2026lab2/internal/database" "mtusi2026lab2/internal/store" @@ -41,8 +42,44 @@ func main() { cfg.DatabaseQueryTimeout, ) + var applicationStore store.Repository = postgresStore + + if cfg.RedisURL != "" { + redisChatCache, cacheError := applicationCache.NewRedisChatCache( + cfg.RedisURL, + cfg.RedisCacheTTL, + cfg.RedisOperationTimeout, + cfg.RedisPoolSize, + ) + if cacheError != nil { + log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError) + } + defer func() { + if closeError := redisChatCache.Close(); closeError != nil { + log.Printf("[WARN] Redis client close failed: %v", closeError) + } + }() + + cacheContext, cacheCancel := context.WithTimeout( + context.Background(), + cfg.RedisOperationTimeout, + ) + if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil { + log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError) + } else { + log.Println("[INFO] Redis chat cache is available") + } + cacheCancel() + + applicationStore = store.NewCachedRepository( + postgresStore, + redisChatCache, + log.Default(), + ) + } + handler := handlers.NewHandler( - postgresStore, + applicationStore, handlers.WithReadiness( databasePool, cfg.ReadinessTimeout, diff --git a/compose.yaml b/compose.yaml index 5805761..02111e7 100644 --- a/compose.yaml +++ b/compose.yaml @@ -21,6 +21,29 @@ services: start_period: 5s restart: unless-stopped + redis: + image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0 + command: + [ + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--maxmemory", + "64mb", + "--maxmemory-policy", + "allkeys-lru", + ] + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + migrate: image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7 entrypoint: ["/bin/sh", "-ec"] @@ -51,6 +74,11 @@ services: SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} SESSION_STORE: ${SESSION_STORE:-postgres} + CACHE_URL: ${CACHE_URL:-redis://redis:6379/0} + CACHE_TTL: ${CACHE_TTL:-5m} + CACHE_OPERATION_TIMEOUT: ${CACHE_OPERATION_TIMEOUT:-250ms} + CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-10} + DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url} DB_MAX_CONNS: ${DB_MAX_CONNS:-10} @@ -85,8 +113,21 @@ services: stop_grace_period: 15s restart: unless-stopped + redis-insight: + image: redis/redisinsight:3.8.0@sha256:b5e19ee240abef6edb435871b90ff8a210995422e8e018ab61c0339d318a1f84 + profiles: ["tools"] + ports: + - "127.0.0.1:${REDIS_INSIGHT_PORT:-5540}:5540" + volumes: + - redis_insight_data:/data + depends_on: + redis: + condition: service_healthy + restart: unless-stopped + volumes: postgres_data: + redis_insight_data: secrets: postgres_password: diff --git a/docs/database.md b/docs/database.md index d2481d4..bdc0209 100644 --- a/docs/database.md +++ b/docs/database.md @@ -5,8 +5,38 @@ PostgreSQL является источником истины для пользователей, чатов, участников, сообщений и сессий. -Redis будет использоваться как cache-aside кэш чатов, но не как источник -истины. Потеря Redis не должна приводить к потере данных. +Redis используется как cache-aside кэш неизменяемых карточек чатов, но не как +источник истины. Потеря Redis не приводит к потере данных или сессий. + +## Redis cache-aside + +Ключ: + +```text +chat:v1: +``` + +Значение — JSON-представление `domain.Chat`: идентификатор, заголовок, +упорядоченный список участников и время создания. TTL по умолчанию — 5 минут. +Префикс `v1` версионирует внутренний формат независимо от HTTP API. + +Алгоритм чтения: + +1. Прочитать и проверить значение Redis. +2. При hit проверить, что вызывающий пользователь есть в `member_ids`. +3. При miss прочитать PostgreSQL и best-effort заполнить Redis. +4. При timeout/ошибке Redis прочитать PostgreSQL и не повторять cache write в + том же запросе. + +Создание чата сначала полностью фиксируется транзакцией PostgreSQL, после чего +выполняется best-effort запись в Redis. Контракт не содержит изменения +заголовка или состава участников и удаления чата, поэтому write-инвалидация +сейчас не требуется. TTL удаляет забытые копии, а повреждённое значение +удаляется при чтении. + +Redis работает без RDB/AOF и volume, с лимитом 64 MiB и `allkeys-lru`. +Это намеренная политика для производного кэша. Readiness зависит только от +PostgreSQL; при очистке или restart Redis данные лениво восстанавливаются. ## Общие решения @@ -149,12 +179,17 @@ CHECK (expires_at > created_at) Одна транзакция: -1. Проверить существование всех участников. -2. Вставить чат. -3. Вставить всех участников с позициями. +1. Вставить чат. +2. Для каждого участника выполнить параметризованный + `INSERT ... SELECT FROM users WHERE id = $2`. +3. Проверить, что каждая команда вставила ровно одну строку. 4. Выполнить COMMIT. -Любая ошибка приводит к ROLLBACK всей операции. +Если пользователя нет, `RowsAffected() == 0`: функция возвращает +`ErrNotFound`, а deferred `ROLLBACK` удаляет уже вставленный чат и предыдущие +membership-строки. Автотест отправляет существующего вызывающего и +несуществующий UUID, проверяет отсутствие частичного чата, затем успешно +создаёт другой чат через то же приложение. ### Отправка сообщения @@ -210,6 +245,39 @@ LIMIT $4 В обоих запросах передаётся `limit + 1`. Дополнительная строка определяет, нужно ли возвращать `next_cursor`, без отдельного `COUNT(*)`. +## План истории на 10 000 сообщений + +Команда `make explain-history` открывает транзакцию, добавляет отдельные +синтетические user/chat и ровно 10 000 сообщений, выполняет `ANALYZE`, печатает +два `EXPLAIN (ANALYZE, BUFFERS)` и завершает всё `ROLLBACK`. Поэтому измерение +повторяемо и не оставляет нагрузочные строки в постоянной БД. + +Для первой страницы наблюдался план: + +```text +Limit (actual rows=101) + -> Index Scan using messages_chat_created_at_id_idx + Index Cond: (chat_id = ...) +Buffers: shared hit=5 +Execution Time: 0.068 ms +``` + +Для страницы после 5000-го сообщения: + +```text +Limit (actual rows=101) + -> Index Scan using messages_chat_created_at_id_idx + Index Cond: chat_id = ... AND ROW(created_at, id) > ROW(...) +Buffers: shared hit=6 +Execution Time: 0.111 ms +``` + +Составной индекс `(chat_id, created_at, id)` одновременно соответствует +фильтру одного чата, tuple-границе keyset cursor и порядку выдачи. Поэтому +PostgreSQL не делает `Seq Scan` и не сортирует всю историю для каждой страницы. +Времена относятся только к указанному WSL2-стенду и не являются универсальным +production-бенчмарком. + ## Миграции Первая миграция создаёт таблицы в порядке: @@ -230,4 +298,4 @@ Compose-сервис. Миграции не запускаются автома Инструмент хранит текущую версию и состояние применения в служебной таблице `schema_migrations`. Неуспешная миграция останавливает запуск API и требует -явного разбора причины, а не автоматического `force`. \ No newline at end of file +явного разбора причины, а не автоматического `force`. diff --git a/evidence/level3.md b/evidence/level3.md index f769838..067fe52 100644 --- a/evidence/level3.md +++ b/evidence/level3.md @@ -1,7 +1,6 @@ # Доказательства уровня 3 -Состояние: рабочее дерево поверх commit `10b5842`; итоговый commit уровня 3 -создаётся после проверки staged diff. +Состояние: commit уровня 3 `158fed1` (`реализован уровень 3`). ## Окружение @@ -99,8 +98,9 @@ Executing explicit persistence hook; hook output suppressed to avoid leaking sec PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. ``` -Hook последовательно перезапускает `postgres`, ждёт его healthcheck и -перезапускает `api`. `docker compose ps` после сценария показывал оба сервиса в +В commit `158fed1` hook последовательно перезапускал `postgres`, ждал его +healthcheck и перезапускал `api`; Redis был добавлен следующим этапом. +`docker compose ps` после сценария показывал оба сервиса в состоянии `healthy`. Named volume: ```text diff --git a/evidence/level4.md b/evidence/level4.md new file mode 100644 index 0000000..5f29403 --- /dev/null +++ b/evidence/level4.md @@ -0,0 +1,236 @@ +# Доказательства уровня 4 + +Состояние: полный уровень 4 в ветке `solution/bvt2301-churilin` на базе commit +уровня 3 `158fed1`; результаты ниже получены перед публикацией изменений. + +Все созданные пользователи, чаты и сообщения синтетические. Пароли, Bearer +tokens, database URL и содержимое secret-файлов не сохранялись в evidence. + +## Проверенное окружение + +```text +Ubuntu 26.04 LTS, WSL2, x86_64 +Intel Core i5-1135G7, 4 cores / 8 logical CPU +Docker-visible RAM: 3.724 GiB +Docker Engine 29.7.2, Docker Compose 5.5.0 +Go 1.27.1, Python 3.14.4 +PostgreSQL 16.15 +Redis 8.10.2, go-redis/v9 v9.23.0 +Redis Insight 3.8.0 +``` + +API и PostgreSQL не имеют отдельных Compose CPU/RAM quotas и используют лимиты +Docker Desktop/WSL. Redis дополнительно ограничен `maxmemory=64mb`. Все +контейнерные образы закреплены точным тегом и digest. + +## Полная команда + +После запуска стенда все накопительные проверки объединены целью: + +```sh +make test-level4 PYTHON=.venv/bin/python +``` + +Она последовательно запускает Go tests/race/vet, offline check, OpenAPI +validation, Compose validation, public smoke, транзакционные сценарии, короткий +session TTL, отказ Redis, отказ PostgreSQL, полный restart и SQL EXPLAIN. + +## Cache-aside и TTL + +Ключ: + +```text +chat:v1: +``` + +Значение — JSON `domain.Chat` с полями `id`, `title`, `member_ids` и +`created_at`. Наблюдаемый TTL после чтения был 243 секунды из настроенных 300: + +```text +db0: keys=1, expires=1 +maxmemory=67108864 +maxmemory-policy=allkeys-lru +save="" +appendonly=no +``` + +PostgreSQL остаётся источником истины. RDB/AOF и Redis volume намеренно +отключены, так как потерянная карточка лениво восстанавливается из PostgreSQL. +Unit-тесты подтверждают miss → source → fill, hit без второго source read, +проверку членства на hit и игнорирование ошибки best-effort cache write. + +## Отказ Redis + +```sh +make test-cache-fallback +``` + +```text +Stopping only Redis; hook output is suppressed. +PASS: Redis outage used PostgreSQL fallback; readiness, session, +authorization and writes remained correct. +``` + +Сценарий прогревает карточку, останавливает только Redis, тем же Bearer-токеном +проверяет readiness, читает существующий чат и создаёт новый. Запрос без +корректного токена остаётся 401. После запуска Redis чтение нового чата снова +заполняет кеш. + +Наблюдаемые времена отдельного запуска: + +```text +cache hit GET: 0.84 ms +fallback GET: 254.46 ms +POST during outage: 254.31 ms +first GET after recovery: 3.10 ms +``` + +Redis timeout равен 250 ms. После сетевой ошибки чтения в том же запросе не +выполняется вторая cache write, поэтому fallback не платит второй timeout. + +## Конкурентная регистрация и rollback + +```sh +make test-level4-transactions +``` + +```text +PASS: concurrent username race produced one winner; failed composite chat +creation rolled back and the connection remained usable. +``` + +Четыре параллельных запроса регистрируют один и тот же уникальный username. +Тест требует ровно один HTTP 201 и три HTTP 409. Решение принимает окончательное +решение по ограничению `users_username_unique`, а не по небезопасной схеме +check-then-insert. + +Для rollback тест создаёт чат с существующим вызывающим и несуществующим UUID +второго участника. Код успевает вставить строку `chats` и первого участника, +затем получает `RowsAffected() == 0` на `INSERT ... SELECT FROM users`. +Deferred rollback отменяет обе вставки. Чат не появляется в списке пользователя, +а следующая составная операция через тот же API успешно завершается. + +## Короткий expiry, неверный пароль и logout + +```sh +make test-session-security +``` + +```text +PASS: deployed short SESSION_TTL_SECONDS expired the token; wrong password +and logout remained enforced. +``` + +Action hook временно пересоздаёт API с `SESSION_TTL_SECONDS=2`. Автотест +проверяет: + +1. неправильный пароль получает 401; +2. новый Bearer-токен сразу работает; +3. через 3.25 секунды тот же токен получает 401; +4. новая сессия создаётся с правильным паролем; +5. logout возвращает 204; +6. отозванный токен сразу получает 401. + +Блок `finally` пересоздаёт API с обычной конфигурацией. После теста внутри +контейнера подтверждено `SESSION_TTL_SECONDS=3600`. + +## Отказ обязательной PostgreSQL + +```sh +make test-database-failure +``` + +```text +Stopping only PostgreSQL; hook output is suppressed. +PASS: PostgreSQL outage returned bounded 503 responses, anonymous access +stayed rejected, and the existing session recovered. +``` + +Во время остановки только PostgreSQL: + +- `/health/live` возвращает 200; +- `/health/ready` возвращает ограниченный 503 `unavailable`; +- запрос без Bearer отклоняется 401 до обращения к БД; +- запрос с ранее действующим Bearer возвращает 503, а не считается доверенным; +- запись пользователя возвращает 503 без деталей драйвера/SQL. + +После запуска PostgreSQL существующий пул соединений восстанавливается, а +прежний Bearer-токен снова получает исходного пользователя. + +## План истории на 10 000 сообщений + +```sh +make explain-history +``` + +Сценарий создаёт данные внутри транзакции, выполняет `ANALYZE` и в конце делает +`ROLLBACK`. Постоянные таблицы после измерения не засоряются. + +```text +synthetic_message_count +----------------------- +10000 +``` + +Первая страница: + +```text +Limit (actual time=0.019..0.043 rows=101 loops=1) + -> Index Scan using messages_chat_created_at_id_idx + (actual time=0.018..0.037 rows=101 loops=1) + Index Cond: (chat_id = ...) +Buffers: shared hit=5 +Execution Time: 0.068 ms +``` + +Страница после курсора на позиции 5000: + +```text +Limit (actual time=0.013..0.046 rows=101 loops=1) + -> Index Scan using messages_chat_created_at_id_idx + (actual time=0.012..0.040 rows=101 loops=1) + Index Cond: chat_id = ... AND ROW(created_at, id) > ROW(...) +Buffers: shared hit=6 +Execution Time: 0.111 ms +``` + +Оба запроса используют индекс `(chat_id, created_at, id)`, не выполняют +`Seq Scan` и возвращают только `limit + 1 = 101` строку. Времена относятся к +описанному локальному стенду и не объявляются production-бенчмарком. + +## Полный restart + +```sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +```text +PASS: persistence preserved confirmed data and existing session. +``` + +Hook перезапускает PostgreSQL и Redis, ждёт оба healthcheck и перезапускает API. +PostgreSQL volume сохраняет данные и сессию. Redis стартует пустым и лениво +заполняется после следующего чтения. + +## Redis Insight + +```sh +make compose-tools-up +curl http://127.0.0.1:5540/api/health/ +``` + +```json +{"status":"up"} +``` + +Для ручного подключения внутри UI: host `redis`, port `6379`, database `0`, +без TLS и пароля. Такая конфигурация допустима только для изолированного +локального учебного стенда: Redis не публикует host-port, а UI привязан к +`127.0.0.1`. + +## Границы доказательства + +Проверки подтверждают обязательные критерии уровня 4 в указанном одноузловом +стенде. Они не доказывают HA PostgreSQL, поведение при произвольном network +partition, максимальную пропускную способность или критерии выбранного Track 2 +уровня 5. diff --git a/go.mod b/go.mod index 6530bfe..f880f62 100644 --- a/go.mod +++ b/go.mod @@ -5,13 +5,16 @@ go 1.27.1 require ( github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.11.0 + github.com/redis/go-redis/v9 v9.23.0 golang.org/x/crypto v0.57.0 ) require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect + go.uber.org/atomic v1.12.0 // indirect golang.org/x/sync v0.23.0 // indirect golang.org/x/sys v0.48.0 // indirect golang.org/x/text v0.42.0 // indirect diff --git a/go.sum b/go.sum index 112f194..409359b 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,10 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= @@ -11,13 +15,22 @@ github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= +github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= @@ -28,5 +41,3 @@ golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/cache/chat.go b/internal/cache/chat.go new file mode 100644 index 0000000..2ce42a0 --- /dev/null +++ b/internal/cache/chat.go @@ -0,0 +1,175 @@ +package cache + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "mtusi2026lab2/internal/domain" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +const chatKeyPrefix = "chat:v1:" + +var ErrMiss = errors.New("cache miss") + +// ChatCache хранит только производную копию неизменяемых данных чата. +// PostgreSQL остаётся источником истины. +type ChatCache interface { + Get(ctx context.Context, chatID string) (domain.Chat, error) + Set(ctx context.Context, chat domain.Chat) error +} + +type RedisChatCache struct { + client *redis.Client + ttl time.Duration + operationTimeout time.Duration +} + +func NewRedisChatCache( + redisURL string, + ttl time.Duration, + operationTimeout time.Duration, + poolSize int, +) (*RedisChatCache, error) { + options, err := redis.ParseURL(strings.TrimSpace(redisURL)) + if err != nil { + return nil, fmt.Errorf("parse Redis URL: %w", err) + } + + options.DialTimeout = operationTimeout + options.ReadTimeout = operationTimeout + options.WriteTimeout = operationTimeout + options.PoolTimeout = operationTimeout + options.PoolSize = poolSize + options.MaxRetries = -1 + + return &RedisChatCache{ + client: redis.NewClient(options), + ttl: ttl, + operationTimeout: operationTimeout, + }, nil +} + +func (c *RedisChatCache) Ping(ctx context.Context) error { + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + if err := c.client.Ping(operationContext).Err(); err != nil { + return fmt.Errorf("ping Redis: %w", err) + } + + return nil +} + +func (c *RedisChatCache) Close() error { + return c.client.Close() +} + +func (c *RedisChatCache) Get( + ctx context.Context, + chatID string, +) (domain.Chat, error) { + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + payload, err := c.client.Get( + operationContext, + chatKey(chatID), + ).Bytes() + if errors.Is(err, redis.Nil) { + return domain.Chat{}, ErrMiss + } + if err != nil { + return domain.Chat{}, fmt.Errorf("get cached chat: %w", err) + } + + var chat domain.Chat + if err = json.Unmarshal(payload, &chat); err != nil { + c.deleteInvalidValue(operationContext, chatID) + return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err) + } + + if err = validateCachedChat(chat, chatID); err != nil { + c.deleteInvalidValue(operationContext, chatID) + return domain.Chat{}, err + } + + return chat, nil +} + +func (c *RedisChatCache) Set( + ctx context.Context, + chat domain.Chat, +) error { + payload, err := json.Marshal(chat) + if err != nil { + return fmt.Errorf("encode chat for cache: %w", err) + } + + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + if err = c.client.Set( + operationContext, + chatKey(chat.ID), + payload, + c.ttl, + ).Err(); err != nil { + return fmt.Errorf("cache chat: %w", err) + } + + return nil +} + +func (c *RedisChatCache) withTimeout( + ctx context.Context, +) (context.Context, context.CancelFunc) { + return context.WithTimeout(ctx, c.operationTimeout) +} + +func (c *RedisChatCache) deleteInvalidValue( + ctx context.Context, + chatID string, +) { + _ = c.client.Del(ctx, chatKey(chatID)).Err() +} + +func chatKey(chatID string) string { + return chatKeyPrefix + chatID +} + +func validateCachedChat(chat domain.Chat, expectedID string) error { + if chat.ID != expectedID { + return errors.New("cached chat id does not match cache key") + } + if _, err := uuid.Parse(chat.ID); err != nil { + return errors.New("cached chat contains invalid id") + } + if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() { + return errors.New("cached chat is incomplete") + } + if len(chat.MemberIDs) == 0 { + return errors.New("cached chat has no members") + } + + seenMembers := make(map[string]struct{}, len(chat.MemberIDs)) + for _, memberID := range chat.MemberIDs { + if _, err := uuid.Parse(memberID); err != nil { + return errors.New("cached chat contains invalid member id") + } + if _, exists := seenMembers[memberID]; exists { + return errors.New("cached chat contains duplicate member id") + } + seenMembers[memberID] = struct{}{} + } + + return nil +} + +var _ ChatCache = (*RedisChatCache)(nil) diff --git a/internal/config/config.go b/internal/config/config.go index a9f7132..a02b1e9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -25,6 +25,11 @@ type Config struct { DatabaseConnectTimeout time.Duration DatabaseQueryTimeout time.Duration + RedisURL string + RedisCacheTTL time.Duration + RedisOperationTimeout time.Duration + RedisPoolSize int + ReadinessTimeout time.Duration ShutdownTimeout time.Duration } @@ -96,6 +101,32 @@ func Load() (Config, error) { return Config{}, err } + redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE") + if err != nil { + return Config{}, err + } + + redisCacheTTL, err := durationFromEnv( + "CACHE_TTL", + 5*time.Minute, + ) + if err != nil { + return Config{}, err + } + + redisOperationTimeout, err := durationFromEnv( + "CACHE_OPERATION_TIMEOUT", + 250*time.Millisecond, + ) + if err != nil { + return Config{}, err + } + + redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1) + if err != nil { + return Config{}, err + } + readinessTimeout, err := durationFromEnv( "READINESS_TIMEOUT", 2*time.Second, @@ -132,6 +163,11 @@ func Load() (Config, error) { DatabaseConnectTimeout: databaseConnectTimeout, DatabaseQueryTimeout: databaseQueryTimeout, + RedisURL: redisURL, + RedisCacheTTL: redisCacheTTL, + RedisOperationTimeout: redisOperationTimeout, + RedisPoolSize: int(redisPoolSize), + ReadinessTimeout: readinessTimeout, ShutdownTimeout: shutdownTimeout, }, nil @@ -184,6 +220,49 @@ func requiredValueOrFile(valueEnv, fileEnv string) (string, error) { return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv) } +func optionalValueOrFile(valueEnv, fileEnv string) (string, error) { + value, valueExists := os.LookupEnv(valueEnv) + filePath, fileExists := os.LookupEnv(fileEnv) + + if valueExists && fileExists { + return "", fmt.Errorf( + "%s and %s must not be set at the same time", + valueEnv, + fileEnv, + ) + } + + if valueExists { + value = strings.TrimSpace(value) + if value == "" { + return "", fmt.Errorf("%s must not be empty", valueEnv) + } + + return value, nil + } + + if fileExists { + filePath = strings.TrimSpace(filePath) + if filePath == "" { + return "", fmt.Errorf("%s must not be empty", fileEnv) + } + + data, err := os.ReadFile(filePath) + if err != nil { + return "", fmt.Errorf("read %s: %w", fileEnv, err) + } + + value = strings.TrimSpace(string(data)) + if value == "" { + return "", fmt.Errorf("file from %s must not be empty", fileEnv) + } + + return value, nil + } + + return "", nil +} + func envOrDefault(name, fallback string) string { value := strings.TrimSpace(os.Getenv(name)) if value == "" { diff --git a/internal/store/cached_repository.go b/internal/store/cached_repository.go new file mode 100644 index 0000000..5cc8c4a --- /dev/null +++ b/internal/store/cached_repository.go @@ -0,0 +1,98 @@ +package store + +import ( + "context" + "errors" + "log" + + applicationCache "mtusi2026lab2/internal/cache" + "mtusi2026lab2/internal/domain" +) + +// CachedRepository декорирует основной Repository. Все операции, кроме чтения +// и создания чата, автоматически делегируются встроенному Repository. +type CachedRepository struct { + Repository + chatCache applicationCache.ChatCache + logger *log.Logger +} + +func NewCachedRepository( + repository Repository, + chatCache applicationCache.ChatCache, + logger *log.Logger, +) *CachedRepository { + if logger == nil { + logger = log.Default() + } + + return &CachedRepository{ + Repository: repository, + chatCache: chatCache, + logger: logger, + } +} + +func (r *CachedRepository) CreateChat( + ctx context.Context, + title string, + memberIDs []string, +) (domain.Chat, error) { + chat, err := r.Repository.CreateChat(ctx, title, memberIDs) + if err != nil { + return domain.Chat{}, err + } + + // Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не + // должна превращать успешную бизнес-операцию в 503. + if err = r.chatCache.Set(ctx, chat); err != nil { + r.logger.Printf("[WARN] Redis chat cache write failed: %v", err) + } + + return chat, nil +} + +func (r *CachedRepository) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + chat, err := r.chatCache.Get(ctx, chatID) + if err == nil { + if !containsMember(chat.MemberIDs, callerID) { + return domain.Chat{}, ErrNotFound + } + + return chat, nil + } + + shouldFillCache := errors.Is(err, applicationCache.ErrMiss) + if !shouldFillCache { + r.logger.Printf("[WARN] Redis chat cache read failed: %v", err) + } + + chat, err = r.Repository.GetChatByID(ctx, chatID, callerID) + if err != nil { + return domain.Chat{}, err + } + + if shouldFillCache { + if err = r.chatCache.Set(ctx, chat); err != nil { + r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err) + } + } + + return chat, nil +} + +func containsMember(memberIDs []string, callerID string) bool { + for _, memberID := range memberIDs { + if memberID == callerID { + return true + } + } + + return false +} + +var _ Repository = (*CachedRepository)(nil) diff --git a/internal/store/cached_repository_test.go b/internal/store/cached_repository_test.go new file mode 100644 index 0000000..eff51f3 --- /dev/null +++ b/internal/store/cached_repository_test.go @@ -0,0 +1,181 @@ +package store + +import ( + "context" + "errors" + "io" + "log" + "testing" + + applicationCache "mtusi2026lab2/internal/cache" + "mtusi2026lab2/internal/domain" +) + +type fakeChatCache struct { + chats map[string]domain.Chat + getErr error + setErr error + sets int +} + +func (c *fakeChatCache) Get( + _ context.Context, + chatID string, +) (domain.Chat, error) { + if c.getErr != nil { + return domain.Chat{}, c.getErr + } + + chat, exists := c.chats[chatID] + if !exists { + return domain.Chat{}, applicationCache.ErrMiss + } + + return chat, nil +} + +func (c *fakeChatCache) Set( + _ context.Context, + chat domain.Chat, +) error { + c.sets++ + if c.setErr != nil { + return c.setErr + } + c.chats[chat.ID] = chat + + return nil +} + +type countingRepository struct { + Repository + getChatCalls int +} + +func (r *countingRepository) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + r.getChatCalls++ + return r.Repository.GetChatByID(ctx, chatID, callerID) +} + +func cachedRepositoryFixture( + t *testing.T, +) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) { + t.Helper() + + legacy := NewMemoryStore() + member, err := legacy.CreateUser("cache_member", "Участник") + if err != nil { + t.Fatalf("create member: %v", err) + } + outsider, err := legacy.CreateUser("cache_outsider", "Посторонний") + if err != nil { + t.Fatalf("create outsider: %v", err) + } + chat, err := legacy.CreateChat("Кешируемый чат", []string{member.ID}) + if err != nil { + t.Fatalf("create chat: %v", err) + } + + repository := &countingRepository{ + Repository: NewMemoryRepository(legacy), + } + chatCache := &fakeChatCache{ + chats: make(map[string]domain.Chat), + } + + return repository, chatCache, member, outsider, chat +} + +func TestCachedRepositoryMissThenHit(t *testing.T) { + repository, chatCache, member, _, expected := cachedRepositoryFixture(t) + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + first, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("first read: %v", err) + } + second, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("second read: %v", err) + } + + if repository.getChatCalls != 1 { + t.Fatalf("expected one source read, got %d", repository.getChatCalls) + } + if chatCache.sets != 1 { + t.Fatalf("expected one cache fill, got %d", chatCache.sets) + } + if first.ID != expected.ID || second.ID != expected.ID { + t.Fatal("cache changed chat identity") + } +} + +func TestCachedRepositoryFallsBackWhenCacheUnavailable(t *testing.T) { + repository, chatCache, member, _, expected := cachedRepositoryFixture(t) + chatCache.getErr = errors.New("redis unavailable") + chatCache.setErr = errors.New("redis unavailable") + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + chat, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("fallback read: %v", err) + } + if chat.ID != expected.ID || repository.getChatCalls != 1 { + t.Fatal("source repository was not used after cache failure") + } + if chatCache.sets != 0 { + t.Fatal("failed cache read must not trigger another cache operation") + } +} + +func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) { + repository, chatCache, _, outsider, expected := cachedRepositoryFixture(t) + chatCache.chats[expected.ID] = expected + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + _, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID) + if !errors.Is(err, ErrNotFound) { + t.Fatalf("expected ErrNotFound for outsider, got %v", err) + } + if repository.getChatCalls != 0 { + t.Fatal("cache hit unexpectedly queried source repository") + } +} + +func TestCachedRepositoryIgnoresWriteFailure(t *testing.T) { + repository, chatCache, member, _, _ := cachedRepositoryFixture(t) + chatCache.setErr = errors.New("redis unavailable") + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + chat, err := cached.CreateChat( + context.Background(), + "Новый чат", + []string{member.ID}, + ) + if err != nil { + t.Fatalf("create chat with unavailable cache: %v", err) + } + if chat.ID == "" || chatCache.sets != 1 { + t.Fatal("chat was not created before best-effort cache write") + } +} diff --git a/internal/store/postgres_chats.go b/internal/store/postgres_chats.go index 3a97426..10dfa6c 100644 --- a/internal/store/postgres_chats.go +++ b/internal/store/postgres_chats.go @@ -31,40 +31,6 @@ func (s *PostgreSQLStore) CreateChat( _ = transaction.Rollback(queryContext) }() - // Проверяем участников внутри той же транзакции, в которой - // создаются чат и строки членства. - for _, memberID := range memberIDs { - var exists bool - - err = transaction.QueryRow( - queryContext, - ` - SELECT EXISTS ( - SELECT 1 - FROM users - WHERE id = $1 - ) - `, - memberID, - ).Scan(&exists) - - if err != nil { - return domain.Chat{}, fmt.Errorf( - "check chat member %s: %w", - memberID, - err, - ) - } - - if !exists { - return domain.Chat{}, fmt.Errorf( - "%w: member %s", - ErrNotFound, - memberID, - ) - } - } - chat := domain.Chat{ ID: uuid.NewString(), Title: title, @@ -89,7 +55,7 @@ func (s *PostgreSQLStore) CreateChat( } for position, memberID := range memberIDs { - _, err = transaction.Exec( + commandTag, insertErr := transaction.Exec( queryContext, ` INSERT INTO chat_members ( @@ -97,17 +63,33 @@ func (s *PostgreSQLStore) CreateChat( user_id, position ) - VALUES ($1, $2, $3) + SELECT + $1, + id, + $3 + FROM users + WHERE id = $2 `, chat.ID, memberID, position, ) - if err != nil { + if insertErr != nil { return domain.Chat{}, fmt.Errorf( "insert chat member %s: %w", memberID, - err, + insertErr, + ) + } + + // INSERT ... SELECT не вставляет строку, если пользователя нет. + // Возврат из функции активирует deferred Rollback: уже созданные + // chat и предыдущие membership-строки не останутся в базе. + if commandTag.RowsAffected() != 1 { + return domain.Chat{}, fmt.Errorf( + "%w: member %s", + ErrNotFound, + memberID, ) } } diff --git a/scripts/explain_history.sh b/scripts/explain_history.sh new file mode 100755 index 0000000..c9ca9f2 --- /dev/null +++ b/scripts/explain_history.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +env_file=${ENV_FILE:-.env} + +docker compose --env-file "$env_file" exec -T postgres sh -ec \ + 'exec psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"' \ + < tests/explain_history.sql diff --git a/scripts/postgres_outage.sh b/scripts/postgres_outage.sh new file mode 100755 index 0000000..980cdf2 --- /dev/null +++ b/scripts/postgres_outage.sh @@ -0,0 +1,20 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +env_file=${ENV_FILE:-.env} + +case "${DATABASE_ACTION:-}" in + stop) + docker compose --env-file "$env_file" stop postgres + ;; + start) + docker compose --env-file "$env_file" up -d --wait postgres + ;; + *) + echo "DATABASE_ACTION must be stop or start" >&2 + exit 2 + ;; +esac diff --git a/scripts/redis_outage.sh b/scripts/redis_outage.sh new file mode 100755 index 0000000..f9f9386 --- /dev/null +++ b/scripts/redis_outage.sh @@ -0,0 +1,20 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +env_file=${ENV_FILE:-.env} + +case "${CACHE_ACTION:-}" in + stop) + docker compose --env-file "$env_file" stop redis + ;; + start) + docker compose --env-file "$env_file" up -d --wait redis + ;; + *) + echo "CACHE_ACTION must be stop or start" >&2 + exit 2 + ;; +esac diff --git a/scripts/restart.sh b/scripts/restart.sh index 64e9c2a..8ecf62c 100755 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -7,9 +7,9 @@ cd "$project_root" env_file=${ENV_FILE:-.env} # PostgreSQL хранит все обязательные данные и сессии в named volume. -# Обычный restart не удаляет volume и не применяет миграции повторно. -docker compose --env-file "$env_file" restart postgres -docker compose --env-file "$env_file" up -d --wait postgres +# Redis содержит только восстанавливаемый кеш и намеренно не имеет volume. +docker compose --env-file "$env_file" restart postgres redis +docker compose --env-file "$env_file" up -d --wait postgres redis -# API перезапускается после восстановления готовности PostgreSQL. +# API перезапускается после восстановления обязательной БД и кеша. docker compose --env-file "$env_file" restart api diff --git a/scripts/session_ttl.sh b/scripts/session_ttl.sh new file mode 100755 index 0000000..74102c6 --- /dev/null +++ b/scripts/session_ttl.sh @@ -0,0 +1,29 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +env_file=${ENV_FILE:-.env} + +case "${SESSION_TTL_ACTION:-}" in + short) + ttl=${SHORT_SESSION_TTL_SECONDS:-2} + case "$ttl" in + ''|*[!0-9]*|0) + echo "SHORT_SESSION_TTL_SECONDS must be a positive integer" >&2 + exit 2 + ;; + esac + SESSION_TTL_SECONDS="$ttl" docker compose --env-file "$env_file" \ + up -d --no-deps --force-recreate --wait api + ;; + restore) + docker compose --env-file "$env_file" \ + up -d --no-deps --force-recreate --wait api + ;; + *) + echo "SESSION_TTL_ACTION must be short or restore" >&2 + exit 2 + ;; +esac diff --git a/tests/cache_resilience.py b/tests/cache_resilience.py new file mode 100755 index 0000000..2082347 --- /dev/null +++ b/tests/cache_resilience.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Verify that Redis outage degrades to PostgreSQL without bypassing auth.""" +import os +from pathlib import Path +import subprocess +import uuid + +from client import Client, Failure, arguments, check, run + + +def execute_hook(script, action): + env = dict(os.environ) + env['CACHE_ACTION'] = action + try: + result = subprocess.run( + [str(script)], + env=env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=90, + check=False, + ) + except subprocess.TimeoutExpired: + raise Failure('Redis outage hook exceeded 90 seconds') from None + check(result.returncode == 0, 'Redis outage hook failed for action ' + action) + + +def main(): + def configure(parser): + parser.add_argument( + '--action-script', + required=True, + help='Executable student hook controlled by CACHE_ACTION=stop|start', + ) + + args = arguments( + 'Redis failure scenario; creates only synthetic API data', + configure, + ) + script = Path(args.action_script).expanduser().resolve() + check( + script.is_file() and os.access(script, os.X_OK), + 'action script must exist and be executable (chmod +x)', + ) + + client = Client(args.base_url, args.ca_file, timeout=3) + alice, bob, _, original_chat = client.bootstrap() + path = '/api/v1/chats/' + original_chat['id'] + + warmed = client.call( + 'GET', + path, + actor=bob, + schema='Chat', + )['json'] + check(warmed == original_chat, 'warm read changed chat data') + + print('Stopping only Redis; hook output is suppressed.') + execute_hook(script, 'stop') + + created_during_outage = None + try: + client.call('GET', '/health/ready', schema='Health') + + fallback = client.call( + 'GET', + path, + actor=bob, + schema='Chat', + )['json'] + check(fallback == original_chat, 'PostgreSQL fallback changed chat data') + + created_during_outage = client.call( + 'POST', + '/api/v1/chats', + 201, + actor=alice, + body={ + 'title': 'Redis outage ' + uuid.uuid4().hex[:8], + 'member_ids': [alice['id'], bob['id']], + }, + schema='Chat', + )['json'] + + client.call('GET', path, 401, actor={'id': 'unused', 'token': 'invalid'}) + finally: + execute_hook(script, 'start') + + check(created_during_outage is not None, 'chat was not created during outage') + recovered = client.call( + 'GET', + '/api/v1/chats/' + created_during_outage['id'], + actor=bob, + schema='Chat', + )['json'] + check(recovered == created_during_outage, 'cache recovery changed chat data') + + print( + 'PASS: Redis outage used PostgreSQL fallback; readiness, session, ' + 'authorization and writes remained correct.' + ) + + +if __name__ == '__main__': + run(main) diff --git a/tests/database_resilience.py b/tests/database_resilience.py new file mode 100755 index 0000000..ae107b9 --- /dev/null +++ b/tests/database_resilience.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Verify bounded behavior while mandatory PostgreSQL is unavailable.""" +import os +from pathlib import Path +import subprocess +import time +import uuid + +from client import Client, Failure, arguments, check, run + + +def execute_hook(script, action): + env = dict(os.environ) + env['DATABASE_ACTION'] = action + try: + result = subprocess.run( + [str(script)], + env=env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=90, + check=False, + ) + except subprocess.TimeoutExpired: + raise Failure('PostgreSQL outage hook exceeded 90 seconds') from None + check( + result.returncode == 0, + 'PostgreSQL outage hook failed for action ' + action, + ) + + +def main(): + def configure(parser): + parser.add_argument( + '--action-script', + required=True, + help='Executable hook controlled by DATABASE_ACTION=stop|start', + ) + + args = arguments( + 'PostgreSQL failure scenario; creates only synthetic API data', + configure, + ) + script = Path(args.action_script).expanduser().resolve() + check( + script.is_file() and os.access(script, os.X_OK), + 'action script must exist and be executable (chmod +x)', + ) + + client = Client(args.base_url, args.ca_file, timeout=8) + alice, _, _, _ = client.bootstrap() + + print('Stopping only PostgreSQL; hook output is suppressed.') + execute_hook(script, 'stop') + try: + client.call('GET', '/health/live', schema='Health') + readiness = client.call('GET', '/health/ready', 503) + check( + readiness['json']['error']['code'] == 'unavailable', + 'readiness did not return a bounded unavailable error', + ) + + client.call('GET', '/api/v1/users/me', 401) + authenticated = client.call( + 'GET', + '/api/v1/users/me', + 503, + actor=alice, + ) + check( + authenticated['json']['error']['code'] == 'unavailable', + 'database auth failure did not return unavailable', + ) + + registration = client.call( + 'POST', + '/api/v1/users', + 503, + body={ + 'username': 'db_down_' + uuid.uuid4().hex[:16], + 'display_name': 'Database outage', + 'password': 'T3st-' + uuid.uuid4().hex, + }, + ) + check( + registration['json']['error']['code'] == 'unavailable', + 'write during database outage did not return unavailable', + ) + finally: + execute_hook(script, 'start') + + deadline = time.monotonic() + 20 + while True: + try: + recovered = client.call( + 'GET', + '/api/v1/users/me', + actor=alice, + schema='User', + )['json'] + break + except Failure: + check( + time.monotonic() < deadline, + 'PostgreSQL pool did not recover within 20 seconds', + ) + time.sleep(0.5) + + check( + recovered['id'] == alice['id'], + 'existing session changed after PostgreSQL recovery', + ) + print( + 'PASS: PostgreSQL outage returned bounded 503 responses, ' + 'anonymous access stayed rejected, and the existing session recovered.' + ) + + +if __name__ == '__main__': + run(main) diff --git a/tests/explain_history.sql b/tests/explain_history.sql new file mode 100755 index 0000000..2eb7510 --- /dev/null +++ b/tests/explain_history.sql @@ -0,0 +1,114 @@ +\set ON_ERROR_STOP on +\pset pager off + +BEGIN; + +INSERT INTO users ( + id, + username, + display_name, + password_hash +) +VALUES ( + '00000000-0000-4000-8000-000000000041', + 'level4_explain_user', + 'Level 4 EXPLAIN user', + 'synthetic-not-a-login-hash' +); + +INSERT INTO chats ( + id, + title +) +VALUES ( + '00000000-0000-4000-8000-000000000042', + 'Level 4 EXPLAIN chat' +); + +INSERT INTO chat_members ( + chat_id, + user_id, + position +) +VALUES ( + '00000000-0000-4000-8000-000000000042', + '00000000-0000-4000-8000-000000000041', + 0 +); + +WITH generated AS ( + SELECT + number, + md5('level4-message-' || number::text) AS digest + FROM generate_series(1, 10000) AS series(number) +) +INSERT INTO messages ( + id, + chat_id, + sender_id, + text, + created_at +) +SELECT + ( + substr(digest, 1, 8) || '-' || + substr(digest, 9, 4) || '-4' || + substr(digest, 14, 3) || '-a' || + substr(digest, 18, 3) || '-' || + substr(digest, 21, 12) + )::uuid, + '00000000-0000-4000-8000-000000000042', + '00000000-0000-4000-8000-000000000041', + 'Synthetic history message ' || number, + TIMESTAMPTZ '2026-01-01 00:00:00+00' + + number * INTERVAL '1 microsecond' +FROM generated; + +ANALYZE messages; + +\echo 'Synthetic message count (must be 10000):' +SELECT count(*) AS synthetic_message_count +FROM messages +WHERE chat_id = '00000000-0000-4000-8000-000000000042'; + +\echo 'First page plan:' +EXPLAIN (ANALYZE, BUFFERS) +SELECT + id, + chat_id, + sender_id, + text, + created_at +FROM messages +WHERE chat_id = '00000000-0000-4000-8000-000000000042' +ORDER BY created_at, id +LIMIT 101; + +SELECT + id AS cursor_id, + created_at AS cursor_created_at +FROM messages +WHERE chat_id = '00000000-0000-4000-8000-000000000042' +ORDER BY created_at, id +OFFSET 4999 +LIMIT 1 +\gset + +\echo 'Page after cursor plan:' +EXPLAIN (ANALYZE, BUFFERS) +SELECT + id, + chat_id, + sender_id, + text, + created_at +FROM messages +WHERE chat_id = '00000000-0000-4000-8000-000000000042' + AND (created_at, id) > ( + :'cursor_created_at'::timestamptz, + :'cursor_id'::uuid + ) +ORDER BY created_at, id +LIMIT 101; + +ROLLBACK; diff --git a/tests/level4_transactions.py b/tests/level4_transactions.py new file mode 100755 index 0000000..10e9ca4 --- /dev/null +++ b/tests/level4_transactions.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Verify PostgreSQL uniqueness and atomic chat creation through the public API.""" +import base64 +from concurrent.futures import ThreadPoolExecutor +import uuid + +from client import Client, arguments, check, run + + +def register_same_user(base_url, ca_file, body): + client = Client(base_url, ca_file, timeout=15) + return client.call( + 'POST', + '/api/v1/users', + [201, 409], + body=body, + schema='User', + ) + + +def login(client, registration): + credential = base64.b64encode( + ( + registration['username'] + + ':' + + registration['password'] + ).encode() + ).decode() + session = client.call( + 'POST', + '/api/v1/auth/sessions', + 201, + headers={'Authorization': 'Basic ' + credential}, + schema='Session', + )['json'] + return { + 'id': session['user']['id'], + 'user': session['user'], + 'registration': registration, + 'token': session['token'], + } + + +def main(): + args = arguments( + 'Level 4 PostgreSQL race and transaction checks; creates synthetic data' + ) + client = Client(args.base_url, args.ca_file, timeout=15) + client.call('GET', '/health/ready', schema='Health') + + registration = { + 'username': 'race_' + uuid.uuid4().hex[:16], + 'display_name': 'Concurrent registration', + 'password': 'T3st-' + uuid.uuid4().hex, + } + + with ThreadPoolExecutor(max_workers=4) as executor: + futures = [ + executor.submit( + register_same_user, + args.base_url, + args.ca_file, + registration, + ) + for _ in range(4) + ] + results = [future.result() for future in futures] + + statuses = [result['status'] for result in results] + check( + statuses.count(201) == 1 and statuses.count(409) == 3, + 'concurrent duplicate registration must yield one 201 and three 409 responses', + ) + + actor = login(client, registration) + before = client.call( + 'GET', + '/api/v1/chats?limit=100', + actor=actor, + schema='ChatPage', + )['json'] + check(not before['items'], 'new race-test user unexpectedly has chats') + + failed_title = 'Rollback proof ' + uuid.uuid4().hex[:8] + client.call( + 'POST', + '/api/v1/chats', + 400, + actor=actor, + body={ + 'title': failed_title, + 'member_ids': [actor['id'], str(uuid.uuid4())], + }, + ) + + after = client.call( + 'GET', + '/api/v1/chats?limit=100', + actor=actor, + schema='ChatPage', + )['json'] + check( + not after['items'], + 'failed composite chat creation left visible partial data', + ) + + successful = client.call( + 'POST', + '/api/v1/chats', + 201, + actor=actor, + body={ + 'title': 'After rollback ' + uuid.uuid4().hex[:8], + 'member_ids': [actor['id']], + }, + schema='Chat', + )['json'] + check( + successful['member_ids'] == [actor['id']], + 'connection did not recover after rolled-back transaction', + ) + + print( + 'PASS: concurrent username race produced one winner; ' + 'failed composite chat creation rolled back and the connection remained usable.' + ) + + +if __name__ == '__main__': + run(main) diff --git a/tests/session_security.py b/tests/session_security.py new file mode 100755 index 0000000..3223aa6 --- /dev/null +++ b/tests/session_security.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Verify deployed short session TTL, wrong password and logout.""" +import base64 +import os +from pathlib import Path +import subprocess +import time + +from client import Client, Failure, arguments, check, run + + +def execute_hook(script, action, ttl_seconds): + env = dict(os.environ) + env['SESSION_TTL_ACTION'] = action + env['SHORT_SESSION_TTL_SECONDS'] = str(ttl_seconds) + try: + result = subprocess.run( + [str(script)], + env=env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=90, + check=False, + ) + except subprocess.TimeoutExpired: + raise Failure('session TTL hook exceeded 90 seconds') from None + check( + result.returncode == 0, + 'session TTL hook failed for action ' + action, + ) + + +def basic(username, password): + encoded = base64.b64encode((username + ':' + password).encode()).decode() + return {'Authorization': 'Basic ' + encoded} + + +def main(): + def configure(parser): + parser.add_argument( + '--action-script', + required=True, + help='Executable hook controlled by SESSION_TTL_ACTION=short|restore', + ) + parser.add_argument('--ttl-seconds', type=int, default=2) + + args = arguments( + 'Short deployed session TTL, wrong-password and logout checks', + configure, + ) + check( + 1 <= args.ttl_seconds <= 10, + 'ttl-seconds must be between 1 and 10 for this test', + ) + + script = Path(args.action_script).expanduser().resolve() + check( + script.is_file() and os.access(script, os.X_OK), + 'action script must exist and be executable (chmod +x)', + ) + + execute_hook(script, 'short', args.ttl_seconds) + try: + client = Client(args.base_url, args.ca_file, timeout=10) + actor = client.user('short_ttl') + registration = actor['registration'] + + client.call( + 'POST', + '/api/v1/auth/sessions', + 401, + headers=basic(registration['username'], 'Wrong-password-123'), + ) + client.call( + 'GET', + '/api/v1/users/me', + actor=actor, + schema='User', + ) + + time.sleep(args.ttl_seconds + 1.25) + client.call('GET', '/api/v1/users/me', 401, actor=actor) + + session = client.call( + 'POST', + '/api/v1/auth/sessions', + 201, + headers=basic( + registration['username'], + registration['password'], + ), + schema='Session', + )['json'] + fresh_actor = { + 'id': actor['id'], + 'token': session['token'], + } + client.call( + 'DELETE', + '/api/v1/auth/sessions/current', + 204, + actor=fresh_actor, + ) + client.call('GET', '/api/v1/users/me', 401, actor=fresh_actor) + finally: + execute_hook(script, 'restore', args.ttl_seconds) + + print( + 'PASS: deployed short SESSION_TTL_SECONDS expired the token; ' + 'wrong password and logout remained enforced.' + ) + + +if __name__ == '__main__': + run(main)