tasks for 4
This commit is contained in:
+14
-2
@@ -9,7 +9,19 @@ DATABASE_NAME=messenger
|
|||||||
DATABASE_USER=messenger
|
DATABASE_USER=messenger
|
||||||
DATABASE_PASSWORD=change-me-for-local-development
|
DATABASE_PASSWORD=change-me-for-local-development
|
||||||
DATABASE_URL=jdbc:postgresql://postgres:5432/messenger
|
DATABASE_URL=jdbc:postgresql://postgres:5432/messenger
|
||||||
|
DATABASE_PORT=5432
|
||||||
DATABASE_POOL_SIZE=10
|
DATABASE_POOL_SIZE=10
|
||||||
|
DATABASE_MIN_IDLE=2
|
||||||
|
DATABASE_QUERY_TIMEOUT_SECONDS=5
|
||||||
|
DATABASE_TRANSACTION_TIMEOUT_SECONDS=5
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||||
SESSION_STORE=postgres
|
REDIS_HOST=redis
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
REDIS_PORT=6379
|
||||||
|
REDIS_EXPOSED_PORT=6379
|
||||||
|
REDIS_CONNECT_TIMEOUT=1s
|
||||||
|
REDIS_COMMAND_TIMEOUT=500ms
|
||||||
|
REDIS_POOL_MAX_ACTIVE=8
|
||||||
|
REDIS_POOL_MAX_IDLE=8
|
||||||
|
REDIS_POOL_MIN_IDLE=0
|
||||||
|
REDIS_POOL_MAX_WAIT=500ms
|
||||||
|
USER_CACHE_TTL_SECONDS=300
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ CA_FILE ?=
|
|||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence
|
.PHONY: help check validate test load test-persistence test-operational explain-history
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "check/validate: contract; test: API; test-persistence: restart; test-operational: failure/race/rollback; explain-history: 10k index plan"
|
||||||
|
|
||||||
check:
|
check:
|
||||||
$(PYTHON) scripts/check_contract.py
|
$(PYTHON) scripts/check_contract.py
|
||||||
@@ -28,3 +28,9 @@ else
|
|||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||||
endif
|
endif
|
||||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
test-operational:
|
||||||
|
$(PYTHON) tests/operational.py --base-url "$(BASE_URL)"
|
||||||
|
|
||||||
|
explain-history:
|
||||||
|
$(PYTHON) scripts/explain_history.py
|
||||||
|
|||||||
@@ -1,37 +1,79 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Антипин Егор Иванович, БПИ2301
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: 4.
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: заполнить после публикации.
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Runtime: Java 23, Spring Boot 4.1.1, PostgreSQL 16.4, Redis 7.4, Python 3.11.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Требуются Docker Desktop/Compose, JDK 23 и Python 3.9+.
|
||||||
|
|
||||||
## Архитектура и решения
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
# Заменить DATABASE_PASSWORD в локальном .env; файл игнорируется Git.
|
||||||
|
docker compose --env-file .env config --quiet
|
||||||
|
docker compose --env-file .env up -d --build --wait
|
||||||
|
python3 -m pip install -r requirements-dev.txt
|
||||||
|
```
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Безопасная остановка сохраняет данные: `docker compose --env-file .env stop`.
|
||||||
|
Намеренное удаление учебных данных: `docker compose --env-file .env down -v`.
|
||||||
|
|
||||||
|
## Архитектура и источники истины
|
||||||
|
|
||||||
|
Путь запроса: клиент → Spring Security/API → PostgreSQL. Redis является необязательным
|
||||||
|
cache-aside-ускорителем чтения пользователя после проверки Bearer-сессии.
|
||||||
|
|
||||||
|
PostgreSQL — источник истины для пользователей, чатов, членства, сообщений и сессий.
|
||||||
|
Сессия хранит SHA-256-хеш opaque-токена, абсолютный `expires_at` и `revoked_at`. Каждый Bearer-запрос
|
||||||
|
сначала проверяет в PostgreSQL, что сессия существует, не отозвана и не истекла. Только после этого
|
||||||
|
пользователь берётся из Redis либо PostgreSQL. Поэтому Redis не может авторизовать отозванный токен.
|
||||||
|
|
||||||
|
Redis хранит `messenger:user:<uuid>` с TTL 300 секунд. Cache miss и недоступность Redis приводят к
|
||||||
|
чтению PostgreSQL. Повреждённая запись удаляется. API пока не содержит изменения/удаления пользователя;
|
||||||
|
при появлении такой операции ключ должен удаляться после commit. Redis настроен с AOF
|
||||||
|
`appendfsync everysec` и именованным volume, хотя корректность не зависит от сохранности кэша.
|
||||||
|
|
||||||
|
Все JDBC-значения передаются параметрами. Динамические части запросов состоят только из статических
|
||||||
|
фрагментов приложения. HikariCP ограничен 10 соединениями, JDBC-запросы/транзакции имеют таймаут
|
||||||
|
5 секунд. Lettuce pool ограничен 8 соединениями, connect timeout — 1 секунда, command/max-wait —
|
||||||
|
500 мс.
|
||||||
|
|
||||||
|
Создание чата — транзакция: INSERT чата и все INSERT членства либо фиксируются вместе, либо полностью
|
||||||
|
откатываются. Уникальность username обеспечивается PostgreSQL, поэтому работает между процессами API;
|
||||||
|
предварительный SELECT служит только быстрым путём ответа.
|
||||||
|
|
||||||
|
Подробное описание находится в `infra/database-design.md`.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий | Команда/сценарий | Наблюдаемый результат | Доказательство |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Контракт и структура | `make check`, `make validate` | PASS | stdout команд |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Публичный API | `make test` | `PASS: lab2 public API scenario` | `tests/smoke.py` |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Полный рестарт | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | сообщение и сессия сохранены | hook перезапускает `postgres redis api` без `down -v` |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Expiry/logout/password/отказы | `make test-operational` | PASS для всех сценариев | `tests/operational.py` |
|
||||||
|
| Гонка username | 12 параллельных POST одного username | один 201, остальные 409 | `tests/operational.py` |
|
||||||
|
| Rollback чата | временный trigger отклоняет участника | API 503, строки чата нет | `tests/operational.py` |
|
||||||
|
| Индекс истории | `make explain-history` | Index Scan, без Seq Scan, 10 000 строк | `evidence/message-history-explain.md` |
|
||||||
|
| Java integration tests | `gradlew test` с локальными DS env | BUILD SUCCESSFUL, 10 тестов | Gradle report |
|
||||||
|
| Secrets/volumes | `git ls-files` и ignore-файлы | приватные файлы не отслеживаются | `.gitignore`, `.dockerignore` |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
## Эксперименты отказов
|
||||||
|
|
||||||
## Эксперименты и отказы
|
| Воздействие | Ожидание | Наблюдение | Восстановление / потеря |
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Redis остановлен | cache-aside обходит кэш | Bearer `/users/me` остаётся 200 через PostgreSQL | после start кэш заполняется снова; потери нет |
|
||||||
|
| PostgreSQL остановлен | кэш не обходит проверку сессии | Bearer получает 503; анонимный запрос — 401 | соединения восстанавливаются; потери нет |
|
||||||
|
| TTL сессии 2 секунды | токен перестаёт действовать | до expiry 200, после 2.5 секунды 401 | повторный Basic login создаёт новую сессию |
|
||||||
|
| Logout | текущий токен отозван | DELETE 204, следующий запрос 401 | отзыв постоянный в PostgreSQL |
|
||||||
|
| Рестарт всех компонентов | volumes сохраняются | прежний токен и сообщение доступны | автоматическое ожидание readiness; потери нет |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
- Стенд содержит один экземпляр API; высокая доступность API не заявлена.
|
||||||
|
- Redis ускоряет чтение пользователя, но проверка сессии всегда обращается в PostgreSQL ради строгих
|
||||||
|
expiry/logout. Это осознанный компромисс корректности и производительности.
|
||||||
|
- Защита от cache stampede и измерение latency/числа SQL-запросов относятся к треку 5 и не заявлены.
|
||||||
|
- `EXPLAIN` проверяет 10 000 равномерных сообщений; набор 100 000+ относится к треку 5.
|
||||||
|
|||||||
@@ -23,11 +23,13 @@ dependencies {
|
|||||||
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
|
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
|
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
|
||||||
implementation 'org.springframework.boot:spring-boot-flyway'
|
implementation 'org.springframework.boot:spring-boot-flyway'
|
||||||
implementation 'org.flywaydb:flyway-core'
|
implementation 'org.flywaydb:flyway-core'
|
||||||
implementation 'org.flywaydb:flyway-database-postgresql'
|
implementation 'org.flywaydb:flyway-database-postgresql'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||||
implementation 'org.bouncycastle:bcprov-jdk18on:1.84'
|
implementation 'org.bouncycastle:bcprov-jdk18on:1.84'
|
||||||
|
implementation 'org.apache.commons:commons-pool2'
|
||||||
runtimeOnly 'org.postgresql:postgresql'
|
runtimeOnly 'org.postgresql:postgresql'
|
||||||
|
|
||||||
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
|
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ services:
|
|||||||
POSTGRES_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env}
|
POSTGRES_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env}
|
||||||
volumes:
|
volumes:
|
||||||
- postgres-data:/var/lib/postgresql/data
|
- postgres-data:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${DATABASE_PORT:-5432}:5432"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
@@ -14,6 +16,25 @@ services:
|
|||||||
retries: 20
|
retries: 20
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7.4-bookworm
|
||||||
|
command:
|
||||||
|
- redis-server
|
||||||
|
- --appendonly
|
||||||
|
- "yes"
|
||||||
|
- --appendfsync
|
||||||
|
- everysec
|
||||||
|
volumes:
|
||||||
|
- redis-data:/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${REDIS_EXPOSED_PORT:-6379}:6379"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
api:
|
api:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
@@ -24,12 +45,28 @@ services:
|
|||||||
DATABASE_USER: ${DATABASE_USER:-messenger}
|
DATABASE_USER: ${DATABASE_USER:-messenger}
|
||||||
DATABASE_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env}
|
DATABASE_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env}
|
||||||
DATABASE_POOL_SIZE: ${DATABASE_POOL_SIZE:-10}
|
DATABASE_POOL_SIZE: ${DATABASE_POOL_SIZE:-10}
|
||||||
|
DATABASE_MIN_IDLE: ${DATABASE_MIN_IDLE:-2}
|
||||||
|
DATABASE_QUERY_TIMEOUT_SECONDS: ${DATABASE_QUERY_TIMEOUT_SECONDS:-5}
|
||||||
|
DATABASE_TRANSACTION_TIMEOUT_SECONDS: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:-5}
|
||||||
|
REDIS_HOST: redis
|
||||||
|
REDIS_PORT: 6379
|
||||||
|
REDIS_CONNECT_TIMEOUT: ${REDIS_CONNECT_TIMEOUT:-1s}
|
||||||
|
REDIS_COMMAND_TIMEOUT: ${REDIS_COMMAND_TIMEOUT:-500ms}
|
||||||
|
REDIS_POOL_MAX_ACTIVE: ${REDIS_POOL_MAX_ACTIVE:-8}
|
||||||
|
REDIS_POOL_MAX_IDLE: ${REDIS_POOL_MAX_IDLE:-8}
|
||||||
|
REDIS_POOL_MIN_IDLE: ${REDIS_POOL_MIN_IDLE:-0}
|
||||||
|
REDIS_POOL_MAX_WAIT: ${REDIS_POOL_MAX_WAIT:-500ms}
|
||||||
|
USER_CACHE_TTL_SECONDS: ${USER_CACHE_TTL_SECONDS:-300}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres-data:
|
postgres-data:
|
||||||
|
redis-data:
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Message history index evidence
|
||||||
|
|
||||||
|
Проверка выполнена командой `make explain-history`. Скрипт `scripts/explain_message_history.sql`
|
||||||
|
создаёт 10 000 сообщений внутри транзакции, выполняет `ANALYZE` и
|
||||||
|
`EXPLAIN (ANALYZE, BUFFERS)`, после чего делает `ROLLBACK`.
|
||||||
|
|
||||||
|
Проверяемый запрос соответствует JDBC-запросу страницы истории:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = $1
|
||||||
|
AND (created_at, id) > ($2, $3)
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT 100;
|
||||||
|
```
|
||||||
|
|
||||||
|
Фактический существенный фрагмент плана:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Limit (cost=0.29..10.75 rows=100 width=74) (actual time=0.008..0.028 rows=100 loops=1)
|
||||||
|
Buffers: shared hit=6
|
||||||
|
-> Index Scan using messages_chat_created_id_idx on messages
|
||||||
|
(cost=0.29..524.11 rows=5007 width=74)
|
||||||
|
(actual time=0.007..0.021 rows=100 loops=1)
|
||||||
|
Index Cond: ((chat_id = '70000000-0000-4000-8000-000000000002'::uuid)
|
||||||
|
AND (ROW(created_at, id) > ROW(
|
||||||
|
'2026-01-01 00:00:05+00'::timestamptz,
|
||||||
|
'70000000-0000-4000-8000-000000005000'::uuid)))
|
||||||
|
Buffers: shared hit=6
|
||||||
|
Planning Time: 0.177 ms
|
||||||
|
Execution Time: 0.062 ms
|
||||||
|
```
|
||||||
|
|
||||||
|
Вывод: PostgreSQL начинает чтение с позиции курсора по индексу
|
||||||
|
`messages_chat_created_id_idx(chat_id, created_at, id)` и останавливается после 100 строк.
|
||||||
|
`Seq Scan on messages` отсутствует; стоимость страницы не требует повторного полного просмотра
|
||||||
|
10 000 предыдущих сообщений.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Модель данных PostgreSQL
|
# Модель данных PostgreSQL
|
||||||
|
|
||||||
PostgreSQL является первоисточником данных о пользователях, чатах, участниках чатов и сообщениях.
|
PostgreSQL является первоисточником данных о пользователях, чатах, участниках чатов, сообщениях и сессиях.
|
||||||
При запуске API инструмент Flyway применяет схему базы данных, описанную в файлах из директории `src/main/resources/db/migration`. Инициализация новой пустой базы данных выполняется с помощью скрипта `V1__create_messenger_schema.sql`.
|
При запуске API инструмент Flyway применяет схему базы данных, описанную в файлах из директории `src/main/resources/db/migration`. Инициализация новой пустой базы данных выполняется с помощью скрипта `V1__create_messenger_schema.sql`.
|
||||||
|
|
||||||
## Таблицы и ограничения
|
## Таблицы и ограничения
|
||||||
@@ -23,12 +23,55 @@ PostgreSQL является первоисточником данных о по
|
|||||||
|
|
||||||
Курсоры для сообщений и чатов используют тот же кортеж `(created_at, id)`, что и соответствующее предложение `ORDER BY` в запросах.
|
Курсоры для сообщений и чатов используют тот же кортеж `(created_at, id)`, что и соответствующее предложение `ORDER BY` в запросах.
|
||||||
|
|
||||||
|
Запрос страницы истории имеет вид `WHERE chat_id = ? AND (created_at, id) > (?, ?)
|
||||||
|
ORDER BY created_at, id LIMIT ?`. Все значения передаются параметрами `JdbcTemplate`, поэтому данные
|
||||||
|
пользователя не становятся частью SQL. Составной индекс `messages_chat_created_id_idx` сначала сужает
|
||||||
|
диапазон по `chat_id`, затем начинает чтение непосредственно после курсора. Проверка
|
||||||
|
`make explain-history` создаёт 10 000 сообщений внутри откатываемой транзакции и выполняет
|
||||||
|
`EXPLAIN (ANALYZE, BUFFERS)`. Проверка завершается ошибкой при отсутствии Index Scan по этому индексу
|
||||||
|
или при появлении `Seq Scan on messages`.
|
||||||
|
|
||||||
|
## Redis: роль, TTL и отказ
|
||||||
|
|
||||||
|
Redis используется как cache-aside-кэш объектов пользователей на горячем пути Bearer-аутентификации.
|
||||||
|
Он не является источником истины для сессий: перед использованием кэша API всегда параметризованным
|
||||||
|
запросом проверяет в PostgreSQL, что токен существует, не отозван и `expires_at > CURRENT_TIMESTAMP`.
|
||||||
|
Поэтому устаревшая запись Redis не может восстановить отозванную или истёкшую сессию.
|
||||||
|
|
||||||
|
Ключи имеют вид `messenger:user:<uuid>` и TTL, задаваемый `USER_CACHE_TTL_SECONDS` (по умолчанию
|
||||||
|
300 секунд). При cache miss пользователь читается из PostgreSQL и помещается в Redis. Изменения и
|
||||||
|
удаление пользователей API пока не поддерживает; при появлении таких операций соответствующий ключ
|
||||||
|
должен удаляться после успешного commit. Повреждённая запись удаляется. При таймауте или недоступности
|
||||||
|
Redis API пропускает кэш и читает PostgreSQL. Redis имеет ограниченный Lettuce pool и короткие таймауты.
|
||||||
|
В Compose также включён AOF `appendfsync everysec` и именованный volume `redis-data`, хотя потеря кэша
|
||||||
|
не влияет на корректность.
|
||||||
|
|
||||||
|
Сессии истекают по абсолютному `expires_at` в PostgreSQL. Logout атомарно заполняет `revoked_at`.
|
||||||
|
Если PostgreSQL недоступен, защищённый запрос получает ограниченный ответ `503 unavailable`; кэш не
|
||||||
|
используется для обхода проверки токена. Запрос без Bearer-токена остаётся `401` и никогда не получает
|
||||||
|
доверенную личность из `X-User-Id`.
|
||||||
|
|
||||||
|
## Пулы и таймауты
|
||||||
|
|
||||||
|
HikariCP ограничен `DATABASE_POOL_SIZE` (по умолчанию 10), имеет конечные connection/validation
|
||||||
|
timeouts, а JDBC-запросы и транзакции — таймаут 5 секунд. Lettuce pool ограничен 8 активными
|
||||||
|
соединениями, ожидание соединения и сетевые операции Redis также имеют конечные таймауты.
|
||||||
|
|
||||||
## Границы транзакций
|
## Границы транзакций
|
||||||
|
|
||||||
Создание чата выполняется в рамках одной транзакции базы данных. Сначала вставляется запись в таблицу `chats`, затем — записи для каждого участника в таблицу `chat_members`. Если возникает дубликат или отсутствует запись об участнике, вся операция откатывается (rollback); таким образом, чат никогда не будет зафиксирован в базе данных (commit) без полного набора участников.
|
Создание чата выполняется в рамках одной транзакции базы данных. Сначала вставляется запись в таблицу `chats`, затем — записи для каждого участника в таблицу `chat_members`. Если возникает дубликат или отсутствует запись об участнике, вся операция откатывается (rollback); таким образом, чат никогда не будет зафиксирован в базе данных (commit) без полного набора участников.
|
||||||
|
|
||||||
|
`make test-operational` устанавливает временный тестовый trigger, который намеренно отклоняет вставку
|
||||||
|
одного участника после вставки чата, и проверяет отсутствие строки чата после ошибки. Trigger всегда
|
||||||
|
удаляется в `finally`.
|
||||||
|
|
||||||
Создание пользователя или сообщения выполняется как атомарная транзакция, состоящая из одного SQL-оператора. Уникальность имени пользователя (username) обеспечивается на уровне базы данных с помощью ограничения `users_username_uk`; в случае одновременной попытки создания дубликата API возвращает ответ `409 Conflict`.
|
Создание пользователя или сообщения выполняется как атомарная транзакция, состоящая из одного SQL-оператора. Уникальность имени пользователя (username) обеспечивается на уровне базы данных с помощью ограничения `users_username_uk`; в случае одновременной попытки создания дубликата API возвращает ответ `409 Conflict`.
|
||||||
|
|
||||||
|
Предварительная проверка username нужна только для быстрого понятного ответа. Корректность при гонке
|
||||||
|
обеспечивает именно уникальное ограничение PostgreSQL и обработка `DuplicateKeyException`.
|
||||||
|
`make test-operational` отправляет 12 одновременных регистраций: ровно одна должна получить `201`,
|
||||||
|
остальные — `409`.
|
||||||
|
|
||||||
Создание сессии сохраняет хеш токена и срок действия одним SQL-оператором. Bearer-аутентификация выбирает только неотозванную сессию, у которой `expires_at > CURRENT_TIMESTAMP`. Logout атомарно устанавливает `revoked_at`. Сессии находятся в PostgreSQL и переживают рестарт API и PostgreSQL при сохранении именованного volume.
|
Создание сессии сохраняет хеш токена и срок действия одним SQL-оператором. Bearer-аутентификация выбирает только неотозванную сессию, у которой `expires_at > CURRENT_TIMESTAMP`. Logout атомарно устанавливает `revoked_at`. Сессии находятся в PostgreSQL и переживают рестарт API и PostgreSQL при сохранении именованного volume.
|
||||||
|
|
||||||
Операции получения списка и поиска выполняются в режиме изоляции `READ COMMITTED`. Контракт API не предусматривает использование единого снимка данных (snapshot) для нескольких HTTP-запросов в рамках постраничного вывода (пагинации).
|
Операции получения списка и поиска выполняются в режиме изоляции `READ COMMITTED`. Контракт API не предусматривает использование единого снимка данных (snapshot) для нескольких HTTP-запросов в рамках постраничного вывода (пагинации).
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Run the 10k-row message history plan probe inside a rolled-back transaction."""
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
sql = (root / 'scripts' / 'explain_message_history.sql').read_text(encoding='utf-8')
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
'docker', 'compose', '--env-file', '.env', 'exec', '-T', 'postgres',
|
||||||
|
'sh', '-lc', 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
|
||||||
|
],
|
||||||
|
cwd=root,
|
||||||
|
input=sql,
|
||||||
|
text=True,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.STDOUT,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
print(result.stdout, end='')
|
||||||
|
if result.returncode != 0:
|
||||||
|
raise SystemExit(result.returncode)
|
||||||
|
plan = result.stdout[result.stdout.find('QUERY PLAN'):]
|
||||||
|
if 'Index Scan' not in plan or 'messages_chat_created_id_idx' not in plan:
|
||||||
|
raise SystemExit('FAIL: expected messages_chat_created_id_idx index scan')
|
||||||
|
if 'Seq Scan on messages' in plan:
|
||||||
|
raise SystemExit('FAIL: message history used a sequential scan')
|
||||||
|
print('PASS: 10,000-row keyset page used messages_chat_created_id_idx without a full scan.')
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
BEGIN;
|
||||||
|
|
||||||
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||||
|
VALUES (
|
||||||
|
'70000000-0000-4000-8000-000000000001',
|
||||||
|
'explain_probe',
|
||||||
|
'EXPLAIN probe',
|
||||||
|
'$argon2id$v=19$m=16384,t=2,p=1$probe$probe',
|
||||||
|
'2026-01-01T00:00:00Z'
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO chats (id, title, created_at)
|
||||||
|
VALUES (
|
||||||
|
'70000000-0000-4000-8000-000000000002',
|
||||||
|
'EXPLAIN history probe',
|
||||||
|
'2026-01-01T00:00:00Z'
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO chat_members (chat_id, user_id)
|
||||||
|
VALUES (
|
||||||
|
'70000000-0000-4000-8000-000000000002',
|
||||||
|
'70000000-0000-4000-8000-000000000001'
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT
|
||||||
|
('70000000-0000-4000-8000-' || lpad(series::text, 12, '0'))::uuid,
|
||||||
|
'70000000-0000-4000-8000-000000000002'::uuid,
|
||||||
|
'70000000-0000-4000-8000-000000000001'::uuid,
|
||||||
|
'history probe ' || series,
|
||||||
|
'2026-01-01T00:00:00Z'::timestamptz + series * interval '1 millisecond'
|
||||||
|
FROM generate_series(1, 10000) AS series;
|
||||||
|
|
||||||
|
ANALYZE messages;
|
||||||
|
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = '70000000-0000-4000-8000-000000000002'::uuid
|
||||||
|
AND (created_at, id) > (
|
||||||
|
'2026-01-01T00:00:05Z'::timestamptz,
|
||||||
|
'70000000-0000-4000-8000-000000005000'::uuid
|
||||||
|
)
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT 100;
|
||||||
|
|
||||||
|
ROLLBACK;
|
||||||
Regular → Executable
+2
-2
@@ -2,5 +2,5 @@
|
|||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
# Restart every stateful component used by the application without deleting the
|
# Restart every stateful component used by the application without deleting the
|
||||||
# named PostgreSQL volume. The persistence test waits for readiness afterwards.
|
# named PostgreSQL/Redis volumes. The persistence test waits for readiness afterwards.
|
||||||
docker compose --env-file .env restart postgres api
|
docker compose --env-file .env restart postgres redis api
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.example.mtusi_messenger.cache;
|
||||||
|
|
||||||
|
import com.example.mtusi_messenger.model.User;
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.dao.DataAccessException;
|
||||||
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class UserCache {
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(UserCache.class);
|
||||||
|
private static final String KEY_PREFIX = "messenger:user:";
|
||||||
|
|
||||||
|
private final StringRedisTemplate redis;
|
||||||
|
private final ObjectMapper mapper;
|
||||||
|
private final Duration ttl;
|
||||||
|
|
||||||
|
public UserCache(
|
||||||
|
StringRedisTemplate redis,
|
||||||
|
ObjectMapper mapper,
|
||||||
|
@Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds
|
||||||
|
) {
|
||||||
|
if (ttlSeconds <= 0) {
|
||||||
|
throw new IllegalArgumentException("User cache TTL must be positive");
|
||||||
|
}
|
||||||
|
this.redis = redis;
|
||||||
|
this.mapper = mapper;
|
||||||
|
this.ttl = Duration.ofSeconds(ttlSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<User> find(UUID userId) {
|
||||||
|
try {
|
||||||
|
String value = redis.opsForValue().get(key(userId));
|
||||||
|
if (value == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(mapper.readValue(value, User.class));
|
||||||
|
} catch (DataAccessException e) {
|
||||||
|
log.warn("Redis user cache is unavailable; using PostgreSQL fallback");
|
||||||
|
return Optional.empty();
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
log.warn("Ignoring malformed Redis user cache entry for {}", userId);
|
||||||
|
evict(userId);
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void put(User user) {
|
||||||
|
try {
|
||||||
|
redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl);
|
||||||
|
} catch (DataAccessException e) {
|
||||||
|
log.warn("Redis user cache is unavailable; user was not cached");
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new IllegalStateException("Cannot serialize user cache entry", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void evict(UUID userId) {
|
||||||
|
try {
|
||||||
|
redis.delete(key(userId));
|
||||||
|
} catch (DataAccessException e) {
|
||||||
|
log.warn("Redis user cache is unavailable; cache eviction was skipped");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String key(UUID userId) {
|
||||||
|
return KEY_PREFIX + userId;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ public class PostgresChatRepository implements ChatRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional(timeout = 5)
|
||||||
public Chat save(Chat chat) {
|
public Chat save(Chat chat) {
|
||||||
jdbc.update("""
|
jdbc.update("""
|
||||||
INSERT INTO chats (id, title, created_at)
|
INSERT INTO chats (id, title, created_at)
|
||||||
|
|||||||
+8
-1
@@ -2,12 +2,14 @@ package com.example.mtusi_messenger.security;
|
|||||||
|
|
||||||
import com.example.mtusi_messenger.repository.UserRepository;
|
import com.example.mtusi_messenger.repository.UserRepository;
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
import org.springframework.security.authentication.AuthenticationProvider;
|
||||||
|
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||||
import org.springframework.security.authentication.BadCredentialsException;
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.AuthenticationException;
|
import org.springframework.security.core.AuthenticationException;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.dao.DataAccessException;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -27,7 +29,12 @@ public class DatabaseAuthenticationProvider implements AuthenticationProvider {
|
|||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
String username = authentication.getName();
|
String username = authentication.getName();
|
||||||
String password = String.valueOf(authentication.getCredentials());
|
String password = String.valueOf(authentication.getCredentials());
|
||||||
var stored = users.findCredentialsByUsername(username);
|
final java.util.Optional<UserRepository.UserCredentials> stored;
|
||||||
|
try {
|
||||||
|
stored = users.findCredentialsByUsername(username);
|
||||||
|
} catch (DataAccessException e) {
|
||||||
|
throw new AuthenticationServiceException("Authentication database is unavailable", e);
|
||||||
|
}
|
||||||
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
|
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
|
||||||
.filter(hash -> hash.startsWith("$argon2"))
|
.filter(hash -> hash.startsWith("$argon2"))
|
||||||
.orElse(dummyPasswordHash);
|
.orElse(dummyPasswordHash);
|
||||||
|
|||||||
+12
-3
@@ -7,6 +7,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
|||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.security.core.AuthenticationException;
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -27,11 +28,19 @@ public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
|||||||
AuthenticationException exception
|
AuthenticationException exception
|
||||||
) throws IOException {
|
) throws IOException {
|
||||||
String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE);
|
String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE);
|
||||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
boolean unavailable = exception instanceof AuthenticationServiceException;
|
||||||
|
response.setStatus(unavailable
|
||||||
|
? HttpServletResponse.SC_SERVICE_UNAVAILABLE
|
||||||
|
: HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
response.setCharacterEncoding("UTF-8");
|
response.setCharacterEncoding("UTF-8");
|
||||||
response.setHeader("WWW-Authenticate", challenge);
|
if (!unavailable) {
|
||||||
|
response.setHeader("WWW-Authenticate", challenge);
|
||||||
|
}
|
||||||
mapper.writeValue(response.getOutputStream(), new ErrorResponse(
|
mapper.writeValue(response.getOutputStream(), new ErrorResponse(
|
||||||
new ErrorResponse.ErrorBody("unauthorized", "Authentication required", requestId)));
|
new ErrorResponse.ErrorBody(
|
||||||
|
unavailable ? "unavailable" : "unauthorized",
|
||||||
|
unavailable ? "Authentication service temporarily unavailable" : "Authentication required",
|
||||||
|
requestId)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
package com.example.mtusi_messenger.service;
|
package com.example.mtusi_messenger.service;
|
||||||
|
|
||||||
|
import com.example.mtusi_messenger.cache.UserCache;
|
||||||
import com.example.mtusi_messenger.model.Session;
|
import com.example.mtusi_messenger.model.Session;
|
||||||
import com.example.mtusi_messenger.model.User;
|
import com.example.mtusi_messenger.model.User;
|
||||||
import com.example.mtusi_messenger.repository.SessionRepository;
|
import com.example.mtusi_messenger.repository.SessionRepository;
|
||||||
import com.example.mtusi_messenger.repository.UserRepository;
|
import com.example.mtusi_messenger.repository.UserRepository;
|
||||||
import com.example.mtusi_messenger.security.SessionPrincipal;
|
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.dao.DataAccessException;
|
||||||
|
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||||
import org.springframework.security.authentication.BadCredentialsException;
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -24,11 +27,13 @@ public class AuthenticationService {
|
|||||||
|
|
||||||
private final UserRepository users;
|
private final UserRepository users;
|
||||||
private final SessionRepository sessions;
|
private final SessionRepository sessions;
|
||||||
|
private final UserCache userCache;
|
||||||
private final long ttlSeconds;
|
private final long ttlSeconds;
|
||||||
|
|
||||||
public AuthenticationService(
|
public AuthenticationService(
|
||||||
UserRepository users,
|
UserRepository users,
|
||||||
SessionRepository sessions,
|
SessionRepository sessions,
|
||||||
|
UserCache userCache,
|
||||||
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
|
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
|
||||||
) {
|
) {
|
||||||
if (ttlSeconds <= 0) {
|
if (ttlSeconds <= 0) {
|
||||||
@@ -36,6 +41,7 @@ public class AuthenticationService {
|
|||||||
}
|
}
|
||||||
this.users = users;
|
this.users = users;
|
||||||
this.sessions = sessions;
|
this.sessions = sessions;
|
||||||
|
this.userCache = userCache;
|
||||||
this.ttlSeconds = ttlSeconds;
|
this.ttlSeconds = ttlSeconds;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,16 +60,28 @@ public class AuthenticationService {
|
|||||||
|
|
||||||
public SessionPrincipal authenticateBearer(String token) {
|
public SessionPrincipal authenticateBearer(String token) {
|
||||||
byte[] tokenHash = hashToken(token);
|
byte[] tokenHash = hashToken(token);
|
||||||
UUID userId = sessions.findActiveUserId(tokenHash)
|
try {
|
||||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
UUID userId = sessions.findActiveUserId(tokenHash)
|
||||||
User user = users.findById(userId)
|
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
User user = userCache.find(userId).orElseGet(() -> {
|
||||||
return new SessionPrincipal(user, tokenHash);
|
User loaded = users.findById(userId)
|
||||||
|
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||||
|
userCache.put(loaded);
|
||||||
|
return loaded;
|
||||||
|
});
|
||||||
|
return new SessionPrincipal(user, tokenHash);
|
||||||
|
} catch (DataAccessException e) {
|
||||||
|
throw new AuthenticationServiceException("Authentication database is unavailable", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void revoke(SessionPrincipal principal) {
|
public void revoke(SessionPrincipal principal) {
|
||||||
if (!sessions.revoke(principal.tokenHash())) {
|
try {
|
||||||
throw new BadCredentialsException("Invalid or expired session");
|
if (!sessions.revoke(principal.tokenHash())) {
|
||||||
|
throw new BadCredentialsException("Invalid or expired session");
|
||||||
|
}
|
||||||
|
} catch (DataAccessException e) {
|
||||||
|
throw new AuthenticationServiceException("Authentication database is unavailable", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import java.util.*;
|
|||||||
public class ChatService {
|
public class ChatService {
|
||||||
private final ChatRepository chats; private final UserService users; private final CursorService cursors;
|
private final ChatRepository chats; private final UserService users; private final CursorService cursors;
|
||||||
public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; }
|
public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; }
|
||||||
public synchronized Chat create(CreateChatRequest r, UUID caller) {
|
public Chat create(CreateChatRequest r, UUID caller) {
|
||||||
Set<UUID> ids = new LinkedHashSet<>(r.member_ids());
|
Set<UUID> ids = new LinkedHashSet<>(r.member_ids());
|
||||||
if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids");
|
if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids");
|
||||||
for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids");
|
for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids");
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ public class UserService {
|
|||||||
this.users = users;
|
this.users = users;
|
||||||
this.passwordEncoder = passwordEncoder;
|
this.passwordEncoder = passwordEncoder;
|
||||||
}
|
}
|
||||||
public synchronized User create(CreateUserRequest r) {
|
public User create(CreateUserRequest r) {
|
||||||
String username = r.username(); String display = r.display_name();
|
String username = r.username(); String display = r.display_name();
|
||||||
if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken");
|
if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken");
|
||||||
String passwordHash = passwordEncoder.encode(r.password());
|
String passwordHash = passwordEncoder.encode(r.password());
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
|||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||||
|
import org.springframework.dao.DataAccessException;
|
||||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
@@ -27,6 +28,10 @@ public class GlobalExceptionHandler {
|
|||||||
ResponseEntity<ErrorResponse> bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); }
|
ResponseEntity<ErrorResponse> bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); }
|
||||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||||
ResponseEntity<ErrorResponse> unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); }
|
ResponseEntity<ErrorResponse> unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); }
|
||||||
|
@ExceptionHandler(DataAccessException.class)
|
||||||
|
ResponseEntity<ErrorResponse> unavailable(DataAccessException e, HttpServletRequest req) {
|
||||||
|
return ResponseEntity.status(503).body(body("unavailable", "Storage temporarily unavailable", req));
|
||||||
|
}
|
||||||
@ExceptionHandler(Exception.class)
|
@ExceptionHandler(Exception.class)
|
||||||
ResponseEntity<ErrorResponse> internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); }
|
ResponseEntity<ErrorResponse> internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); }
|
||||||
private ErrorResponse body(
|
private ErrorResponse body(
|
||||||
|
|||||||
@@ -8,8 +8,31 @@ spring:
|
|||||||
password: ${DATABASE_PASSWORD:messenger}
|
password: ${DATABASE_PASSWORD:messenger}
|
||||||
hikari:
|
hikari:
|
||||||
maximum-pool-size: ${DATABASE_POOL_SIZE:10}
|
maximum-pool-size: ${DATABASE_POOL_SIZE:10}
|
||||||
|
minimum-idle: ${DATABASE_MIN_IDLE:2}
|
||||||
connection-timeout: 5000
|
connection-timeout: 5000
|
||||||
validation-timeout: 2000
|
validation-timeout: 2000
|
||||||
|
idle-timeout: 600000
|
||||||
|
max-lifetime: 1800000
|
||||||
|
|
||||||
|
data:
|
||||||
|
redis:
|
||||||
|
host: ${REDIS_HOST:localhost}
|
||||||
|
port: ${REDIS_PORT:6379}
|
||||||
|
connect-timeout: ${REDIS_CONNECT_TIMEOUT:1s}
|
||||||
|
timeout: ${REDIS_COMMAND_TIMEOUT:500ms}
|
||||||
|
lettuce:
|
||||||
|
pool:
|
||||||
|
max-active: ${REDIS_POOL_MAX_ACTIVE:8}
|
||||||
|
max-idle: ${REDIS_POOL_MAX_IDLE:8}
|
||||||
|
min-idle: ${REDIS_POOL_MIN_IDLE:0}
|
||||||
|
max-wait: ${REDIS_POOL_MAX_WAIT:500ms}
|
||||||
|
|
||||||
|
jdbc:
|
||||||
|
template:
|
||||||
|
query-timeout: ${DATABASE_QUERY_TIMEOUT_SECONDS:5}
|
||||||
|
|
||||||
|
transaction:
|
||||||
|
default-timeout: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:5}
|
||||||
|
|
||||||
flyway:
|
flyway:
|
||||||
enabled: true
|
enabled: true
|
||||||
@@ -31,3 +54,5 @@ messenger:
|
|||||||
storage: postgres
|
storage: postgres
|
||||||
session:
|
session:
|
||||||
ttl-seconds: ${SESSION_TTL_SECONDS:3600}
|
ttl-seconds: ${SESSION_TTL_SECONDS:3600}
|
||||||
|
cache:
|
||||||
|
user-ttl-seconds: ${USER_CACHE_TTL_SECONDS:300}
|
||||||
|
|||||||
@@ -0,0 +1,179 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Destructive local Compose checks for cache, outages, races, and rollback."""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
from client import Client, Failure, check, run
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args, env=None, capture=False):
|
||||||
|
result = subprocess.run(
|
||||||
|
['docker', 'compose', '--env-file', '.env', *args],
|
||||||
|
cwd=ROOT,
|
||||||
|
env=env,
|
||||||
|
check=False,
|
||||||
|
text=True,
|
||||||
|
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
check(result.returncode == 0, 'docker compose command failed: ' + ' '.join(args))
|
||||||
|
return result.stdout.strip() if capture else ''
|
||||||
|
|
||||||
|
|
||||||
|
def psql(sql, capture=False):
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
'docker', 'compose', '--env-file', '.env', 'exec', '-T', 'postgres',
|
||||||
|
'sh', '-lc', 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -At'
|
||||||
|
],
|
||||||
|
cwd=ROOT,
|
||||||
|
input=sql,
|
||||||
|
text=True,
|
||||||
|
check=False,
|
||||||
|
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
)
|
||||||
|
check(result.returncode == 0, 'PostgreSQL probe failed')
|
||||||
|
return result.stdout.strip() if capture else ''
|
||||||
|
|
||||||
|
|
||||||
|
def wait_ready(client, seconds=90):
|
||||||
|
deadline = time.monotonic() + seconds
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
client.call('GET', '/health/ready', schema='Health')
|
||||||
|
return
|
||||||
|
except Failure:
|
||||||
|
time.sleep(0.5)
|
||||||
|
raise Failure('API did not become ready')
|
||||||
|
|
||||||
|
|
||||||
|
def basic(username, password):
|
||||||
|
value = base64.b64encode((username + ':' + password).encode()).decode()
|
||||||
|
return {'Authorization': 'Basic ' + value}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import argparse
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||||
|
args = parser.parse_args()
|
||||||
|
client = Client(args.base_url)
|
||||||
|
normal_env = dict(os.environ)
|
||||||
|
normal_env.pop('SESSION_TTL_SECONDS', None)
|
||||||
|
short_env = dict(normal_env)
|
||||||
|
short_env['SESSION_TTL_SECONDS'] = '2'
|
||||||
|
trigger_installed = False
|
||||||
|
|
||||||
|
try:
|
||||||
|
compose('up', '-d', '--force-recreate', '--no-deps', '--wait', 'api', env=short_env)
|
||||||
|
expiring = client.user('expiry')
|
||||||
|
client.call('GET', '/api/v1/users/me', actor=expiring, schema='User')
|
||||||
|
time.sleep(2.5)
|
||||||
|
client.call('GET', '/api/v1/users/me', 401, actor=expiring)
|
||||||
|
|
||||||
|
compose('up', '-d', '--force-recreate', '--no-deps', '--wait', 'api', env=normal_env)
|
||||||
|
wait_ready(client)
|
||||||
|
|
||||||
|
actor = client.user('operational')
|
||||||
|
password = actor['registration']['password']
|
||||||
|
client.call(
|
||||||
|
'POST', '/api/v1/auth/sessions', 401,
|
||||||
|
headers=basic(actor['registration']['username'], password + '-wrong'))
|
||||||
|
|
||||||
|
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||||
|
cache_key = 'messenger:user:' + actor['id']
|
||||||
|
ttl = compose('exec', '-T', 'redis', 'redis-cli', 'TTL', cache_key, capture=True)
|
||||||
|
check(ttl.isdigit() and 0 < int(ttl) <= 300, 'Redis cache key has no bounded TTL')
|
||||||
|
appendonly = compose(
|
||||||
|
'exec', '-T', 'redis', 'redis-cli', '--raw', 'CONFIG', 'GET', 'appendonly',
|
||||||
|
capture=True)
|
||||||
|
check(appendonly.splitlines()[-1:] == ['yes'], 'Redis AOF persistence is disabled')
|
||||||
|
|
||||||
|
compose('stop', 'redis')
|
||||||
|
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||||
|
compose('start', 'redis')
|
||||||
|
compose('up', '-d', '--wait', 'redis')
|
||||||
|
|
||||||
|
logout_actor = client.user('logout')
|
||||||
|
client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=logout_actor)
|
||||||
|
client.call('GET', '/api/v1/users/me', 401, actor=logout_actor)
|
||||||
|
|
||||||
|
compose('stop', 'postgres')
|
||||||
|
client.call('GET', '/api/v1/users/me', 401)
|
||||||
|
client.call('GET', '/api/v1/users/me', 503, actor=actor)
|
||||||
|
compose('start', 'postgres')
|
||||||
|
compose('up', '-d', '--wait', 'postgres')
|
||||||
|
wait_ready(client)
|
||||||
|
|
||||||
|
race_name = 'race_' + uuid.uuid4().hex[:12]
|
||||||
|
race_body = {
|
||||||
|
'username': race_name,
|
||||||
|
'display_name': 'Race probe',
|
||||||
|
'password': 'correct horse battery staple',
|
||||||
|
}
|
||||||
|
|
||||||
|
def register_once(_):
|
||||||
|
local = Client(args.base_url)
|
||||||
|
return local.call('POST', '/api/v1/users', [201, 409], body=race_body)['status']
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=12) as executor:
|
||||||
|
statuses = list(executor.map(register_once, range(12)))
|
||||||
|
check(statuses.count(201) == 1, 'username race created more or less than one user')
|
||||||
|
check(statuses.count(409) == 11, 'username race did not return conflict to every loser')
|
||||||
|
|
||||||
|
owner = client.user('rollback_owner')
|
||||||
|
probe = client.user('rollback_member')
|
||||||
|
function_name = 'fail_rollback_probe'
|
||||||
|
title = 'rollback-probe-' + uuid.uuid4().hex
|
||||||
|
psql(f"""
|
||||||
|
DROP TRIGGER IF EXISTS {function_name}_trigger ON chat_members;
|
||||||
|
DROP FUNCTION IF EXISTS {function_name}();
|
||||||
|
CREATE OR REPLACE FUNCTION {function_name}() RETURNS trigger
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF NEW.user_id = '{probe['id']}'::uuid THEN
|
||||||
|
RAISE EXCEPTION 'intentional rollback probe';
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER {function_name}_trigger
|
||||||
|
BEFORE INSERT ON chat_members
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION {function_name}();
|
||||||
|
""")
|
||||||
|
trigger_installed = True
|
||||||
|
client.call(
|
||||||
|
'POST', '/api/v1/chats', 503, actor=owner,
|
||||||
|
body={'title': title, 'member_ids': [owner['id'], probe['id']]})
|
||||||
|
count = psql(
|
||||||
|
"SELECT count(*) FROM chats WHERE title = '" + title + "';",
|
||||||
|
capture=True)
|
||||||
|
check(count == '0', 'failed composite chat operation was not rolled back')
|
||||||
|
|
||||||
|
print('PASS: expiry, logout, wrong password, Redis fallback, DB failure, '
|
||||||
|
'username race, and chat rollback verified.')
|
||||||
|
finally:
|
||||||
|
compose('up', '-d', '--wait', 'postgres', 'redis')
|
||||||
|
if trigger_installed:
|
||||||
|
try:
|
||||||
|
psql(f"""
|
||||||
|
DROP TRIGGER IF EXISTS {function_name}_trigger ON chat_members;
|
||||||
|
DROP FUNCTION IF EXISTS {function_name}();
|
||||||
|
""")
|
||||||
|
except Failure:
|
||||||
|
pass
|
||||||
|
compose('up', '-d', '--force-recreate', '--wait', 'api', env=normal_env)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run(main)
|
||||||
Reference in New Issue
Block a user