forked from mtusi2026/mtusi2026lab3
Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
# Проверки авторизации после перехода на Redis
|
||||
|
||||
Актуальный профиль: сессии только в Redis; пользователи, чаты, участники и
|
||||
сообщения — PostgreSQL. Исходные tests/ и contracts/ не изменяются.
|
||||
Запуск локально и в Gitea: [RUNNING.md](RUNNING.md).
|
||||
|
||||
## Покрытие
|
||||
|
||||
| Сценарий | Тесты |
|
||||
| --- | --- |
|
||||
| Login → защищённый запрос → logout → 401; другая сессия работает | auth_contract.py normal; auth_tests/transport_test.go; storage_test.go |
|
||||
| Неверный пароль / неизвестный username; отсутствующий, неизвестный, изменённый токен | HTTP normal; storage_test.go; middleware |
|
||||
| Короткий TTL; чтение не продлевает expiry; повторный вход после истечения | auth_contract.py expiry на API TTL=2; storage_test.go; redis_test.go |
|
||||
| В Redis SHA-256 токена, положительный PTTL, исходного токена нет в ключах/значениях | storage_test.go; клиентский audit учитывает собственные SET без FLUSH |
|
||||
| Неудачный вход и запрещённый JSON body не создают сессии | storage_test.go; auth_handler_test.go; audit SET |
|
||||
| Отказ Redis при create/read/logout → 503, не 401/500 | redis_test.go; HTTP dependency с настоящей остановкой Redis |
|
||||
| Readiness 503 при отказе каждого хранилища, снова 200 после возврата; live=200 | HTTP dependency для PostgreSQL и Redis; redis_test.go |
|
||||
| Действующая сессия и прежний deadline после настоящего полного рестарта | restart_http_test.go; redis_test.go; публичный persistence; auth persistence |
|
||||
| Отозванная сессия не появляется после рестарта API/Redis | restart_http_test.go; auth persistence; Redis persistence |
|
||||
| Неуспешный WAITAOF не даёт успешный logout | redis_test.go: нулевое подтверждение, только реплика, неправильный ответ, ошибка команды |
|
||||
| Новая БД до 3; повторный up; конкурирующие миграторы; rollback SQL-ошибки | cmd/migrate/postgres_test.go |
|
||||
| Откат 3 → 2 → 1 и повтор до 3 | cmd/migrate/roundtrip_test.go; сравнение columns/types/nullability/defaults/PK/FK/CHECK/indexes |
|
||||
| Сохранность пользователей, чатов, участников и сообщений на каждом шаге миграций | roundtrip_test.go; сравнение полных строк; старая SQL-сессия после DROP не восстанавливается |
|
||||
| KDF/соль/UTF-8; единственный победитель гонки username | password_test.go; storage_test.go; HTTP normal |
|
||||
| Атомарный rollback создания чата | storage_test.go; реальный PostgreSQL |
|
||||
| Ошибки SQL сохраняют категорию до HTTP | errors_test.go: EOF, DNS, SQLSTATE, wrappers; SQL login вместо удалённых SQL-сессий |
|
||||
| Ожидание заблокированного запроса/занятого пула ограничено | budgets_test.go; реальный NewPostgres; бюджет описан в RUNNING.md |
|
||||
| История без полного scan; 10 000 сообщений | lab2/sqlprobe, suite sql-plan: настоящий запрос репозитория, первая и глубокая страницы |
|
||||
| Границы бизнес-запросов и строгие JSON/UTF-8 cases с password/Bearer | lab2/business.py → validation_edges.py; публичный smoke отдельно |
|
||||
| GET /chats и история: порядок, полный обход без потерь/дублей, чужой cursor, смена limit | lab2/business.py, business-cursors в полном verify |
|
||||
| 100 сообщений от 10 участников, read-after-write и полное совпадение истории | lab2/business.py, read-after-write; concurrency по умолчанию 4 |
|
||||
|
||||
Проверки, требующие серверов, без явных тестовых адресов получают SKIP;
|
||||
это не подтверждение работоспособности. Полный stack.py verify поднимает
|
||||
собственные контейнеры и считает SKIP ошибкой. Перезапуски/отказы выполняются
|
||||
последовательно; evidence фиксирует StartedAt, контейнеры и сохранённые volumes.
|
||||
|
||||
WAITAOF fault injection меняет только ответ этой команды через go-redis Hook;
|
||||
DEL выполняется на настоящем тестовом Redis. Отдельные интеграционные сценарии
|
||||
проверяют реальные подтверждения Redis с AOF и реальный HTTP logout.
|
||||
Тесты не повторяют logout ради успешного результата.
|
||||
|
||||
## Источники ожиданий
|
||||
|
||||
README.md (все пункты 3 и 4), COURSE.md, contracts/README.md,
|
||||
contracts/openapi.json, contracts/examples.json, contracts/infrastructure.json,
|
||||
tests/README.md, tests/client.py, tests/smoke.py, tests/resilience.py,
|
||||
MAINTAINERS.md, CONTRIBUTING.md, infra/README.md, infra/MIGRATIONS.md,
|
||||
.env.example, examples/requests.http и шаблон REPORT.md.
|
||||
Семантика подтверждения WAITAOF — дополнительное требование текущего задания
|
||||
пользователя; преподаватель требует сохранности отзыва после рестарта.
|
||||
|
||||
## История
|
||||
|
||||
[PostgreSQL auth и clean clone, 14.10](../evidence/portability-2026-10-14-d3001ea4031a/REPORT.md)
|
||||
относятся к прежнему хранилищу сессий, не доказывают состояние Redis-версии.
|
||||
Исследовательские заготовки 5: [lab2/README.md](lab2/README.md).
|
||||
**26.10.2026, строгий аудит: FAIL.** SQL timeouts/Redis/restart проходят.
|
||||
В чистом snapshot воспроизведены malformed Basic 500 вместо 401 и duplicate UUID
|
||||
в другом регистре 409 вместо 400; подробный лог в сохранённом helper отсутствует.
|
||||
Go: 41 PASS / 2 FAIL / 0 SKIP. REPORT.md автора остаётся TODO.
|
||||
[Матрица всех критериев 3+4, дефекты и свежие измерения](../evidence/grade4-strict-audit-2026-10-26/REPORT.md).
|
||||
Прежний HTTP history_deep от 25.10 был ошибочно измерен с after; он недействителен.
|
||||
Текущий генератор использует cursor и проверяет реальную глубину. SQL EXPLAIN
|
||||
≥10k оставался корректным. Серверный Gitea Actions run не подтверждён.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Собственные проверки лабораторной 2
|
||||
|
||||
Для лабораторной 3 и накопительной оценки «4» см. [lab3/README.md](lab3/README.md).
|
||||
|
||||
Актуальный стенд: API + PostgreSQL + Redis с AOF. Сессии хранятся в Redis,
|
||||
бизнес-данные — в PostgreSQL. Используется Basic → Bearer; проверки, которые
|
||||
ожидали in-memory состояние или доступ через X-User-Id, удалены. Негативные
|
||||
сценарии, подтверждающие отказ по одному X-User-Id, остаются обязательными.
|
||||
Контракт и публичные tests/ преподавателя не изменяются.
|
||||
|
||||
## Полная проверка из чистого clone
|
||||
|
||||
```sh
|
||||
python3 student-tests/check_clone.py --measure-budgets --output student-tests/output/clean-clone
|
||||
```
|
||||
|
||||
Каталог вывода выбирайте новым. Нужен работающий Docker Desktop/Engine;
|
||||
для уже загруженных базовых образов можно добавить --pull never. Проверяется
|
||||
текущий рабочий снимок, включая untracked исходники, без локальных secrets/.env.
|
||||
Это не подтверждение опубликованного remote commit.
|
||||
|
||||
Полный порядок, зависимости и Gitea CI: [RUNNING.md](RUNNING.md).
|
||||
Авторизация, Redis и миграции: [AUTH_TESTS.md](AUTH_TESTS.md).
|
||||
|
||||
## Бизнес-сценарии на уже запущенном учебном API
|
||||
|
||||
```sh
|
||||
export LAB2_BASE_URL=http://127.0.0.1:8080
|
||||
python3 student-tests/lab2/run.py \
|
||||
--suite business-boundaries --suite business-cursors --suite read-after-write
|
||||
```
|
||||
|
||||
- business-boundaries: поля, типы, кодировка UTF-8, точные имена JSON-ключей,
|
||||
границы Unicode, Content-Type и ошибки. Совместимые byte/JSON-проверки
|
||||
сохранены в validation_edges.py, регистрация требует password;
|
||||
положительный User-ответ не должен возвращать password/password_hash.
|
||||
- business-cursors: **и GET /chats, и история сообщений**. Полный обход чатов
|
||||
с limit=2, порядок (created_at,id), отсутствие потерь/повторов/чужих чатов,
|
||||
завершение next_cursor, смена limit 1 → 100, чужой cursor и плохие параметры.
|
||||
- read-after-write: 100 сообщений от 10 аутентифицированных участников;
|
||||
число параллельных запросов задаёт config.concurrency (по умолчанию 4).
|
||||
Следующее чтение видит подтверждённое сообщение; полный обход сверяет
|
||||
порядок, уникальность, содержимое и отправителей всех сообщений.
|
||||
|
||||
JSON-проверки также можно запустить отдельно:
|
||||
|
||||
```sh
|
||||
python3 student-tests/validation_edges.py --base-url http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
Tokens не выводятся; тела регистрации, содержащие пароль, не сохраняются
|
||||
в evidence, включая hex-представление. Данные синтетические; API не имеет
|
||||
удаления, поэтому используйте отдельный тестовый стенд.
|
||||
|
||||
## Измерения и дополнительные сценарии
|
||||
|
||||
В lab2/budgets.py остаётся ограниченная HTTP-матрица 1/5/10 клиентов;
|
||||
сборщик CPU/RAM находится в lab2/resources.py и не зависит от старых
|
||||
запускателей первой лабы. Методика измерений при выделении сборщика сохранена.
|
||||
SQL-планы проверяются на 10 000 сообщениях. Описания и отдельные заготовки
|
||||
исследований на 5: [lab2/README.md](lab2/README.md). Они не являются условием
|
||||
прохождения обычного stack.py verify на 4.
|
||||
|
||||
Архивные evidence прежних запусков сохраняются как история; их PASS
|
||||
не подтверждает текущую версию. Авторский REPORT.md и объяснение на защите
|
||||
автоматические тесты не заменяют.
|
||||
@@ -0,0 +1,191 @@
|
||||
# Запуск тестов лабораторной 2
|
||||
|
||||
Нужны Python 3.9+, Go версии из go.mod с поддержкой `-race` (C toolchain),
|
||||
Git, make, Docker и Docker Compose 2.24.4+ (`!override`). На macOS запусти
|
||||
Docker Desktop. В Linux пользователь должен иметь доступ к отдельному Docker
|
||||
daemon. Первой сборке нужен доступ к Python/Go/container registries.
|
||||
|
||||
## Один сценарий для локального запуска и Gitea CI
|
||||
|
||||
Из корня clone:
|
||||
|
||||
```sh
|
||||
./scripts/setup-tests.sh
|
||||
.venv/bin/python student-tests/stack.py verify
|
||||
```
|
||||
|
||||
setup-tests создаёт локальное `.venv`, устанавливает requirements-dev.txt
|
||||
и проверяет зависимости через pip check. Системный Python не изменяется.
|
||||
HTTP-тестам и инфраструктурным hooks достаточно стандартной библиотеки Python.
|
||||
Зависимости Go определяются go.mod/go.sum; загружаются обычными средствами Go
|
||||
при тестировании и сборке Docker. Пароли и внешние сервисные аккаунты не нужны.
|
||||
|
||||
verify создаёт уникальный проект `lab2-test-*`, новые синтетические secrets и
|
||||
отдельные volumes PostgreSQL и Redis. `.env` и secret-файлы генерируются во временном
|
||||
каталоге; основной `.env`/secrets разработчика не используются. Никаких заранее
|
||||
собранных образов приложения не требуется: API и migrate строятся из clone.
|
||||
Контейнеры публикуют только случайные localhost-порты.
|
||||
|
||||
Последовательно выполняются:
|
||||
|
||||
1. `make check validate`, собственные проверки тестовых инструментов.
|
||||
2. Сборка и запуск PostgreSQL, Redis с AOF, migrate и API; ожидание готовности.
|
||||
3. Отдельная сборка race-instrumented пакетов (`go test -race -run '^$' ./...`),
|
||||
затем все Go-тесты с `-race` на настоящих PostgreSQL и Redis. Сборка не
|
||||
считается прохождением тестов. Runner budget сборки — 300 с, исполнения
|
||||
Go-набора — 600 с; каждый вложенный Python acceptance-процесс под race
|
||||
получает собственные 300 с. Это суммарные budgets инструментов, не
|
||||
разрешение отдельному запросу ждать пять минут. Вложенный auth сохраняет
|
||||
клиентский timeout 15 с, рабочий SQL budget приложения остаётся 1 с;
|
||||
общий guard clean-clone runner — 1200 с с учётом установки/сборки и всех
|
||||
независимых suites. Рабочие SQL/Redis, HTTP client и operation budgets
|
||||
не увеличиваются. При runner timeout сохраняется частичный очищенный лог.
|
||||
SKIP фактического Go-прогона считается ошибкой.
|
||||
Включены миграции до 3, откат 3 → 2 → 1 → 3, структура восстановленной
|
||||
sessions и сохранность четырёх бизнес-таблиц.
|
||||
4. Публичный `make test`, 16 HTTP auth-проверок, границы бизнес-запросов и
|
||||
строгие JSON/UTF-8 cases с password/Bearer. business-cursors обходит и
|
||||
GET /chats, и историю сообщений: порядок, отсутствие потерь/повторов,
|
||||
чужой cursor и смена limit. read-after-write сверяет 100 сообщений от
|
||||
10 участников; число одновременных запросов по умолчанию 4.
|
||||
5. Публичный test-persistence с настоящим scripts/restart.sh и собственная
|
||||
проверка сохранности токенов, logout, сообщений и срока сессий после рестарта.
|
||||
6. EXPLAIN (ANALYZE, BUFFERS) реального запроса истории на 10 000 сообщениях.
|
||||
7. Поочерёдная остановка PostgreSQL и Redis: readiness=503, liveness=200,
|
||||
сессионные операции, отсутствие обхода auth и восстановление.
|
||||
8. Отдельный запуск API с TTL=2 и проверка expiry без продления при чтении.
|
||||
9. Удаление только созданных тестовым запуском контейнеров/сети/volume. Очистка
|
||||
выполняется и при ошибке; её неуспех делает общий результат FAIL.
|
||||
|
||||
Логи, summary.json и lifecycle.jsonl находятся в игнорируемом
|
||||
`student-tests/output/<время>`. Можно задать пустой каталог через `--output PATH`.
|
||||
Для подробного анализа смотри лог упавшего этапа. Секреты в артефакты не входят.
|
||||
`--pull never` допускается для офлайн-прогона, если базовые образы уже есть
|
||||
локально; обычный запуск/CI использует `--pull missing`.
|
||||
|
||||
Это профиль с Redis как единственным источником сессий. Тестовый override явно
|
||||
передаёт `SESSION_STORE=redis` и `REDIS_ADDR=redis:6379`; это конфигурация
|
||||
изолированного стенда, а не исправление `.env.example`. Обычный запуск также
|
||||
требует действительный REDIS_ADDR. PostgreSQL-sessions ожидаются только при
|
||||
откате миграции ниже версии 3.
|
||||
|
||||
Ошибки отдельных функциональных этапов сохраняются, остальные независимые
|
||||
проверки продолжаются; общий результат остаётся FAIL. Ошибка сборки/подъёма
|
||||
стенда останавливает зависимые проверки. Любой SKIP Go-тестов — FAIL.
|
||||
|
||||
`TestPostgresOperationsHaveBoundedWaits` проверяет настоящий пул приложения:
|
||||
блокировку SQL, занятые соединения, короткий deadline вызывающего кода,
|
||||
освобождение до бюджета и обслуживание после восстановления. Настройки
|
||||
statement_timeout фикстуры не наследуются. Отмена создания чата проверяется
|
||||
при заблокированном INSERT участников до COMMIT: для этой точки можно точно
|
||||
утверждать отсутствие частичных данных. Неопределённый COMMIT не подменяется
|
||||
утверждением «любой таймаут гарантирует отсутствие записи».
|
||||
|
||||
GET /users/me использует тестовый бюджет из AUTH_TEST_OPERATION_BUDGET_MS.
|
||||
Если он не задан, остаётся прежний **предварительный** бюджет 3000 мс;
|
||||
он не объявлен согласованной политикой и не задан преподавателем. Аварийная
|
||||
отмена — бюджет + 2 секунды. Приложение должно завершиться до неё самостоятельно;
|
||||
правильный HTTP 503 после аварийной отмены не делает тест успешным.
|
||||
Согласованное значение передаётся явно:
|
||||
|
||||
```sh
|
||||
.venv/bin/python student-tests/stack.py verify --operation-budget-ms 3000
|
||||
```
|
||||
|
||||
Для ограниченной таблицы задержек восьми операций добавь `--measure-budgets`.
|
||||
Это отдельный закрытый цикл 1/5/10 клиентов, 2 повтора, 3 запроса на работника
|
||||
на повтор и отдельный прогрев. История — 1000 сообщений, глубокий cursor после
|
||||
800; SQL-план на 10 000 проверяется отдельным прежним этапом. API ограничен
|
||||
2 CPU/1 GiB, PostgreSQL 1 CPU/512 MiB, Redis 0.5 CPU/256 MiB только в этом
|
||||
тестовом override. CPU/RAM измеряет существующий cgroup sampler лабораторной 1.
|
||||
Сборщик ресурсов — lab2/resources.py; зависимости от запускателей lab1 нет.
|
||||
Время HTTP не выдаётся за время SQL. Малые выборки не обосновывают стабильный
|
||||
p99 или выбор production timeout.
|
||||
|
||||
```sh
|
||||
.venv/bin/python student-tests/stack.py verify --measure-budgets --output student-tests/output/budgets
|
||||
```
|
||||
|
||||
Конкурентная диагностика Redis в существующем logout_diagnostic_test.go
|
||||
использует настоящий NewRedis и SessionRepository. Сохраняет счётчики WAITAOF,
|
||||
ошибки, время, статистику пула при 1/5/10 клиентах и отсутствие занятых соединений
|
||||
после окончания. Дополнительные CLIENT ID идут тем же закреплённым путём,
|
||||
не занимают второй слот пула; это наблюдение добавляет небольшой overhead.
|
||||
Файл diagnostics/redis-logout.json содержит сырые результаты.
|
||||
|
||||
Набор покрывает автоматизируемые критерии 3/4, но не выставляет оценку:
|
||||
обоснование индексов, архитектура, bootstrap и источник истины должны быть
|
||||
описаны в REPORT.md. Исследовательский трек 5 остаётся отдельной работой.
|
||||
|
||||
## Для чего нужен scripts/restart.sh
|
||||
|
||||
Это hook публичного теста сохранности. Он перезапускает API и PostgreSQL,
|
||||
а при наличии сервисов redis/valkey — и их. Задача migrate не перезапускается:
|
||||
это завершившаяся миграция, а не постоянно работающее хранилище.
|
||||
|
||||
Скрипт не выполняет `down -v`, очистку или заполнение БД. Он проверяет реальную
|
||||
смену StartedAt, сохранение ID контейнеров/volumes и восстановление ready.
|
||||
Подмена hook на пустой `exit 0` проверку самого hook не проходит.
|
||||
|
||||
Для ручного запуска на своём учебном стенде явно задай проект и его Compose
|
||||
файлы. Пример после создания локальных secrets/.env и запуска этого проекта:
|
||||
|
||||
```sh
|
||||
export COMPOSE_PROJECT_NAME=lab2-test-local
|
||||
export BASE_URL=http://127.0.0.1:8080
|
||||
docker compose up -d --build --wait
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
```
|
||||
|
||||
Если использован override, экспортируй COMPOSE_FILE с теми же файлами, что при
|
||||
запуске Docker. На macOS/Linux разделитель списка — `:`. Для нестандартных имён
|
||||
хранилищ задай `HL_STATE_SERVICES='postgres cache'`. Для записи доказательств
|
||||
используется `HL_LIFECYCLE_EVIDENCE=/путь/lifecycle.jsonl`. Без явного
|
||||
COMPOSE_PROJECT_NAME hook откажется выбирать проект автоматически.
|
||||
|
||||
Для отдельных сценариев отказа есть пары scripts/stop-postgres.sh /
|
||||
scripts/start-postgres.sh и scripts/stop-redis.sh / scripts/start-redis.sh. Они действуют на явно указанный проект и не удаляют
|
||||
данные. Сам verify передаёт им всё окружение автоматически.
|
||||
|
||||
## Проверка настоящего clone текущей рабочей версии
|
||||
|
||||
```sh
|
||||
python3 student-tests/check_clone.py --output student-tests/output/clean-clone
|
||||
```
|
||||
|
||||
Если базовые Docker-образы уже загружены, при проблемах с registry добавь
|
||||
`--pull never`. Инструмент берёт текущие исходники, включая ещё не добавленные
|
||||
в Git файлы, исключает локальные secrets/.env/.venv/артефакты, создаёт временный
|
||||
Git-репозиторий и выполняет настоящий `git clone --no-local`. В clone с пробелами
|
||||
и кириллицей в пути создаётся новое .venv и запускается полный verify. Проверяется
|
||||
executable bit hooks и чистота Git до/после тестов. История и индекс исходного
|
||||
репозитория не меняются. В артефактах остаётся manifest SHA-256 файлов снимка.
|
||||
|
||||
Это проверка переносимости текущей рабочей версии. Remote fork получит её
|
||||
только после обычного commit/push пользователя. Артефакты, private-файлы и
|
||||
локальное окружение коммитить не нужно. После коммита переносимость remote
|
||||
проверяется теми же двумя командами setup-tests/verify в свежем clone.
|
||||
|
||||
## Gitea Actions
|
||||
|
||||
Workflow находится в `.gitea/workflows/application.yml`; он запускается на push
|
||||
и pull_request. Существующий GitHub skeleton workflow не меняется.
|
||||
Используются абсолютные URLs actions: это поддерживаемый синтаксис Gitea,
|
||||
а не указание запускать CI на GitHub.
|
||||
|
||||
На сервере Gitea должны быть включены Actions и зарегистрирован runner с label
|
||||
`lab2-isolated-docker`: отдельная одноразовая VM на job, Docker/Compose, make,
|
||||
Git и C toolchain. Node нужен checkout/setup actions; Go и Python ставятся
|
||||
через setup actions. Для host executor на такой VM регистрационная метка —
|
||||
`lab2-isolated-docker:host`; `runs-on` использует часть до `:host`.
|
||||
Нельзя подменять эту инфраструктуру доступом к общему
|
||||
Docker-host для кода из PR — это прямо запрещено CONTRIBUTING.md. Workflow
|
||||
не использует пользовательские secrets и не публикует приложение.
|
||||
|
||||
После checkout CI вызывает те же setup-tests.sh и stack.py verify; итоговый
|
||||
sanitized summary печатается в лог job. Серверный зелёный запуск можно считать
|
||||
подтверждённым только по реальному результату Actions после push. Локальный
|
||||
PASS сценария не означает, что runner Gitea уже настроен.
|
||||
|
||||
Документация платформы: [Actions quick start](https://docs.gitea.com/usage/actions/quickstart/),
|
||||
[абсолютные action URLs](https://docs.gitea.com/usage/actions/comparison/).
|
||||
@@ -0,0 +1,538 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab2 auth acceptance tests. Uses the unchanged teacher HTTP client.
|
||||
|
||||
No server startup, automatic Docker actions, retries of writes or secret output.
|
||||
Infrastructure hooks run only in explicitly selected suites.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, LAB, check, timestamp # noqa: E402
|
||||
|
||||
LOGIN = "/api/v1/auth/sessions"
|
||||
LOGOUT = LOGIN + "/current"
|
||||
ME = "/api/v1/users/me"
|
||||
ARGS = None
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
value = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + value}
|
||||
|
||||
|
||||
def registration(password=None):
|
||||
return {
|
||||
"username": "auth_" + uuid.uuid4().hex[:20],
|
||||
"display_name": "Проверка auth",
|
||||
"password": password if password is not None else "Aa:" + uuid.uuid4().hex,
|
||||
}
|
||||
|
||||
|
||||
def new_client(timeout=None):
|
||||
return Client(ARGS.base_url, ARGS.ca_file, timeout=timeout or ARGS.timeout)
|
||||
|
||||
|
||||
def error(c, method, path, status, code, **kwargs):
|
||||
if LAB >= 3 and method == "POST" and path.endswith("/messages"):
|
||||
kwargs["headers"] = {**kwargs.get("headers", {}), "Idempotency-Key": uuid.uuid4().hex}
|
||||
response = c.call(method, path, status, **kwargs)
|
||||
check(response["json"]["error"]["code"] == code, "incorrect contract error code")
|
||||
if status == 401:
|
||||
challenge = ('Basic realm="messenger", charset="UTF-8"'
|
||||
if path == LOGIN else 'Bearer realm="messenger"')
|
||||
check(response["headers"].get("WWW-Authenticate") == challenge,
|
||||
"incorrect authentication challenge")
|
||||
return response
|
||||
|
||||
|
||||
def create_actor(c, password=None):
|
||||
body = registration(password)
|
||||
user = c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
session = c.call("POST", LOGIN, 201,
|
||||
headers=basic(body["username"], body["password"]), schema="Session")["json"]
|
||||
check(session["user"] == user, "login returned a different user")
|
||||
check(timestamp(session["expires_at"]) > dt.datetime.now(dt.timezone.utc),
|
||||
"new session is already expired")
|
||||
return {"id": user["id"], "user": user, "registration": body,
|
||||
"token": session["token"], "expires_at": session["expires_at"]}
|
||||
|
||||
|
||||
def login(c, actor):
|
||||
return c.call("POST", LOGIN, 201, schema="Session",
|
||||
headers=basic(actor["registration"]["username"],
|
||||
actor["registration"]["password"]))["json"]
|
||||
|
||||
|
||||
def chat(c, owner, members=None):
|
||||
members = members if members is not None else [owner["id"]]
|
||||
return c.call("POST", "/api/v1/chats", 201, actor=owner,
|
||||
body={"title": "Auth regression", "member_ids": members}, schema="Chat")["json"]
|
||||
|
||||
|
||||
class AuthContract(unittest.TestCase):
|
||||
"""Independent cases: a logout or rejection never poisons another test."""
|
||||
|
||||
def setUp(self):
|
||||
self.c = new_client()
|
||||
|
||||
def test_public_health_and_registration(self):
|
||||
for path in ("/health/live", "/health/ready"):
|
||||
with self.subTest(path=path):
|
||||
self.c.call("GET", path, schema="Health")
|
||||
body = registration()
|
||||
# Registration is public even when a stale credential is supplied.
|
||||
user = self.c.call("POST", "/api/v1/users", 201, body=body,
|
||||
headers={"Authorization": "Bearer invalid"}, schema="User")["json"]
|
||||
check(user["username"] == body["username"], "username changed")
|
||||
check(user["display_name"] == body["display_name"], "display_name changed")
|
||||
|
||||
def test_password_unicode_boundaries_and_colon(self):
|
||||
for label, password in (
|
||||
("ascii_min", "a" * 12), ("ascii_max", "b" * 128),
|
||||
("unicode_min", "😀" * 12), ("unicode_max", "😀" * 128),
|
||||
("colon", "начало:пароль:конец"),
|
||||
("spaces_are_significant", " significant-password "),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
actor = create_actor(self.c, password)
|
||||
me = self.c.call("GET", ME, actor=actor, schema="User")["json"]
|
||||
check(me == actor["user"], "current user differs from registration")
|
||||
altered = password.strip() if password != password.strip() else password + "x"
|
||||
error(self.c, "POST", LOGIN, 401, "unauthorized",
|
||||
headers=basic(actor["registration"]["username"], altered))
|
||||
|
||||
def test_invalid_password_length_and_blank(self):
|
||||
for label, value in (
|
||||
("empty", ""), ("ascii_short", "a" * 11), ("ascii_long", "a" * 129),
|
||||
("unicode_short", "😀" * 11), ("unicode_long", "😀" * 129),
|
||||
("blank_ascii", " " * 12), ("blank_unicode", "\u2003" * 12),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
body = registration(value)
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
|
||||
def test_registration_required_fields_types_and_names(self):
|
||||
for field in ("username", "display_name", "password"):
|
||||
for label, value in (("missing", None), ("null", None), ("integer", 1),
|
||||
("boolean", True), ("array", []), ("object", {})):
|
||||
with self.subTest(field=field, case=label):
|
||||
body = registration()
|
||||
if label == "missing":
|
||||
body.pop(field)
|
||||
else:
|
||||
body[field] = value
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
for alias in (field.upper(), field[0].upper() + field[1:]):
|
||||
for extra in (False, True):
|
||||
with self.subTest(field=field, alias=alias, extra=extra):
|
||||
body = registration()
|
||||
body[alias] = body[field] if extra else body.pop(field)
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
for root in (None, True, 1, "string", []):
|
||||
with self.subTest(root_type=type(root).__name__):
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
|
||||
raw=json.dumps(root).encode(), headers={"Content-Type": "application/json"})
|
||||
body = registration()
|
||||
body["sender_id"] = str(uuid.uuid4())
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
|
||||
def test_registration_bytes_json_and_content_type(self):
|
||||
for label, raw in (
|
||||
("empty", b""), ("malformed", b'{"username":'),
|
||||
("second_json", json.dumps(registration()).encode() + b"{}"),
|
||||
("trailing_garbage", json.dumps(registration()).encode() + b" garbage"),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
|
||||
raw=raw, headers={"Content-Type": "application/json"})
|
||||
for field in ("username", "display_name", "password"):
|
||||
for label, bad in (("ff", b"\xff"), ("overlong", b"\xc0\xaf"),
|
||||
("truncated", b"\xe2\x82"), ("surrogate", b"\xed\xa0\x80")):
|
||||
with self.subTest(field=field, encoding=label):
|
||||
body = registration()
|
||||
body[field] = "BYTE_MARKER"
|
||||
raw = json.dumps(body).encode().replace(b"BYTE_MARKER", b"prefix" + bad + b"suffix")
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
|
||||
raw=raw, headers={"Content-Type": "application/json"})
|
||||
for media in ("text/plain", "application/octet-stream"):
|
||||
with self.subTest(media=media):
|
||||
error(self.c, "POST", "/api/v1/users", 415, "unsupported_media_type",
|
||||
raw=json.dumps(registration()).encode(), headers={"Content-Type": media})
|
||||
|
||||
def test_username_and_display_name_constraints(self):
|
||||
for username in ("ab", "a" * 33, "ABC", "имя", "bad-name", "bad name", " bad"):
|
||||
with self.subTest(case="username", length=len(username)):
|
||||
body = registration()
|
||||
body["username"] = username
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
for name in ("", " \t\n", "\u00a0\u2003", "😀" * 101):
|
||||
with self.subTest(case="display_name", length=len(name)):
|
||||
body = registration()
|
||||
body["display_name"] = name
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
for length in (1, 100):
|
||||
with self.subTest(case="valid_display_name", length=length):
|
||||
body = registration()
|
||||
body["display_name"] = "😀" * length
|
||||
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
check(user["display_name"] == body["display_name"], "Unicode display name changed")
|
||||
body = registration()
|
||||
body["username"] = uuid.uuid4().hex
|
||||
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
check(user["username"] == body["username"], "maximum-length username changed")
|
||||
|
||||
def test_wrong_credentials_have_same_public_error(self):
|
||||
actor = create_actor(self.c)
|
||||
responses = []
|
||||
for label, username, password in (
|
||||
("wrong_password", actor["registration"]["username"], "wrong-password"),
|
||||
("unknown_user", registration()["username"], actor["registration"]["password"]),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
responses.append(error(self.c, "POST", LOGIN, 401, "unauthorized",
|
||||
headers=basic(username, password)))
|
||||
if len(responses) == 2:
|
||||
check(responses[0]["json"]["error"]["message"] ==
|
||||
responses[1]["json"]["error"]["message"],
|
||||
"credentials errors reveal whether username exists")
|
||||
self.c.call("GET", ME, actor=actor, schema="User")
|
||||
|
||||
def test_login_rejects_missing_or_malformed_basic(self):
|
||||
actor = create_actor(self.c)
|
||||
encoded_no_colon = base64.b64encode(b"username-only").decode()
|
||||
for label, headers in (
|
||||
("absent", {}), ("legacy_id", {"X-User-Id": actor["id"]}),
|
||||
("bearer", {"Authorization": "Bearer " + actor["token"]}),
|
||||
("empty_basic", {"Authorization": "Basic"}),
|
||||
("invalid_base64", {"Authorization": "Basic !!!"}),
|
||||
("missing_separator", {"Authorization": "Basic " + encoded_no_colon}),
|
||||
("invalid_username_utf8", {"Authorization": "Basic " + base64.b64encode(b"\xffuser:synthetic-password").decode("ascii")}),
|
||||
("username_contains_nul", {"Authorization": "Basic " + base64.b64encode(b"bad\x00user:synthetic-password").decode("ascii")}),
|
||||
("wrong_scheme", {"Authorization": "Digest anything"}),
|
||||
("empty_password", basic(actor["registration"]["username"], "")),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
error(self.c, "POST", LOGIN, 401, "unauthorized", headers=headers)
|
||||
|
||||
def test_login_does_not_accept_json_credentials(self):
|
||||
actor = create_actor(self.c)
|
||||
body = {"username": actor["registration"]["username"],
|
||||
"password": actor["registration"]["password"]}
|
||||
# Authentication precedes payload validation.
|
||||
error(self.c, "POST", LOGIN, 401, "unauthorized", body=body)
|
||||
error(self.c, "POST", LOGIN, 400, "invalid_request", body=body,
|
||||
headers=basic(body["username"], body["password"]))
|
||||
|
||||
def test_protected_routes_require_bearer_before_validation(self):
|
||||
actor = create_actor(self.c)
|
||||
basic_headers = basic(actor["registration"]["username"], actor["registration"]["password"])
|
||||
unknown = str(uuid.uuid4())
|
||||
routes = (
|
||||
("GET", ME, None), ("GET", "/api/v1/chats", None),
|
||||
("POST", "/api/v1/chats", {"title": "", "member_ids": []}),
|
||||
("GET", "/api/v1/chats/" + unknown, None),
|
||||
("GET", "/api/v1/chats/not-a-uuid/messages?limit=0", None),
|
||||
("POST", "/api/v1/chats/" + unknown + "/messages", {"text": ""}),
|
||||
("DELETE", LOGOUT, None),
|
||||
)
|
||||
for method, path, body in routes:
|
||||
for label, headers in (
|
||||
("absent", {}), ("basic", basic_headers), ("legacy_id", {"X-User-Id": actor["id"]}),
|
||||
("empty_bearer", {"Authorization": "Bearer"}),
|
||||
("unknown_token", {"Authorization": "Bearer " + uuid.uuid4().hex * 2}),
|
||||
("space_in_token", {"Authorization": "Bearer invalid token"}),
|
||||
):
|
||||
with self.subTest(method=method, path=path, auth=label):
|
||||
error(self.c, method, path, 401, "unauthorized", body=body, headers=headers)
|
||||
|
||||
def test_identity_acl_and_sender_ignore_legacy_header(self):
|
||||
alice, bob, eve = (create_actor(self.c) for _ in range(3))
|
||||
room = chat(self.c, alice, [alice["id"], bob["id"]])
|
||||
path = "/api/v1/chats/" + room["id"]
|
||||
me = self.c.call("GET", ME, actor=alice, headers={"X-User-Id": eve["id"]},
|
||||
schema="User")["json"]
|
||||
check(me == alice["user"], "legacy ID overrode session identity")
|
||||
result = self.c.call("POST", path + "/messages", 201, actor=alice,
|
||||
headers={"X-User-Id": bob["id"],
|
||||
**({"Idempotency-Key": uuid.uuid4().hex} if LAB >= 3 else {})},
|
||||
body={"text": "Auth sender"}, schema="Message")["json"]
|
||||
check(result["sender_id"] == alice["id"], "sender not derived from session")
|
||||
for suffix in ("", "/messages"):
|
||||
error(self.c, "GET", path + suffix, 404, "not_found", actor=eve,
|
||||
headers={"X-User-Id": alice["id"]})
|
||||
error(self.c, "POST", path + "/messages", 404, "not_found", actor=eve,
|
||||
body={"text": "Forbidden"}, headers={"X-User-Id": alice["id"]})
|
||||
hidden = self.c.call("GET", "/api/v1/chats?limit=100", actor=eve,
|
||||
schema="ChatPage")["json"]
|
||||
check(all(item["id"] != room["id"] for item in hidden["items"]), "foreign chat leaked")
|
||||
page = self.c.call("GET", path + "/messages", actor=bob, schema="MessagePage")["json"]
|
||||
check(page["items"] == [result], "confirmed message is not immediately visible")
|
||||
error(self.c, "POST", path + "/messages", 400, "invalid_request", actor=alice,
|
||||
body={"text": "Forged sender", "sender_id": bob["id"]})
|
||||
|
||||
def test_invalid_chat_does_not_leave_visible_partial_chat(self):
|
||||
actor = create_actor(self.c)
|
||||
before = self.c.call("GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage")["json"]
|
||||
for members in ([actor["id"], str(uuid.uuid4())],
|
||||
[actor["id"], actor["id"]],
|
||||
[actor["id"], actor["id"].upper()], [str(uuid.uuid4())]):
|
||||
with self.subTest(member_count=len(members)):
|
||||
error(self.c, "POST", "/api/v1/chats", 400, "invalid_request", actor=actor,
|
||||
body={"title": "Must not exist", "member_ids": members})
|
||||
after = self.c.call("GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage")["json"]
|
||||
check(after == before, "rejected chat request left visible partial data")
|
||||
|
||||
def test_logout_revokes_only_current_session(self):
|
||||
actor = create_actor(self.c)
|
||||
other = login(self.c, actor)
|
||||
check(other["token"] != actor["token"], "separate logins reused a token")
|
||||
self.c.call("DELETE", LOGOUT, 204, actor=actor)
|
||||
error(self.c, "GET", ME, 401, "unauthorized", actor=actor)
|
||||
error(self.c, "DELETE", LOGOUT, 401, "unauthorized", actor=actor)
|
||||
second = dict(actor, token=other["token"])
|
||||
me = self.c.call("GET", ME, actor=second, schema="User")["json"]
|
||||
check(me == actor["user"], "logout revoked another session")
|
||||
fresh = login(self.c, actor)
|
||||
check(fresh["token"] not in (actor["token"], other["token"]), "login reused an earlier token")
|
||||
self.c.call("GET", ME, actor=dict(actor, token=fresh["token"]), schema="User")
|
||||
|
||||
def test_session_ttl_matches_configuration(self):
|
||||
actor = create_actor(self.c)
|
||||
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
check(ARGS.ttl - 5 <= remaining <= ARGS.ttl + 5, "SESSION_TTL_SECONDS not respected")
|
||||
for _ in range(3):
|
||||
self.c.call("GET", ME, actor=actor, schema="User")
|
||||
# Exact non-sliding deadline is checked by the storage and short-TTL suites.
|
||||
|
||||
def test_tokens_distinct_opaque_and_tamper_rejected(self):
|
||||
actor = create_actor(self.c)
|
||||
issued = [actor["token"]] + [login(self.c, actor)["token"] for _ in range(3)]
|
||||
check(len(set(issued)) == len(issued), "independent logins reused tokens")
|
||||
for token in issued:
|
||||
check(token != actor["id"] and token != actor["registration"]["username"],
|
||||
"token contains identity instead of an opaque credential")
|
||||
check(token != actor["registration"]["password"], "password used as session token")
|
||||
token = actor["token"]
|
||||
changed = token[:-1] + ("A" if token[-1] != "A" else "B")
|
||||
error(self.c, "GET", ME, 401, "unauthorized", actor=dict(actor, token=changed))
|
||||
self.c.call("GET", ME, actor=actor, schema="User")
|
||||
# Length/uniqueness is not proof of entropy. RNG is reviewed separately.
|
||||
|
||||
def test_duplicate_username_concurrent_registration(self):
|
||||
body = registration()
|
||||
barrier = threading.Barrier(4)
|
||||
|
||||
def send(index):
|
||||
c = new_client()
|
||||
candidate = dict(body, display_name="Race " + str(index), password=body["password"] + str(index))
|
||||
barrier.wait(timeout=ARGS.timeout)
|
||||
result = c.call("POST", "/api/v1/users", (201, 409), body=candidate, schema="User")
|
||||
if result["status"] == 409:
|
||||
check(result["json"]["error"]["code"] == "conflict", "race loser did not receive conflict")
|
||||
return candidate, result
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(send, range(4)))
|
||||
winners = [(body, result) for body, result in results if result["status"] == 201]
|
||||
check(len(winners) == 1, "username race must have exactly one winner")
|
||||
winner_body, result = winners[0]
|
||||
session = self.c.call("POST", LOGIN, 201, headers=basic(winner_body["username"],
|
||||
winner_body["password"]), schema="Session")["json"]
|
||||
check(session["user"] == result["json"], "race winner was overwritten")
|
||||
for candidate, response in results:
|
||||
if response["status"] == 409:
|
||||
error(self.c, "POST", LOGIN, 401, "unauthorized",
|
||||
headers=basic(candidate["username"], candidate["password"]))
|
||||
|
||||
|
||||
def hook(path):
|
||||
script = Path(path).expanduser().resolve()
|
||||
check(script.is_file() and os.access(script, os.X_OK), "hook must exist and be executable")
|
||||
check(".example." not in script.name, "implement a real hook first")
|
||||
try:
|
||||
result = subprocess.run([str(script)], stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, timeout=ARGS.hook_timeout)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
raise Failure("infrastructure hook failed or timed out; inspect it locally") from None
|
||||
check(result.returncode == 0, "infrastructure hook returned an error")
|
||||
|
||||
|
||||
def wait_ready(c):
|
||||
deadline = time.monotonic() + ARGS.hook_timeout
|
||||
while True:
|
||||
try:
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "API readiness did not recover")
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def expiry():
|
||||
c = new_client()
|
||||
actor = create_actor(c)
|
||||
start = time.monotonic()
|
||||
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
check(0 < remaining <= ARGS.ttl + 5, "short TTL not applied")
|
||||
c.call("GET", ME, actor=actor, schema="User")
|
||||
# Reading halfway must not renew the original deadline.
|
||||
time.sleep(max(0, remaining / 2))
|
||||
c.call("GET", ME, actor=actor, schema="User")
|
||||
time.sleep(max(0, remaining + 0.25 - (time.monotonic() - start)))
|
||||
error(c, "GET", ME, 401, "unauthorized", actor=actor)
|
||||
error(c, "DELETE", LOGOUT, 401, "unauthorized", actor=actor)
|
||||
fresh = login(c, actor)
|
||||
check(fresh["token"] != actor["token"], "expired token reused")
|
||||
c.call("GET", ME, actor=dict(actor, token=fresh["token"]), schema="User")
|
||||
|
||||
|
||||
def persistence():
|
||||
c = new_client(timeout=2)
|
||||
actor = create_actor(c)
|
||||
revoked = dict(actor, token=login(c, actor)["token"])
|
||||
c.call("DELETE", LOGOUT, 204, actor=revoked)
|
||||
room = chat(c, actor)
|
||||
original = c.message(actor, room, "Auth persistence")["json"]
|
||||
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
check(remaining > 2 * ARGS.hook_timeout + 10, "TTL too short for restart bounds")
|
||||
hook(ARGS.restart_hook)
|
||||
wait_ready(c)
|
||||
# No re-login before checking the original token.
|
||||
check(c.call("GET", ME, actor=actor, schema="User")["json"] == actor["user"],
|
||||
"original session/user did not survive restart")
|
||||
check(c.call("GET", "/api/v1/chats/" + room["id"], actor=actor, schema="Chat")["json"] == room,
|
||||
"chat/membership changed after restart")
|
||||
page = c.call("GET", "/api/v1/chats/" + room["id"] + "/messages",
|
||||
actor=actor, schema="MessagePage")["json"]
|
||||
check(page["items"] == [original], "confirmed message changed after restart")
|
||||
error(c, "GET", ME, 401, "unauthorized", actor=revoked)
|
||||
error(c, "DELETE", LOGOUT, 401, "unauthorized", actor=revoked)
|
||||
c.call("DELETE", LOGOUT, 204, actor=actor)
|
||||
error(c, "GET", ME, 401, "unauthorized", actor=actor)
|
||||
check(login(c, actor)["user"] == actor["user"], "password/user not persistent")
|
||||
# HTTP exposes expiry only at login. Storage test verifies deadline stability.
|
||||
|
||||
|
||||
def dependency():
|
||||
c = new_client()
|
||||
actor = create_actor(c)
|
||||
failures = []
|
||||
fallback_session = None
|
||||
revoked_during_outage = False
|
||||
sql_with_redis = ARGS.dependency == "postgres" and getattr(ARGS, "session_store", "redis") == "redis"
|
||||
if sql_with_redis:
|
||||
fallback_session = dict(actor, token=login(c, actor)["token"])
|
||||
|
||||
def observe(name, operation):
|
||||
try:
|
||||
operation()
|
||||
print("PASS:", name)
|
||||
return True
|
||||
except Failure as exc:
|
||||
failures.append(name + ": " + str(exc))
|
||||
print("FAIL:", name + ": " + str(exc))
|
||||
return False
|
||||
|
||||
try:
|
||||
hook(ARGS.failure_hook)
|
||||
observe("liveness during outage", lambda: c.call("GET", "/health/live", schema="Health"))
|
||||
critical = not (ARGS.dependency == "redis" and ARGS.cache_policy == "fallback")
|
||||
if critical:
|
||||
observe("readiness during outage", lambda: error(c, "GET", "/health/ready", 503, "unavailable"))
|
||||
observe("valid session during outage", lambda: error(c, "GET", ME, 503, "unavailable", actor=actor))
|
||||
else:
|
||||
observe("fallback readiness", lambda: c.call("GET", "/health/ready", schema="Health"))
|
||||
observe("fallback identity", lambda: c.call("GET", ME, actor=actor, schema="User"))
|
||||
for name, headers in (("missing auth", {}), ("legacy identity", {"X-User-Id": actor["id"]})):
|
||||
observe(name, lambda headers=headers: error(c, "GET", ME, 401, "unauthorized", headers=headers))
|
||||
# A syntactically valid Bearer cannot be declared unknown while the
|
||||
# sole session store is unavailable. The lookup failed, not identity.
|
||||
unknown_status = 503 if ARGS.dependency == "redis" and critical else 401
|
||||
observe("unknown bearer during outage", lambda: error(c, "GET", ME, unknown_status,
|
||||
"unavailable" if unknown_status == 503 else "unauthorized",
|
||||
headers={"Authorization": "Bearer " + uuid.uuid4().hex * 2}))
|
||||
if critical:
|
||||
observe("login during outage", lambda: error(c, "POST", LOGIN, 503, "unavailable",
|
||||
headers=basic(actor["registration"]["username"], actor["registration"]["password"])))
|
||||
if not critical:
|
||||
fallback_session = dict(actor, token=login(c, actor)["token"])
|
||||
if sql_with_redis or not critical:
|
||||
revoked_during_outage = observe("Redis logout independent of SQL", lambda: c.call("DELETE", LOGOUT, 204, actor=actor))
|
||||
else:
|
||||
observe("logout during outage", lambda: error(c, "DELETE", LOGOUT, 503, "unavailable", actor=actor))
|
||||
if ARGS.dependency == "postgres":
|
||||
body = registration()
|
||||
observe("registration during SQL outage", lambda: error(c, "POST", "/api/v1/users", 503, "unavailable", body=body))
|
||||
finally:
|
||||
hook(ARGS.recovery_hook)
|
||||
observe("readiness recovers", lambda: wait_ready(c))
|
||||
observe("liveness recovers", lambda: c.call("GET", "/health/live", schema="Health"))
|
||||
survivor = fallback_session or actor
|
||||
observe("independent session after recovery", lambda: c.call("GET", ME, actor=survivor, schema="User"))
|
||||
if revoked_during_outage:
|
||||
observe("logout remains revoked after recovery", lambda: error(c, "GET", ME, 401, "unauthorized", actor=actor))
|
||||
if ARGS.dependency == "postgres":
|
||||
observe("failed registration left no user", lambda: c.call("POST", "/api/v1/users", 201, body=body, schema="User"))
|
||||
check(not failures, "; ".join(failures))
|
||||
|
||||
|
||||
def main():
|
||||
global ARGS
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--ca-file", default=None)
|
||||
p.add_argument("--timeout", type=float, default=15)
|
||||
p.add_argument("--ttl", type=int, default=3600, help="actual server SESSION_TTL_SECONDS")
|
||||
p.add_argument("--suite", choices=("normal", "expiry", "persistence", "dependency"), default="normal")
|
||||
p.add_argument("--restart-hook")
|
||||
p.add_argument("--failure-hook")
|
||||
p.add_argument("--recovery-hook")
|
||||
p.add_argument("--dependency", choices=("postgres", "redis"))
|
||||
p.add_argument("--cache-policy", choices=("critical", "fallback"))
|
||||
p.add_argument("--session-store", choices=("postgres", "redis"), default="redis",
|
||||
help="declared session backend; controls logout expectation during a SQL outage")
|
||||
p.add_argument("--hook-timeout", type=float, default=90)
|
||||
ARGS = p.parse_args()
|
||||
if LAB not in (2, 3):
|
||||
p.error("this suite targets the lab2 auth contract retained in lab3")
|
||||
if ARGS.timeout <= 0 or ARGS.hook_timeout <= 0:
|
||||
p.error("timeouts must be positive")
|
||||
if ARGS.suite == "expiry":
|
||||
if not 2 <= ARGS.ttl <= 10:
|
||||
p.error("expiry needs a separately configured server with TTL 2..10")
|
||||
elif ARGS.ttl < 300:
|
||||
p.error("normal, restart and dependency suites require TTL >= 300")
|
||||
if ARGS.suite == "persistence" and not ARGS.restart_hook:
|
||||
p.error("persistence requires an explicit --restart-hook")
|
||||
if ARGS.suite == "dependency":
|
||||
if not (ARGS.failure_hook and ARGS.recovery_hook and ARGS.dependency):
|
||||
p.error("dependency suite needs failure/recovery hooks and the dependency name")
|
||||
if ARGS.dependency == "redis" and not ARGS.cache_policy:
|
||||
p.error("declare whether Redis is critical or has a safe fallback")
|
||||
if ARGS.suite == "normal":
|
||||
result = unittest.TextTestRunner(verbosity=2).run(
|
||||
unittest.defaultTestLoader.loadTestsFromTestCase(AuthContract))
|
||||
raise SystemExit(0 if result.wasSuccessful() else 1)
|
||||
try:
|
||||
{"expiry": expiry, "persistence": persistence, "dependency": dependency}[ARGS.suite]()
|
||||
except (Failure, ValueError, OSError) as exc:
|
||||
print("FAIL:", str(exc))
|
||||
raise SystemExit(1)
|
||||
print("PASS:", ARGS.suite, "(hook scope and runtime settings need separate evidence)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,32 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func TestStorageAuthHandlerRejectsJSONBody(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
writes := f.redis.audit.writeCount()
|
||||
auth := handler.NewAuthHandler(f.auth)
|
||||
mid := middleware.NewMiddleware(f.auth, "auth-test")
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
request.SetBasicAuth(user.Username, password)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
// Exercise the real handler independently of Router wiring.
|
||||
// This component test does not replace the end-to-end login acceptance test.
|
||||
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Errorf("login with JSON body must return 400; received %d", recorder.Code)
|
||||
}
|
||||
if f.redis.audit.writeCount() != writes {
|
||||
t.Error("login with forbidden JSON body attempted to create a session")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"highload/internal/database"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
)
|
||||
|
||||
func operationBudget(t *testing.T) time.Duration {
|
||||
t.Helper()
|
||||
value := os.Getenv("AUTH_TEST_OPERATION_BUDGET_MS")
|
||||
if value == "" {
|
||||
t.Log("budget_policy=provisional_3000ms; teacher has no numeric threshold; approval remains pending")
|
||||
return 3 * time.Second
|
||||
}
|
||||
n, err := strconv.Atoi(value)
|
||||
if err != nil || n < 500 || n > 10000 {
|
||||
t.Fatal("AUTH_TEST_OPERATION_BUDGET_MS must be 500..10000")
|
||||
}
|
||||
return time.Duration(n) * time.Millisecond
|
||||
}
|
||||
|
||||
func applicationPool(t *testing.T, f *fixture) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
u, err := url.Parse(os.Getenv("AUTH_TEST_DATABASE_URL"))
|
||||
if err != nil {
|
||||
t.Fatal("invalid test URL")
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("search_path", f.config.ConnConfig.RuntimeParams["search_path"])
|
||||
u.RawQuery = q.Encode()
|
||||
// Actual production constructor: never inherit fixture statement_timeout.
|
||||
pool, err := database.NewPostgres(f.ctx, u.String())
|
||||
if err != nil {
|
||||
t.Fatal("application pool unavailable")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.pool = pool
|
||||
f.queries = sqlc.New(pool)
|
||||
return pool
|
||||
}
|
||||
|
||||
func blockOperation(t *testing.T, f *fixture, mode string) func() {
|
||||
t.Helper()
|
||||
if mode == "blocked_query" {
|
||||
tx, err := f.admin.Begin(f.ctx)
|
||||
if err != nil {
|
||||
t.Fatal("lock transaction failed")
|
||||
}
|
||||
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "users"}.Sanitize()
|
||||
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
|
||||
t.Fatal("isolated table lock failed")
|
||||
}
|
||||
return func() {
|
||||
ctx, c := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer c()
|
||||
_ = tx.Rollback(ctx)
|
||||
}
|
||||
}
|
||||
max := f.pool.Config().MaxConns
|
||||
if max <= 0 || max > 128 {
|
||||
t.Fatal("test refuses unbounded/oversized pool")
|
||||
}
|
||||
held := make([]*pgxpool.Conn, 0, max)
|
||||
for range max {
|
||||
conn, err := f.pool.Acquire(f.ctx)
|
||||
if err != nil {
|
||||
for _, h := range held {
|
||||
h.Release()
|
||||
}
|
||||
t.Fatal("pool saturation failed")
|
||||
}
|
||||
held = append(held, conn)
|
||||
}
|
||||
return func() {
|
||||
for _, h := range held {
|
||||
h.Release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresOperationsHaveBoundedWaits(t *testing.T) {
|
||||
budget := operationBudget(t)
|
||||
for _, mode := range []string{"blocked_query", "exhausted_pool"} {
|
||||
for _, scenario := range []string{"application_budget", "shorter_caller_deadline", "released_before_budget"} {
|
||||
t.Run(mode+"/"+scenario, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
applicationPool(t, f)
|
||||
release := blockOperation(t, f, mode)
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
release()
|
||||
}
|
||||
}()
|
||||
safety := budget + 2*time.Second
|
||||
if scenario == "shorter_caller_deadline" {
|
||||
safety = 150 * time.Millisecond
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), safety)
|
||||
defer cancel()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil).WithContext(ctx)
|
||||
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recorder := httptest.NewRecorder()
|
||||
done := make(chan struct{})
|
||||
started := time.Now()
|
||||
go func() { defer close(done); redisRouter(f, f.redis.client).ServeHTTP(recorder, request) }()
|
||||
if scenario == "released_before_budget" {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
release()
|
||||
released = true
|
||||
}
|
||||
<-done
|
||||
elapsed := time.Since(started)
|
||||
t.Logf("mode=%s scenario=%s elapsed_ms=%.3f caller_deadline_ms=%d budget_ms=%d caller_canceled=%t", mode, scenario, float64(elapsed)/float64(time.Millisecond), safety.Milliseconds(), budget.Milliseconds(), ctx.Err() != nil)
|
||||
switch scenario {
|
||||
case "application_budget":
|
||||
if ctx.Err() != nil || elapsed > budget+250*time.Millisecond {
|
||||
t.Error("application did not independently enforce its operation budget before test safety cancellation")
|
||||
}
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
case "shorter_caller_deadline":
|
||||
if elapsed > 750*time.Millisecond {
|
||||
t.Error("short caller deadline was not honored")
|
||||
}
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
case "released_before_budget":
|
||||
if recorder.Code != 200 || elapsed >= budget {
|
||||
t.Error("unblocked operation failed or missed the declared budget")
|
||||
}
|
||||
}
|
||||
if !released {
|
||||
release()
|
||||
released = true
|
||||
}
|
||||
recovery := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/api/v1/users/me", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recoveryCtx, c := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer c()
|
||||
redisRouter(f, f.redis.client).ServeHTTP(recovery, req.WithContext(recoveryCtx))
|
||||
if recovery.Code != 200 {
|
||||
t.Error("service did not recover after releasing lock/pool")
|
||||
}
|
||||
if f.pool.Stat().AcquiredConns() != 0 {
|
||||
t.Error("application pool leaked an acquired connection")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresChatCancellationBeforeCommitIsAtomic(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, _ := f.user(t)
|
||||
applicationPool(t, f)
|
||||
tx, err := f.admin.Begin(f.ctx)
|
||||
if err != nil {
|
||||
t.Fatal("cannot start membership blocker")
|
||||
}
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
_ = tx.Rollback(context.Background())
|
||||
}
|
||||
}()
|
||||
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "chat_members"}.Sanitize()
|
||||
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
|
||||
t.Fatal("cannot block membership insertion")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
repo := postgres.NewChatRepository(f.queries, f.pool)
|
||||
_, err = repo.CreateChat(ctx, "Canceled before membership", []string{user.ID})
|
||||
if !errors.Is(err, repository.ErrServiceUnavailable) {
|
||||
t.Errorf("want unavailable after controlled pre-commit cancellation, got category %v", err)
|
||||
}
|
||||
// The membership INSERT cannot finish while this lock is held, so COMMIT
|
||||
// has not been reached. No ambiguous-commit inference is made here.
|
||||
_ = tx.Rollback(context.Background())
|
||||
released = true
|
||||
for _, name := range []string{"chats", "chat_members"} {
|
||||
var count int
|
||||
if f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+name).Scan(&count) != nil || count != 0 {
|
||||
t.Error("pre-commit cancellation left partial chat data")
|
||||
}
|
||||
}
|
||||
if _, err = repo.CreateChat(f.ctx, "Works after cancellation", []string{user.ID}); err != nil {
|
||||
t.Error("chat repository failed to recover")
|
||||
}
|
||||
if f.pool.Stat().AcquiredConns() != 0 {
|
||||
t.Error("chat cancellation leaked a connection")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
repository "highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func TestErrorDiagnosticsRecordedOnceAndPublicResponseIsSafe(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
original := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil)))
|
||||
defer slog.SetDefault(original)
|
||||
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: errors.New("synthetic-storage-diagnostic")})))
|
||||
_, cause := users.GetUser(context.Background(), uuid.NewString())
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-secret-not-for-logs")
|
||||
recorder := httptest.NewRecorder()
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = httputils.WriteServiceError(w, cause, middleware.RequestIDFromContext(r.Context()))
|
||||
})).ServeHTTP(recorder, request)
|
||||
assertContractError(t, recorder, 500, "internal_error")
|
||||
if strings.Contains(recorder.Body.String(), "synthetic-storage-diagnostic") {
|
||||
t.Error("public response exposed internal cause")
|
||||
}
|
||||
if strings.Contains(output.String(), "synthetic-secret-not-for-logs") {
|
||||
t.Error("server log exposed a Bearer credential")
|
||||
}
|
||||
var records []map[string]any
|
||||
for _, line := range strings.Split(strings.TrimSpace(output.String()), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var record map[string]any
|
||||
if json.Unmarshal([]byte(line), &record) != nil {
|
||||
t.Error("diagnostic log is not structured JSON")
|
||||
continue
|
||||
}
|
||||
// Access records are not detailed duplicate error records.
|
||||
if record["msg"] != "http request" {
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
if len(records) != 1 {
|
||||
t.Errorf("want exactly one detailed error at response boundary, got %d", len(records))
|
||||
return
|
||||
}
|
||||
record := records[0]
|
||||
if _, malformed := record["!BADKEY"]; malformed {
|
||||
t.Error("structured error log contains !BADKEY: slog arguments are not valid key/value pairs")
|
||||
}
|
||||
if record["request_id"] != recorder.Header().Get("X-Request-Id") || record["status"] != float64(500) ||
|
||||
(record["code"] != "internal_error" && record["error_code"] != "internal_error") {
|
||||
t.Error("diagnostic is missing matching request_id/status/error code")
|
||||
}
|
||||
encoded, _ := json.Marshal(record)
|
||||
if !bytes.Contains(encoded, []byte("synthetic-storage-diagnostic")) {
|
||||
t.Error("diagnostic lost storage cause")
|
||||
}
|
||||
}
|
||||
|
||||
// Faults enter through sqlc's database interface, then pass through the real
|
||||
// repository, service and HTTP error mapper. Driver causes are deliberately
|
||||
// not required to survive: the public category and response are the contract.
|
||||
type errorCase struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
status int
|
||||
code string
|
||||
}
|
||||
|
||||
func databaseErrorCases() []errorCase {
|
||||
cases := []errorCase{
|
||||
{"no_rows", pgx.ErrNoRows, service.ErrNotFound, 404, "not_found"},
|
||||
{"duplicate", &pgconn.PgError{Code: "23505"}, service.ErrAlreadyExists, 409, "conflict"},
|
||||
{"eof", io.EOF, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"deadline", context.DeadlineExceeded, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"unexpected_eof", io.ErrUnexpectedEOF, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"closed_connection", pgconn.ErrConnClosed, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"connection_refused", unavailableRow{}.Scan(), service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
// Docker removes the stopped service from DNS. The real outage probe
|
||||
// returned a ConnectError containing this error, without a net.OpError.
|
||||
{"database_dns_missing", &net.DNSError{Err: "no such host", Name: "postgres", IsNotFound: true}, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"sql_syntax", &pgconn.PgError{Code: "42601", Message: "private SQL diagnostic"}, service.ErrServerError, 500, "internal_error"},
|
||||
{"unexpected", errors.New("private database diagnostic"), service.ErrServerError, 500, "internal_error"},
|
||||
}
|
||||
for _, code := range []string{"53300", "57P03", "08006", "08001", "57P01", "57P02"} {
|
||||
cases = append(cases, errorCase{"sqlstate_" + code, &pgconn.PgError{Code: code}, service.ErrServiceUnavailable, 503, "unavailable"})
|
||||
}
|
||||
// Wrapping must not change how an existing error category is recognized.
|
||||
originals := append([]errorCase(nil), cases...)
|
||||
for _, tc := range originals {
|
||||
tc.name = "wrapped_" + tc.name
|
||||
tc.cause = fmt.Errorf("database operation: %w", tc.cause)
|
||||
cases = append(cases, tc)
|
||||
}
|
||||
return cases
|
||||
}
|
||||
|
||||
type faultRow struct{ cause error }
|
||||
|
||||
func (r faultRow) Scan(...any) error { return r.cause }
|
||||
|
||||
type faultDB struct {
|
||||
unavailableDB
|
||||
cause error
|
||||
}
|
||||
|
||||
func (d faultDB) QueryRow(context.Context, string, ...any) pgx.Row {
|
||||
return faultRow{d.cause}
|
||||
}
|
||||
|
||||
func assertContractError(t *testing.T, recorder *httptest.ResponseRecorder, status int, code string) {
|
||||
t.Helper()
|
||||
if recorder.Code != status {
|
||||
t.Fatalf("want HTTP %d, got %d", status, recorder.Code)
|
||||
}
|
||||
if recorder.Header().Get("Content-Type") != "application/json" {
|
||||
t.Fatal("error response must have application/json content type")
|
||||
}
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
decoder := json.NewDecoder(recorder.Body)
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
t.Fatal("error response is not valid JSON")
|
||||
}
|
||||
if decoder.Decode(new(any)) != io.EOF {
|
||||
t.Fatal("error response contains more than one JSON value")
|
||||
}
|
||||
if payload.Error.Code != code || payload.Error.RequestID == "" ||
|
||||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
|
||||
t.Fatal("error category or request ID violates the API contract")
|
||||
}
|
||||
if payload.Error.Message == "" || strings.Contains(payload.Error.Message, "private") {
|
||||
t.Fatal("error message is empty or discloses internal diagnostics")
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorDatabaseCategoryReachesHTTP(t *testing.T) {
|
||||
for _, tc := range databaseErrorCases() {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: tc.cause})))
|
||||
_, err := users.GetUser(context.Background(), uuid.NewString())
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("want category %v, got %v", tc.want, err)
|
||||
}
|
||||
if errors.Is(tc.cause, context.DeadlineExceeded) && !strings.Contains(err.Error(), context.DeadlineExceeded.Error()) {
|
||||
t.Error("deadline diagnostic context lost between repository and service")
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = httputils.WriteServiceError(w, err, middleware.RequestIDFromContext(r.Context()))
|
||||
})).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
|
||||
assertContractError(t, recorder, tc.status, tc.code)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorUnavailableSQLLoginKeepsCategory(t *testing.T) {
|
||||
for _, tc := range databaseErrorCases() {
|
||||
if tc.status != 503 {
|
||||
continue
|
||||
}
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
queries := sqlc.New(faultDB{cause: tc.cause})
|
||||
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
|
||||
mid := middleware.NewMiddleware(auth, "auth-test")
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("synthetic_user", "Synthetic:password")
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The caller exists; the other member lookup fails. This isolates the service
|
||||
// branch that used to replace the received err with ErrServerError.
|
||||
type memberFaultDB struct {
|
||||
unavailableDB
|
||||
caller uuid.UUID
|
||||
cause error
|
||||
}
|
||||
|
||||
func (d memberFaultDB) QueryRow(_ context.Context, _ string, args ...any) pgx.Row {
|
||||
id := uuid.UUID(args[0].(pgtype.UUID).Bytes)
|
||||
if id == d.caller {
|
||||
return memberUserRow{id}
|
||||
}
|
||||
return faultRow{d.cause}
|
||||
}
|
||||
|
||||
type memberUserRow struct{ id uuid.UUID }
|
||||
|
||||
func (r memberUserRow) Scan(dst ...any) error {
|
||||
*dst[0].(*pgtype.UUID) = pgtype.UUID{Bytes: [16]byte(r.id), Valid: true}
|
||||
*dst[1].(*string) = "error_test_caller"
|
||||
*dst[2].(*string) = "Error test caller"
|
||||
*dst[3].(*string) = "unused password hash"
|
||||
*dst[4].(*pgtype.Timestamptz) = pgtype.Timestamptz{Time: time.Unix(1, 0), Valid: true}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestErrorChatMemberLookupKeepsOperationMeaning(t *testing.T) {
|
||||
for _, tc := range databaseErrorCases() {
|
||||
if tc.status != 503 && tc.status != 404 && tc.status != 500 {
|
||||
continue
|
||||
}
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
caller := uuid.New()
|
||||
queries := sqlc.New(memberFaultDB{caller: caller, cause: tc.cause})
|
||||
users := repository.NewUserRepository(queries)
|
||||
// No writable repository: an invalid member list must never reach
|
||||
// chat insertion. Accidentally continuing is a test failure.
|
||||
chats := service.NewChatService(nil, users, service.NewUserService(users))
|
||||
_, err := chats.Create(context.Background(), "Error regression", []string{caller.String(), uuid.NewString()}, caller.String())
|
||||
want, status, code := tc.want, tc.status, tc.code
|
||||
if tc.status == 404 {
|
||||
// contracts/README.md:17: unknown members make POST /chats invalid.
|
||||
want, status, code = service.ErrInvalidInput, 400, "invalid_request"
|
||||
}
|
||||
if !errors.Is(err, want) {
|
||||
t.Fatalf("want category %v, got %v", want, err)
|
||||
}
|
||||
gotStatus, gotCode := httputils.ErrorFromService(err)
|
||||
if gotStatus != status || gotCode != code {
|
||||
t.Fatalf("want %d/%s, got %d/%s", status, code, gotStatus, gotCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorMissingBasicPrecedesForbiddenBody(t *testing.T) {
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
auth := handler.NewAuthHandler(nil)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
|
||||
assertContractError(t, recorder, 401, "unauthorized")
|
||||
if recorder.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatal("missing Basic challenge")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
"highload/internal/repository"
|
||||
)
|
||||
|
||||
type logoutObservationKey struct{}
|
||||
type logoutObservation struct {
|
||||
Group int `json:"clients"`
|
||||
Round int `json:"round"`
|
||||
PauseMS int `json:"pause_ms"`
|
||||
ElapsedMS float64 `json:"elapsed_ms"`
|
||||
WaitMS float64 `json:"waitaof_ms"`
|
||||
DelID int64 `json:"del_connection_id"`
|
||||
WaitID int64 `json:"wait_connection_id"`
|
||||
Local *int64 `json:"local_fsynced"`
|
||||
Replicas *int64 `json:"replicas_fsynced"`
|
||||
Kind string `json:"kind"`
|
||||
CommandError string `json:"command_error,omitempty"`
|
||||
RepositoryError string `json:"repository_error,omitempty"`
|
||||
}
|
||||
type logoutAOFObservation struct{}
|
||||
|
||||
func (h logoutAOFObservation) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (h logoutAOFObservation) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (h logoutAOFObservation) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
started := time.Now()
|
||||
err := next(ctx, cmd)
|
||||
row, _ := ctx.Value(logoutObservationKey{}).(*logoutObservation)
|
||||
if row == nil {
|
||||
return err
|
||||
}
|
||||
name := cmd.Name()
|
||||
if name != "del" && name != "waitaof" {
|
||||
return err
|
||||
}
|
||||
if name == "waitaof" {
|
||||
row.WaitMS = float64(time.Since(started)) / float64(time.Millisecond)
|
||||
if err != nil {
|
||||
row.CommandError = err.Error()
|
||||
row.Kind = "command_error"
|
||||
} else {
|
||||
if value, ok := cmd.(*redisclient.Cmd); ok {
|
||||
if reply, ok := value.Val().([]any); ok && len(reply) == 2 {
|
||||
local, lok := reply[0].(int64)
|
||||
replicas, rok := reply[1].(int64)
|
||||
if lok && rok {
|
||||
row.Local = &local
|
||||
row.Replicas = &replicas
|
||||
row.Kind = "acknowledged"
|
||||
if local != 1 {
|
||||
row.Kind = "unacknowledged"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if row.Local == nil {
|
||||
row.Kind = "unexpected_reply"
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
// next is bound to this Conn's processing path. The observation adds a
|
||||
// read-only CLIENT ID on that same path; it never gets a second pool slot.
|
||||
id := redisclient.NewIntCmd(ctx, "CLIENT", "ID")
|
||||
if e := next(ctx, id); e == nil {
|
||||
if name == "del" {
|
||||
row.DelID = id.Val()
|
||||
} else {
|
||||
row.WaitID = id.Val()
|
||||
}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisLogoutPersistenceDiagnostic(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
f.client.AddHook(logoutAOFObservation{})
|
||||
before := f.client.PoolStats()
|
||||
rows := []logoutObservation{}
|
||||
var mu sync.Mutex
|
||||
stop := make(chan struct{})
|
||||
sampled := make(chan struct{})
|
||||
poolSamples := []map[string]any{}
|
||||
go func() {
|
||||
defer close(sampled)
|
||||
ticker := time.NewTicker(50 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
poolSamples = append(poolSamples, map[string]any{"at": time.Now().UTC().Format(time.RFC3339Nano), "stats": f.client.PoolStats()})
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
close(stop)
|
||||
<-sampled
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for f.client.PoolStats().TotalConns != f.client.PoolStats().IdleConns && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
after := f.client.PoolStats()
|
||||
if after.TotalConns != after.IdleConns || after.PendingRequests != 0 {
|
||||
t.Error("logout left acquired/pending pool connections")
|
||||
}
|
||||
report := map[string]any{"pool_before": before, "pool_after": after, "pool_samples": poolSamples, "samples": rows, "production_options": map[string]any{"read_timeout_ms": f.client.Options().ReadTimeout.Milliseconds(), "pool_size": f.client.Options().PoolSize, "pool_timeout_ms": f.client.Options().PoolTimeout.Milliseconds()}, "instrumentation": "read-only CLIENT ID after DEL and WAITAOF, on the pinned processing path"}
|
||||
if directory := os.Getenv("AUTH_TEST_DIAGNOSTICS_DIR"); directory != "" {
|
||||
_ = os.MkdirAll(directory, 0700)
|
||||
data, _ := json.MarshalIndent(report, "", " ")
|
||||
if os.WriteFile(filepath.Join(directory, "redis-logout.json"), data, 0600) != nil {
|
||||
t.Error("cannot save Redis diagnostics")
|
||||
}
|
||||
}
|
||||
t.Logf("logout samples=%d pool_wait_count=%d wait_ns=%d pool_timeouts=%d final_busy=%d", len(rows), after.WaitCount-before.WaitCount, after.WaitDurationNs-before.WaitDurationNs, after.Timeouts-before.Timeouts, after.TotalConns-after.IdleConns)
|
||||
}()
|
||||
run := func(clients, round, pause int) {
|
||||
var workers sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for range clients {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
// Two sessions for one synthetic identity: revoking one must leave the
|
||||
// other valid, even while other workers revoke their own sessions.
|
||||
first, other := f.trackSafe(uuid.NewString()), f.trackSafe(uuid.NewString())
|
||||
user := uuid.NewString()
|
||||
if _, err := f.repo.Create(f.ctx, first[:], user, time.Minute); err != nil {
|
||||
t.Error("create logout fixture failed")
|
||||
return
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, other[:], user, time.Minute); err != nil {
|
||||
t.Error("create independent fixture failed")
|
||||
return
|
||||
}
|
||||
<-start
|
||||
time.Sleep(time.Duration(pause) * time.Millisecond)
|
||||
row := logoutObservation{Group: clients, Round: round, PauseMS: pause}
|
||||
ctx := context.WithValue(f.ctx, logoutObservationKey{}, &row)
|
||||
began := time.Now()
|
||||
_, err := f.repo.RevokeSession(ctx, first[:])
|
||||
row.ElapsedMS = float64(time.Since(began)) / float64(time.Millisecond)
|
||||
if err != nil {
|
||||
row.RepositoryError = err.Error()
|
||||
t.Errorf("logout clients=%d kind=%s category=%v", clients, row.Kind, err)
|
||||
}
|
||||
if row.Kind == "unacknowledged" && !errors.Is(err, repository.ErrServiceUnavailable) {
|
||||
t.Error("unacknowledged local fsync must preserve unavailable category")
|
||||
}
|
||||
if row.DelID == 0 || row.DelID != row.WaitID {
|
||||
t.Error("DEL/WAITAOF connection identity not preserved")
|
||||
}
|
||||
if _, err = f.repo.GetSessionByTokenHash(f.ctx, other[:]); err != nil {
|
||||
t.Error("concurrent logout affected independent session")
|
||||
}
|
||||
if _, err = f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repository.ErrNotFound) {
|
||||
t.Error("revoked session still available")
|
||||
}
|
||||
mu.Lock()
|
||||
rows = append(rows, row)
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
}
|
||||
for i, pause := range []int{0, 137, 359, 613, 887, 1109} {
|
||||
run(1, i+1, pause)
|
||||
}
|
||||
for _, clients := range []int{5, 10} {
|
||||
for round := 1; round <= 3; round++ {
|
||||
run(clients, round, 137*round)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// track modifies fixture cleanup bookkeeping; concurrent probes synchronize it.
|
||||
var diagnosticTrackMu sync.Mutex
|
||||
|
||||
func (f *redisFixture) trackSafe(token string) [32]byte {
|
||||
diagnosticTrackMu.Lock()
|
||||
defer diagnosticTrackMu.Unlock()
|
||||
return f.track(token)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"highload/internal/security"
|
||||
)
|
||||
|
||||
// These are tests of the selected Argon2id implementation, not a requirement
|
||||
// that lab2 use particular parameters or a particular encoded hash format.
|
||||
func TestPasswordRoundTripAndRandomSalt(t *testing.T) {
|
||||
password := "Синтетический:пароль:😀"
|
||||
first, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
second, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
if first == password || second == password || first == second {
|
||||
t.Fatal("hash must differ from plaintext and have a fresh random salt")
|
||||
}
|
||||
if !strings.HasPrefix(first, "$argon2id$") {
|
||||
t.Fatal("selected password implementation did not encode Argon2id")
|
||||
}
|
||||
for _, encoded := range []string{first, second} {
|
||||
ok, err := security.VerifyPassword(password, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("stored hash does not verify the original password")
|
||||
}
|
||||
ok, err = security.VerifyPassword(password+"x", encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("wrong password was accepted or verifier failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordDoesNotTruncateLongUTF8(t *testing.T) {
|
||||
// Both passwords share much more than bcrypt's 72-byte limit; each is
|
||||
// within the lab's 128-code-point maximum.
|
||||
password := strings.Repeat("😀", 127) + "A"
|
||||
different := strings.Repeat("😀", 127) + "B"
|
||||
encoded, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("maximum-length UTF-8 password cannot be hashed")
|
||||
}
|
||||
ok, err := security.VerifyPassword(password, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("maximum-length UTF-8 password cannot be verified")
|
||||
}
|
||||
ok, err = security.VerifyPassword(different, encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("password suffix was truncated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordWhitespaceIsSignificant(t *testing.T) {
|
||||
password := " synthetic-password "
|
||||
encoded, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
ok, err := security.VerifyPassword(strings.TrimSpace(password), encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("password whitespace was discarded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedPasswordHashRejectedWithoutPanic(t *testing.T) {
|
||||
valid, err := security.HashPassword("synthetic-password")
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
parts := strings.Split(valid, "$")
|
||||
if len(parts) != 6 {
|
||||
t.Fatal("unexpected encoded hash format")
|
||||
}
|
||||
cases := map[string]string{
|
||||
"empty": "",
|
||||
"plaintext": "synthetic-password",
|
||||
"wrong_algorithm": strings.Replace(valid, "argon2id", "argon2i", 1),
|
||||
"wrong_version": strings.Replace(valid, "$v=19$", "$v=999$", 1),
|
||||
"missing_version": strings.Replace(valid, "$v=19$", "$19$", 1),
|
||||
"extra_field": valid + "$extra",
|
||||
}
|
||||
for name, params := range map[string]string{
|
||||
"zero_iterations": "m=65536,t=0,p=2",
|
||||
"zero_threads": "m=65536,t=3,p=0",
|
||||
"tiny_memory": "m=1,t=3,p=2",
|
||||
"huge_memory": "m=4294967295,t=3,p=2",
|
||||
"huge_iterations": "m=65536,t=4294967295,p=2",
|
||||
"huge_threads": "m=65536,t=3,p=255",
|
||||
"negative": "m=-1,t=3,p=2",
|
||||
"non_numeric": "m=no,t=3,p=2",
|
||||
"missing_param": "m=65536,t=3",
|
||||
} {
|
||||
copyParts := append([]string(nil), parts...)
|
||||
copyParts[3] = params
|
||||
cases[name] = strings.Join(copyParts, "$")
|
||||
}
|
||||
for name, field := range map[string]int{"salt": 4, "hash": 5} {
|
||||
for label, value := range map[string]string{
|
||||
"empty": "", "bad_base64": "!!!", "wrong_size": "YQ",
|
||||
} {
|
||||
copyParts := append([]string(nil), parts...)
|
||||
copyParts[field] = value
|
||||
cases[name+"_"+label] = strings.Join(copyParts, "$")
|
||||
}
|
||||
}
|
||||
for name, encoded := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
t.Error("malformed stored hash caused a panic")
|
||||
}
|
||||
}()
|
||||
ok, err := security.VerifyPassword("synthetic-password", encoded)
|
||||
if ok || !errors.Is(err, security.ErrInvalidHash) {
|
||||
t.Error("malformed stored hash was not rejected")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/config"
|
||||
"highload/internal/database"
|
||||
repoerrors "highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
redisrepo "highload/internal/repository/redis"
|
||||
"highload/internal/service"
|
||||
httptransport "highload/internal/transport/http"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/google/uuid"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func TestRedisAddressIsAnAddressNotAFile(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "postgres_url")
|
||||
if err := os.WriteFile(path, []byte("postgres://fixture:fixture@postgres/messenger"), 0600); err != nil {
|
||||
t.Fatal("cannot create synthetic config fixture")
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", path)
|
||||
t.Setenv("REDIS_ADDR", "redis:6379")
|
||||
t.Setenv("SESSION_TTL_SECONDS", "3600")
|
||||
t.Setenv("SESSION_STORE", "redis")
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatal("REDIS_ADDR must be read as an address, not opened as a file")
|
||||
}
|
||||
if cfg.Database.RedisAddr != "redis:6379" {
|
||||
t.Fatal("REDIS_ADDR did not reach the Redis configuration")
|
||||
}
|
||||
}
|
||||
|
||||
type redisFixture struct {
|
||||
ctx context.Context
|
||||
client *redisclient.Client
|
||||
repo *redisrepo.SessionRepository
|
||||
keys []string
|
||||
audit *sessionWriteAudit
|
||||
}
|
||||
|
||||
// Only observe writes through this test's client. No global key counting or
|
||||
// FLUSH commands: other clients' sessions must not affect assertions/cleanup.
|
||||
type sessionWriteAudit struct {
|
||||
sync.Mutex
|
||||
keys map[string]bool
|
||||
writes int
|
||||
}
|
||||
|
||||
func (a *sessionWriteAudit) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (a *sessionWriteAudit) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (a *sessionWriteAudit) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
if cmd.Name() == "set" && len(cmd.Args()) > 1 {
|
||||
if key, ok := cmd.Args()[1].(string); ok {
|
||||
a.Lock()
|
||||
a.keys[key] = true
|
||||
a.writes++
|
||||
a.Unlock()
|
||||
}
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
func (a *sessionWriteAudit) writeCount() int { a.Lock(); defer a.Unlock(); return a.writes }
|
||||
func (a *sessionWriteAudit) ownedKeys() []string {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
keys := make([]string, 0, len(a.keys))
|
||||
for key := range a.keys {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
type aofReplyHook struct {
|
||||
reply any
|
||||
err error
|
||||
}
|
||||
|
||||
func (h aofReplyHook) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (h aofReplyHook) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (h aofReplyHook) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
if cmd.Name() == "waitaof" {
|
||||
// DEL still runs on the real test Redis. Only its persistence
|
||||
// acknowledgement is fault-injected deterministically.
|
||||
value := cmd.(*redisclient.Cmd)
|
||||
value.SetVal(h.reply)
|
||||
value.SetErr(h.err)
|
||||
return h.err
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisUnconfirmedAOFNeverReturnsSuccessfulLogout(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
reply any
|
||||
err error
|
||||
}{
|
||||
{"local_not_fsynced", []any{int64(0), int64(0)}, nil},
|
||||
{"only_replica_fsynced", []any{int64(0), int64(1)}, nil},
|
||||
{"malformed_reply", []any{int64(1)}, nil},
|
||||
{"command_failure", nil, errors.New("synthetic acknowledgement failure")},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
f.redis.client.AddHook(aofReplyHook{tc.reply, tc.err})
|
||||
request := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
|
||||
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recorder := httptest.NewRecorder()
|
||||
redisRouter(f, f.redis.client).ServeHTTP(recorder, request)
|
||||
if recorder.Code != 500 && recorder.Code != 503 {
|
||||
t.Fatalf("unconfirmed persistence must fail logout, got HTTP %d", recorder.Code)
|
||||
}
|
||||
if (tc.name == "local_not_fsynced" || tc.name == "only_replica_fsynced") && recorder.Code != 503 {
|
||||
t.Errorf("valid reply without local acknowledgement must be HTTP 503, got %d", recorder.Code)
|
||||
}
|
||||
code := "internal_error"
|
||||
if recorder.Code == 503 {
|
||||
code = "unavailable"
|
||||
}
|
||||
assertContractError(t, recorder, recorder.Code, code)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
if f.redis.client.Exists(f.ctx, "session:"+hex.EncodeToString(hash[:])).Val() != 0 {
|
||||
t.Fatal("fault fixture did not actually execute DEL before WAITAOF")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newRedisFixture(t *testing.T) *redisFixture {
|
||||
t.Helper()
|
||||
addr := os.Getenv("AUTH_TEST_REDIS_ADDR")
|
||||
if addr == "" {
|
||||
t.Skip("Redis not verified: set AUTH_TEST_REDIS_ADDR to a dedicated test Redis with AOF")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
client, err := database.NewRedis(ctx, addr)
|
||||
if err != nil {
|
||||
t.Fatal("dedicated test Redis is unavailable")
|
||||
}
|
||||
audit := &sessionWriteAudit{keys: make(map[string]bool)}
|
||||
client.AddHook(audit)
|
||||
f := &redisFixture{ctx: ctx, client: client, repo: redisrepo.NewSessionRepository(client), audit: audit}
|
||||
t.Cleanup(func() {
|
||||
cleanup, done := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer done()
|
||||
// No FLUSHDB/FLUSHALL: delete only this test's own random token keys.
|
||||
keys := append(f.audit.ownedKeys(), f.keys...)
|
||||
if len(keys) > 0 {
|
||||
if err := client.Del(cleanup, keys...).Err(); err != nil {
|
||||
t.Error("test-owned Redis key cleanup failed")
|
||||
}
|
||||
}
|
||||
_ = client.Close()
|
||||
})
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *redisFixture) track(token string) [32]byte {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
f.keys = append(f.keys, "session:"+hex.EncodeToString(hash[:]))
|
||||
return hash
|
||||
}
|
||||
|
||||
func TestRedisSessionHasTTLAndReadsDoNotExtendIt(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track("synthetic-" + uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 5*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create Redis session")
|
||||
}
|
||||
key := f.keys[0]
|
||||
before := f.client.PTTL(f.ctx, key).Val()
|
||||
if before <= 0 || before > 5*time.Second {
|
||||
t.Fatal("session key has no bounded positive TTL")
|
||||
}
|
||||
time.Sleep(120 * time.Millisecond)
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || loaded == nil {
|
||||
t.Fatal("cannot read Redis session")
|
||||
}
|
||||
if loaded.UserID != created.UserID || !loaded.ExpiresAt.Equal(created.ExpiresAt) ||
|
||||
!loaded.CreatedAt.Equal(created.CreatedAt) {
|
||||
t.Fatal("session identity or original timestamps changed on read")
|
||||
}
|
||||
after := f.client.PTTL(f.ctx, key).Val()
|
||||
if after <= 0 || after >= before {
|
||||
t.Fatal("reading refreshed or removed the session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisExpiredAndUnknownSessionsAreNotFound(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track(uuid.NewString())
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("unknown session must be not found")
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 200*time.Millisecond); err != nil {
|
||||
t.Fatal("cannot create short-lived test session")
|
||||
}
|
||||
time.Sleep(350 * time.Millisecond)
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("expired Redis session is still available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisLogoutOnlyRemovesSelectedSession(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
first, second := f.track(uuid.NewString()), f.track(uuid.NewString())
|
||||
userID := uuid.NewString()
|
||||
for _, hash := range [][32]byte{first, second} {
|
||||
if _, err := f.repo.Create(f.ctx, hash[:], userID, time.Minute); err != nil {
|
||||
t.Fatal("cannot create independent sessions")
|
||||
}
|
||||
}
|
||||
count, err := f.repo.RevokeSession(f.ctx, first[:])
|
||||
if err != nil || count != 1 {
|
||||
t.Fatal("logout failed to remove exactly one session or acknowledge persistence")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("revoked session is still readable")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, second[:]); err != nil {
|
||||
t.Fatal("logout removed another session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisSessionsSurviveActualRestartWithoutExtendingTTL(t *testing.T) {
|
||||
hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK")
|
||||
if hook == "" {
|
||||
t.Skip("Redis restart not verified: set an explicit dedicated test restart hook")
|
||||
}
|
||||
f := newRedisFixture(t)
|
||||
active, revoked := f.track(uuid.NewString()), f.track(uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, active[:], uuid.NewString(), 30*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create active session")
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, revoked[:], created.UserID, time.Minute); err != nil {
|
||||
t.Fatal("cannot create revocation fixture")
|
||||
}
|
||||
if _, err := f.repo.RevokeSession(f.ctx, revoked[:]); err != nil {
|
||||
t.Fatal("cannot persist logout before restart")
|
||||
}
|
||||
before := f.client.PTTL(f.ctx, f.keys[0]).Val()
|
||||
if err := exec.CommandContext(f.ctx, hook).Run(); err != nil {
|
||||
t.Fatal("explicit Redis restart hook failed (private output suppressed)")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, active[:])
|
||||
if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) {
|
||||
t.Fatal("restart lost active session or changed its original deadline")
|
||||
}
|
||||
if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before {
|
||||
t.Fatal("restart extended or lost remaining TTL")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, revoked[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("restart revived a revoked session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisActiveSessionSurvivesRestartIndependentlyOfLogout(t *testing.T) {
|
||||
hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK")
|
||||
if hook == "" {
|
||||
t.Skip("Redis restart not verified: set an explicit dedicated test restart hook")
|
||||
}
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track(uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 30*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create active session")
|
||||
}
|
||||
before := f.client.PTTL(f.ctx, f.keys[0]).Val()
|
||||
if err := exec.CommandContext(f.ctx, hook).Run(); err != nil {
|
||||
t.Fatal("explicit Redis restart hook failed (private output suppressed)")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) || loaded.UserID != created.UserID {
|
||||
t.Fatal("restart lost active session identity or changed its deadline")
|
||||
}
|
||||
if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before {
|
||||
t.Fatal("restart extended or removed the session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func refusedRedis(t *testing.T) *redisclient.Client {
|
||||
t.Helper()
|
||||
client := redisclient.NewClient(&redisclient.Options{
|
||||
Addr: "synthetic-unavailable:6379", MaxRetries: -1,
|
||||
Dialer: func(context.Context, string, string) (net.Conn, error) {
|
||||
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
|
||||
},
|
||||
})
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
return client
|
||||
}
|
||||
|
||||
func TestRedisUnavailableKeepsUnavailableCategory(t *testing.T) {
|
||||
repo := redisrepo.NewSessionRepository(refusedRedis(t))
|
||||
hash := sha256.Sum256([]byte("synthetic-failed-token"))
|
||||
t.Run("create", func(t *testing.T) {
|
||||
_, err := repo.Create(context.Background(), hash[:], uuid.NewString(), time.Minute)
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
t.Run("read", func(t *testing.T) {
|
||||
_, err := repo.GetSessionByTokenHash(context.Background(), hash[:])
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
t.Run("logout", func(t *testing.T) {
|
||||
_, err := repo.RevokeSession(context.Background(), hash[:])
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
auth := service.NewAuthService(nil, repo, time.Hour)
|
||||
_, err := auth.ValidateSession(context.Background(), "synthetic-error-context")
|
||||
if !errors.Is(err, service.ErrServiceUnavailable) || !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("service lost Redis unavailable category or diagnostic context")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func redisRouter(f *fixture, client *redisclient.Client) http.Handler {
|
||||
users := postgres.NewUserRepository(f.queries)
|
||||
auth := service.NewAuthService(users, redisrepo.NewSessionRepository(client), time.Hour)
|
||||
userService := service.NewUserService(users)
|
||||
chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), users, userService)
|
||||
messages := service.NewMessageService(postgres.NewMessageRepository(f.queries, f.pool), chats, userService)
|
||||
return httptransport.NewRouter(middleware.NewMiddleware(auth, "auth-test"), handler.NewAuthHandler(auth),
|
||||
handler.NewHealthHandler(f.pool, client), handler.NewChatHandler(chats), handler.NewUserHandler(userService),
|
||||
handler.NewMessageHandler(messages)).Handler()
|
||||
}
|
||||
|
||||
func TestRedisCriticalOutageHTTPAndReadiness(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
router := redisRouter(f, refusedRedis(t))
|
||||
for _, tc := range []struct {
|
||||
name, path string
|
||||
status int
|
||||
}{
|
||||
{"liveness", "/health/live", 200},
|
||||
{"readiness", "/health/ready", 503},
|
||||
{"protected_request", "/api/v1/users/me", 503},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-outage-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
if recorder.Code != tc.status {
|
||||
t.Fatalf("want HTTP %d, got %d", tc.status, recorder.Code)
|
||||
}
|
||||
if tc.status == 503 {
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisPublicHTTPContractIsUnchanged(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
r := newRedisFixture(t)
|
||||
server := httptest.NewServer(redisRouter(f, r.client))
|
||||
t.Cleanup(server.Close)
|
||||
_, source, _, _ := runtime.Caller(0)
|
||||
root := filepath.Clean(filepath.Join(filepath.Dir(source), "..", ".."))
|
||||
// The full acceptance suite performs many Argon2id operations. Under -race
|
||||
// it needs its own budget rather than the 45-second SQL fixture budget.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"teacher_smoke", []string{filepath.Join(root, "tests/smoke.py"), "--base-url", server.URL}},
|
||||
{"auth_normal", []string{filepath.Join(root, "student-tests/auth_contract.py"), "--base-url", server.URL, "--ttl", "3600"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Each independent subprocess gets the full acceptance budget. A smoke
|
||||
// run must not consume part of the following auth suite's allowance.
|
||||
acceptanceCtx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(acceptanceCtx, "python3", tc.args...)
|
||||
cmd.Dir = root
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
for _, line := range strings.Split(string(output), "\n") {
|
||||
if strings.HasPrefix(line, "test_") {
|
||||
// Only method names: never print credentials or subtest values.
|
||||
name, _, _ := strings.Cut(line, " ")
|
||||
t.Log("acceptance progress: " + name)
|
||||
}
|
||||
}
|
||||
if acceptanceCtx.Err() != nil {
|
||||
t.Fatal("HTTP acceptance subprocess exceeded its own execution budget; application operation budgets are unchanged")
|
||||
}
|
||||
// Public clients keep tokens in memory. Show only status diagnostics.
|
||||
for _, line := range strings.Split(string(output), "\n") {
|
||||
if strings.Contains(line, "expected [") && strings.Contains(line, "received") {
|
||||
t.Log(line)
|
||||
}
|
||||
}
|
||||
t.Fatal("HTTP acceptance contract failed with Redis-backed sessions")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestRedisHTTPFullRestartKeepsDeadlineAndRevocation(t *testing.T) {
|
||||
base, hook := os.Getenv("AUTH_TEST_BASE_URL"), os.Getenv("AUTH_TEST_STACK_RESTART_HOOK")
|
||||
if base == "" || hook == "" {
|
||||
t.Skip("set AUTH_TEST_BASE_URL and AUTH_TEST_STACK_RESTART_HOOK for a disposable API+stores stack")
|
||||
}
|
||||
for _, withLogout := range []bool{false, true} {
|
||||
name := "active_only"
|
||||
if withLogout {
|
||||
name = "active_and_revoked"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
waitReady := func() {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
response, err := client.Get(strings.TrimRight(base, "/") + "/health/ready")
|
||||
if err == nil {
|
||||
response.Body.Close()
|
||||
if response.StatusCode == http.StatusOK {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("API did not regain readiness after restart")
|
||||
}
|
||||
waitReady()
|
||||
username := "restart_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
|
||||
password := "Synthetic:" + uuid.NewString()
|
||||
call := func(method, path, token string, body any, basic bool, want int, dst any) {
|
||||
t.Helper()
|
||||
var data bytes.Buffer
|
||||
if body != nil {
|
||||
if json.NewEncoder(&data).Encode(body) != nil {
|
||||
t.Fatal("cannot encode test request")
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(base, "/")+path, &data)
|
||||
if err != nil {
|
||||
t.Fatal("cannot construct test request")
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if basic {
|
||||
req.SetBasicAuth(username, password)
|
||||
} else if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal("restart HTTP request failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != want {
|
||||
t.Fatalf("%s %s: want %d, got %d", method, path, want, response.StatusCode)
|
||||
}
|
||||
if dst != nil && json.NewDecoder(response.Body).Decode(dst) != nil {
|
||||
t.Fatal("invalid restart response JSON")
|
||||
}
|
||||
}
|
||||
call("POST", "/api/v1/users", "", map[string]string{"username": username, "password": password, "display_name": "Restart fixture"}, false, 201, nil)
|
||||
var active struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &active)
|
||||
hash := f.track(active.Token)
|
||||
before, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
|
||||
if err != nil {
|
||||
t.Fatal("cannot inspect issued session")
|
||||
}
|
||||
if !before.ExpiresAt.Equal(active.ExpiresAt) {
|
||||
t.Fatal("HTTP and Redis expiry differ")
|
||||
}
|
||||
remaining := f.client.PTTL(ctx, f.keys[0]).Val()
|
||||
if remaining < 2*time.Minute {
|
||||
t.Fatal("normal restart suite requires long session TTL")
|
||||
}
|
||||
revoked := ""
|
||||
if withLogout {
|
||||
var other struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &other)
|
||||
revoked = other.Token
|
||||
f.track(revoked)
|
||||
call("DELETE", "/api/v1/auth/sessions/current", revoked, nil, false, 204, nil)
|
||||
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
|
||||
}
|
||||
if exec.CommandContext(ctx, hook).Run() != nil {
|
||||
t.Fatal("real API+stores restart hook failed")
|
||||
}
|
||||
waitReady()
|
||||
call("GET", "/health/live", "", nil, false, 200, nil)
|
||||
call("GET", "/health/ready", "", nil, false, 200, nil)
|
||||
call("GET", "/api/v1/users/me", active.Token, nil, false, 200, nil)
|
||||
after, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
|
||||
if err != nil {
|
||||
t.Fatal("restart lost session")
|
||||
}
|
||||
if !after.ExpiresAt.Equal(before.ExpiresAt) || after.UserID != before.UserID || !after.CreatedAt.Equal(before.CreatedAt) {
|
||||
t.Fatal("actual API+Redis restart changed session identity/deadline")
|
||||
}
|
||||
if ttl := f.client.PTTL(ctx, f.keys[0]).Val(); ttl <= 0 || ttl >= remaining {
|
||||
t.Fatal("restart reset/removed original TTL")
|
||||
}
|
||||
if revoked != "" {
|
||||
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
|
||||
revokedHash := sha256.Sum256([]byte(revoked))
|
||||
if _, err = f.repo.GetSessionByTokenHash(ctx, revokedHash[:]); err == nil {
|
||||
t.Fatal("revoked credential reappeared after restart")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
repository "highload/internal/repository/postgres"
|
||||
redisrepo "highload/internal/repository/redis"
|
||||
"highload/internal/security"
|
||||
"highload/internal/service"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type fixture struct {
|
||||
admin *pgxpool.Pool
|
||||
pool *pgxpool.Pool
|
||||
config *pgxpool.Config
|
||||
queries *sqlc.Queries
|
||||
users *service.UserService
|
||||
auth *service.AuthService
|
||||
redis *redisFixture
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T) *fixture {
|
||||
t.Helper()
|
||||
url := os.Getenv("AUTH_TEST_DATABASE_URL")
|
||||
if url == "" {
|
||||
t.Skip("storage not verified: set AUTH_TEST_DATABASE_URL for a dedicated test PostgreSQL")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
config, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
t.Fatal("cannot parse test PostgreSQL configuration (credentials suppressed)")
|
||||
}
|
||||
config.MaxConns = 4
|
||||
config.MinConns = 0
|
||||
config.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
config.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
admin, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
t.Fatal("cannot open test PostgreSQL pool")
|
||||
}
|
||||
t.Cleanup(admin.Close)
|
||||
if err := admin.Ping(ctx); err != nil {
|
||||
t.Fatal("test PostgreSQL is unavailable")
|
||||
}
|
||||
// Only this uniquely named schema is created and dropped. Existing tables
|
||||
// and volumes are never removed. The role needs CREATE SCHEMA permission.
|
||||
schema := "auth_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
quoted := pgx.Identifier{schema}.Sanitize()
|
||||
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+quoted); err != nil {
|
||||
t.Fatal("cannot create isolated test schema")
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx, done := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer done()
|
||||
if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA "+quoted+" CASCADE"); err != nil {
|
||||
t.Error("isolated test schema cleanup failed")
|
||||
}
|
||||
})
|
||||
config = config.Copy()
|
||||
config.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
f := &fixture{admin: admin, config: config, ctx: ctx, redis: newRedisFixture(t)}
|
||||
f.connect(t, time.Hour)
|
||||
t.Cleanup(func() { f.pool.Close() })
|
||||
_, source, _, ok := runtime.Caller(0)
|
||||
if !ok {
|
||||
t.Fatal("cannot locate migration files")
|
||||
}
|
||||
migrations, err := filepath.Glob(filepath.Join(filepath.Dir(source), "..", "..", "db", "migrations", "*.sql"))
|
||||
if err != nil || len(migrations) == 0 {
|
||||
t.Fatal("migration SQL is missing")
|
||||
}
|
||||
sort.Strings(migrations)
|
||||
for _, path := range migrations {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal("cannot read migration SQL")
|
||||
}
|
||||
// Current migrations are ordinary SQL with Goose Up/Down markers.
|
||||
// This applies schema fixtures; it is NOT a test of Goose version tracking.
|
||||
up, _, _ := strings.Cut(string(data), "-- +goose Down")
|
||||
if !strings.Contains(up, "-- +goose Up") {
|
||||
t.Fatal("test fixture expects SQL migrations with Goose Up/Down markers")
|
||||
}
|
||||
if _, err := f.pool.Exec(ctx, up, pgx.QueryExecModeSimpleProtocol); err != nil {
|
||||
t.Fatal("migration cannot initialize isolated schema")
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fixture) connect(t *testing.T, ttl time.Duration) {
|
||||
t.Helper()
|
||||
pool, err := pgxpool.NewWithConfig(f.ctx, f.config.Copy())
|
||||
if err != nil {
|
||||
t.Fatal("cannot connect to isolated schema")
|
||||
}
|
||||
f.pool = pool
|
||||
f.queries = sqlc.New(pool)
|
||||
userRepo := repository.NewUserRepository(f.queries)
|
||||
sessionRepo := redisrepo.NewSessionRepository(f.redis.client)
|
||||
f.users = service.NewUserService(userRepo)
|
||||
f.auth = service.NewAuthService(userRepo, sessionRepo, ttl)
|
||||
}
|
||||
|
||||
func (f *fixture) user(t *testing.T) (*model.User, string) {
|
||||
t.Helper()
|
||||
password := "Synthetic:" + uuid.NewString()
|
||||
username := "auth_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
|
||||
user, err := f.users.CreateUser(f.ctx, username, "Auth storage", password)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create synthetic user")
|
||||
}
|
||||
return user, password
|
||||
}
|
||||
|
||||
func (f *fixture) session(t *testing.T, user *model.User, password string) *service.CreatedSession {
|
||||
t.Helper()
|
||||
session, err := f.auth.CreateSession(f.ctx, user.Username, password)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create synthetic session")
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
func TestStoragePasswordIsKDFAndDuplicateCannotOverwrite(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
stored, err := f.queries.GetUserByUsername(f.ctx, user.Username)
|
||||
if err != nil || stored.PasswordHash == password || !strings.HasPrefix(stored.PasswordHash, "$argon2id$") {
|
||||
t.Fatal("database did not preserve the selected password KDF")
|
||||
}
|
||||
ok, err := security.VerifyPassword(password, stored.PasswordHash)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("stored password does not verify")
|
||||
}
|
||||
_, err = f.users.CreateUser(f.ctx, user.Username, "Overwrite", password+"x")
|
||||
if !errors.Is(err, service.ErrAlreadyExists) {
|
||||
t.Fatal("duplicate username was not rejected")
|
||||
}
|
||||
after, err := f.queries.GetUserByUsername(f.ctx, user.Username)
|
||||
if err != nil || after.ID != stored.ID || after.PasswordHash != stored.PasswordHash ||
|
||||
after.DisplayName != stored.DisplayName {
|
||||
t.Fatal("failed duplicate registration changed the original user")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageSessionHashAndReconnectPreserveDeadline(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
key := "session:" + hex.EncodeToString(hash[:])
|
||||
row, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
value, getErr := f.redis.client.Get(f.ctx, key).Result()
|
||||
if err != nil || getErr != nil || strings.Contains(key, session.Token) || strings.Contains(value, session.Token) {
|
||||
t.Fatal("selected session storage did not use SHA-256 of the opaque token")
|
||||
}
|
||||
for _, ownedKey := range f.redis.audit.ownedKeys() {
|
||||
storedValue, err := f.redis.client.Get(f.ctx, ownedKey).Result()
|
||||
if err != nil || strings.Contains(ownedKey, session.Token) || strings.Contains(storedValue, session.Token) {
|
||||
t.Fatal("raw session token was persisted in Redis")
|
||||
}
|
||||
}
|
||||
if f.redis.client.Exists(f.ctx, "session:"+session.Token, session.Token).Val() != 0 {
|
||||
t.Fatal("raw token was stored as a Redis key")
|
||||
}
|
||||
if ttl := f.redis.client.PTTL(f.ctx, key).Val(); ttl <= 0 || ttl > time.Hour {
|
||||
t.Fatal("session must have a positive bounded Redis TTL")
|
||||
}
|
||||
if session.TokenType != "Bearer" || len(session.Token) < 32 || row.RevokedAt != nil ||
|
||||
!row.ExpiresAt.Equal(session.ExpiresAt) || !row.ExpiresAt.After(row.CreatedAt) {
|
||||
t.Fatal("invalid stored session metadata")
|
||||
}
|
||||
beforeDeadline := row.ExpiresAt
|
||||
for range 3 {
|
||||
id, err := f.auth.ValidateSession(f.ctx, session.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("valid session rejected or mapped to another user")
|
||||
}
|
||||
}
|
||||
f.pool.Close()
|
||||
// A different process configuration must not reset already stored expiry.
|
||||
f.connect(t, 24*time.Hour)
|
||||
id, err := f.auth.ValidateSession(f.ctx, session.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("new pool/services lost the existing session")
|
||||
}
|
||||
after, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || !after.ExpiresAt.Equal(beforeDeadline) {
|
||||
t.Fatal("reads or reconnection extended session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageWrongCredentialsNeverCreateSession(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
writes := f.redis.audit.writeCount()
|
||||
for _, credentials := range [][2]string{
|
||||
{user.Username, password + "x"}, {"unknown_auth_user", password},
|
||||
} {
|
||||
_, err := f.auth.CreateSession(f.ctx, credentials[0], credentials[1])
|
||||
if !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("wrong credentials did not yield the same unauthorized error")
|
||||
}
|
||||
}
|
||||
if f.redis.audit.writeCount() != writes {
|
||||
t.Fatal("failed login created a session")
|
||||
}
|
||||
for _, token := range []string{"", uuid.NewString()} {
|
||||
if _, err := f.auth.ValidateSession(f.ctx, token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("empty or unknown token accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageRevocationIsPersistentAndSessionSpecific(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
first, second := f.session(t, user, password), f.session(t, user, password)
|
||||
if first.Token == second.Token {
|
||||
t.Fatal("two logins reused the same token")
|
||||
}
|
||||
if err := f.auth.RevokeSession(f.ctx, first.Token); err != nil {
|
||||
t.Fatal("logout failed")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.connect(t, time.Hour)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, first.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("revoked session revived after reconnect")
|
||||
}
|
||||
id, err := f.auth.ValidateSession(f.ctx, second.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("logout affected another session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageExpiredSessionCannotRevive(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
key := "session:" + hex.EncodeToString(hash[:])
|
||||
if err := f.redis.client.PExpire(f.ctx, key, time.Millisecond).Err(); err != nil {
|
||||
t.Fatal("cannot set an expired fixture")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("expired session accepted")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.connect(t, 24*time.Hour)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("new TTL configuration revived an expired session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageShortTTLExpiresAndReLoginWorks(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.auth = service.NewAuthService(repository.NewUserRepository(f.queries),
|
||||
redisrepo.NewSessionRepository(f.redis.client), 2*time.Second)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
if remaining := time.Until(session.ExpiresAt); remaining <= 0 || remaining > 3*time.Second {
|
||||
t.Fatal("two-second TTL was not used for the stored session")
|
||||
}
|
||||
if id, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil || id != user.ID {
|
||||
t.Fatal("fresh short-lived session was rejected")
|
||||
}
|
||||
time.Sleep(max(0, time.Until(session.ExpiresAt)/2))
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil {
|
||||
t.Fatal("session expired before its original deadline")
|
||||
}
|
||||
timer := time.NewTimer(max(0, time.Until(session.ExpiresAt)) + 100*time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-f.ctx.Done():
|
||||
t.Fatal("expiry fixture exceeded its deadline")
|
||||
}
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("short-lived session was accepted after its stored deadline")
|
||||
}
|
||||
fresh := f.session(t, user, password)
|
||||
if fresh.Token == session.Token {
|
||||
t.Fatal("re-login reused the expired token")
|
||||
}
|
||||
if id, err := f.auth.ValidateSession(f.ctx, fresh.Token); err != nil || id != user.ID {
|
||||
t.Fatal("re-login did not produce a usable session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageChatRollbackAfterMemberInsertFailure(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, _ := f.user(t)
|
||||
repo := repository.NewChatRepository(f.queries, f.pool)
|
||||
// A valid first member is inserted before the nonexistent member fails.
|
||||
// Calling the repository bypasses prevalidation and tests real rollback.
|
||||
_, err := repo.CreateChat(f.ctx, "Must roll back", []string{user.ID, uuid.NewString()})
|
||||
if err == nil {
|
||||
t.Fatal("chat with nonexistent member unexpectedly committed")
|
||||
}
|
||||
for _, table := range []string{"chats", "chat_members"} {
|
||||
var count int
|
||||
err := f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+table).Scan(&count)
|
||||
if err != nil || count != 0 {
|
||||
t.Fatal("failed transaction left partial chat or membership rows")
|
||||
}
|
||||
}
|
||||
created, err := repo.CreateChat(f.ctx, "Valid after rollback", []string{user.ID})
|
||||
if err != nil || created == nil {
|
||||
t.Fatal("rollback poisoned subsequent valid transaction")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
repository "highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
httptransport "highload/internal/transport/http"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type unavailableDB struct{}
|
||||
type unavailableRow struct{}
|
||||
|
||||
func (unavailableRow) Scan(...any) error {
|
||||
return &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
|
||||
}
|
||||
|
||||
func (unavailableDB) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {
|
||||
return pgconn.CommandTag{}, unavailableRow{}.Scan()
|
||||
}
|
||||
|
||||
func (unavailableDB) Query(context.Context, string, ...any) (pgx.Rows, error) {
|
||||
return nil, unavailableRow{}.Scan()
|
||||
}
|
||||
|
||||
func (unavailableDB) QueryRow(context.Context, string, ...any) pgx.Row {
|
||||
return unavailableRow{}
|
||||
}
|
||||
|
||||
func TestSQLUnavailableLoginStopsBeforeSessionCreation(t *testing.T) {
|
||||
queries := sqlc.New(unavailableDB{})
|
||||
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
|
||||
mid := middleware.NewMiddleware(auth, "auth-test")
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("synthetic_user", "Synthetic:password")
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
}
|
||||
|
||||
func TestMiddlewareMalformedAuthWritesExactlyOneError(t *testing.T) {
|
||||
// Invalid syntax must be rejected before asking an auth service or DB.
|
||||
// A nil service deliberately makes an accidental dependency call visible.
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
for _, header := range []string{"", "Basic invalid", "Bearer", "Bearer ",
|
||||
"Bearer invalid token", "Digest invalid"} {
|
||||
t.Run("malformed", func(t *testing.T) {
|
||||
nextCalled := false
|
||||
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { nextCalled = true })
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", header)
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(mid.Auth(next)).ServeHTTP(recorder, request)
|
||||
if nextCalled || recorder.Code != http.StatusUnauthorized {
|
||||
t.Fatal("malformed auth reached business handler or did not yield 401")
|
||||
}
|
||||
if recorder.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
|
||||
t.Fatal("missing contract Bearer challenge")
|
||||
}
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
decoder := json.NewDecoder(recorder.Body)
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
t.Fatal("401 is not one valid JSON object")
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
t.Fatal("middleware wrote more than one response after 401")
|
||||
}
|
||||
if payload.Error.Code != "unauthorized" || payload.Error.RequestID == "" ||
|
||||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
|
||||
t.Fatal("error request ID or code violates contract")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageHTTPAuthRoutingAndLogout(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
userRepo := repository.NewUserRepository(f.queries)
|
||||
chatRepo := repository.NewChatRepository(f.queries, f.pool)
|
||||
chatService := service.NewChatService(chatRepo, userRepo, f.users)
|
||||
messageService := service.NewMessageService(repository.NewMessageRepository(f.queries, f.pool), chatService, f.users)
|
||||
router := httptransport.NewRouter(
|
||||
middleware.NewMiddleware(f.auth, "auth-test"), handler.NewAuthHandler(f.auth),
|
||||
handler.NewHealthHandler(f.pool, f.redis.client),
|
||||
handler.NewChatHandler(chatService), handler.NewUserHandler(f.users),
|
||||
handler.NewMessageHandler(messageService),
|
||||
).Handler()
|
||||
|
||||
call := func(method, path, token string, login bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(method, path, nil)
|
||||
if login {
|
||||
request.SetBasicAuth(user.Username, password)
|
||||
} else if token != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
if recorder.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("auth response missing X-Request-Id")
|
||||
}
|
||||
return recorder
|
||||
}
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
t.Error("auth router panicked; check constructor/handler wiring")
|
||||
}
|
||||
}()
|
||||
response := call("POST", "/api/v1/auth/sessions", "", true)
|
||||
if response.Code != 201 {
|
||||
t.Fatal("Basic login route did not return 201")
|
||||
}
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &session); err != nil ||
|
||||
session.Token == "" || session.TokenType != "Bearer" {
|
||||
t.Fatal("login route returned invalid session")
|
||||
}
|
||||
other := f.session(t, user, password)
|
||||
response = call("GET", "/api/v1/users/me", session.Token, false)
|
||||
if response.Code != 200 || strings.Contains(response.Body.String(), "password") {
|
||||
t.Fatal("Bearer user route failed or exposed password fields")
|
||||
}
|
||||
response = call("DELETE", "/api/v1/auth/sessions/current", session.Token, false)
|
||||
if response.Code != 204 || response.Body.Len() != 0 {
|
||||
t.Fatal("contract logout path must return empty 204")
|
||||
}
|
||||
for _, route := range [][2]string{
|
||||
{"GET", "/api/v1/users/me"}, {"DELETE", "/api/v1/auth/sessions/current"},
|
||||
} {
|
||||
response = call(route[0], route[1], session.Token, false)
|
||||
if response.Code != 401 || response.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
|
||||
t.Fatal("revoked token was accepted or challenged with wrong scheme")
|
||||
}
|
||||
}
|
||||
if response := call("GET", "/api/v1/users/me", other.Token, false); response.Code != 200 {
|
||||
t.Fatal("logout invalidated an independent session of the same user")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Clone a temporary Git snapshot of the current solution and test that clone.
|
||||
|
||||
The user's index, branch, commits and remotes are never changed. Ignored local
|
||||
state is excluded. This validates the working solution, not the remote fork.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def run(args, cwd, env=None, log=None):
|
||||
result = subprocess.run(args, cwd=cwd, env=env, stdout=log or subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=True, timeout=600)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Clean clone command failed; inspect its test log")
|
||||
return result.stdout or ""
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--output", type=Path, required=True)
|
||||
p.add_argument("--measure-budgets", action="store_true", help="include bounded HTTP measurements in the clone")
|
||||
p.add_argument("--pull", choices=("missing", "never", "always"), default="missing")
|
||||
args = p.parse_args()
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
names = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
cwd=ROOT, capture_output=True, check=True).stdout.split(b"\0")
|
||||
paths = sorted({os.fsdecode(name) for name in names if name})
|
||||
manifest = {}
|
||||
summary = {"status": "FAIL", "scope": "temporary Git snapshot of current working tree; not remote HEAD"}
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="lab2-clone-") as directory:
|
||||
temp = Path(directory)
|
||||
# Match the real checkout: an ASCII repository name inside a path
|
||||
# with spaces/Unicode. Docker Desktop Bake currently rejects a
|
||||
# non-ASCII *repository basename* in its session shared-key header.
|
||||
snapshot, clone = temp / "snapshot", temp / "путь с пробелами" / "HighLoad"
|
||||
snapshot.mkdir()
|
||||
clone.parent.mkdir()
|
||||
for name in paths:
|
||||
source = ROOT / name
|
||||
if not source.is_file() and not source.is_symlink():
|
||||
continue
|
||||
# Even an accidentally tracked secret must not enter this fixture.
|
||||
parts = Path(name).parts
|
||||
if name in ("api", "server"):
|
||||
continue # Local compiled binaries are not source dependencies.
|
||||
if "secrets" in parts or "output" in parts or "evidence" in parts or ".venv" in parts:
|
||||
continue
|
||||
if Path(name).name.startswith(".env") and name != ".env.example":
|
||||
continue
|
||||
target = snapshot / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, target, follow_symlinks=False)
|
||||
if not source.is_symlink():
|
||||
manifest[name] = hashlib.sha256(source.read_bytes()).hexdigest()
|
||||
env = os.environ.copy()
|
||||
env.update(GIT_AUTHOR_NAME="Lab2 test snapshot", GIT_AUTHOR_EMAIL="lab2-test@localhost",
|
||||
GIT_COMMITTER_NAME="Lab2 test snapshot", GIT_COMMITTER_EMAIL="lab2-test@localhost")
|
||||
with (output / "clone.log").open("w") as log:
|
||||
run(["git", "init", "--initial-branch=main"], snapshot, env, log)
|
||||
run(["git", "add", "--all"], snapshot, env, log)
|
||||
run(["git", "-c", "commit.gpgsign=false", "commit", "-m", "Temporary acceptance snapshot"], snapshot, env, log)
|
||||
run(["git", "clone", "--no-local", str(snapshot), str(clone)], temp, env, log)
|
||||
if run(["git", "status", "--porcelain"], clone).strip():
|
||||
raise RuntimeError("Clone is not clean")
|
||||
for name in (".env", "secrets", ".venv", "student-tests/output"):
|
||||
if (clone / name).exists():
|
||||
raise RuntimeError("Private local state unexpectedly entered the clone")
|
||||
for name in ("restart.sh", "stop-postgres.sh", "start-postgres.sh", "stop-redis.sh", "start-redis.sh", "setup-tests.sh"):
|
||||
if not os.access(clone / "scripts" / name, os.X_OK):
|
||||
raise RuntimeError("Executable bit lost in clone: " + name)
|
||||
with (output / "dependencies.log").open("w") as log:
|
||||
run([str(clone / "scripts/setup-tests.sh")], clone, log=log)
|
||||
with (output / "verify.log").open("w") as log:
|
||||
verify_args = [str(clone / ".venv/bin/python"), "student-tests/stack.py", "verify",
|
||||
"--output", str(output / "acceptance"), "--pull", args.pull]
|
||||
if args.measure_budgets:
|
||||
verify_args.append("--measure-budgets")
|
||||
verification = subprocess.run(verify_args,
|
||||
cwd=clone, stdout=log, stderr=subprocess.STDOUT, text=True, timeout=1200)
|
||||
summary["acceptance_exit"] = verification.returncode
|
||||
acceptance_path = output / "acceptance/summary.json"
|
||||
if acceptance_path.exists():
|
||||
acceptance = json.loads(acceptance_path.read_text())
|
||||
summary["bootstrap"] = "PASS" if any(x["check"] == "compose-up" and x["status"] == "PASS" for x in acceptance["results"]) else "FAIL"
|
||||
# Fixtures stay ignored; the test runner must not modify source files.
|
||||
if run(["git", "status", "--porcelain"], clone).strip():
|
||||
raise RuntimeError("Tests changed tracked or unignored files in the clone")
|
||||
summary["source_clean_after_tests"] = True
|
||||
summary["status"] = "PASS" if verification.returncode == 0 else "FAIL"
|
||||
if verification.returncode != 0:
|
||||
summary["detail"] = "Clone/bootstrap completed; acceptance tests failed, see acceptance summary"
|
||||
summary["source_files"] = len(manifest)
|
||||
except (OSError, RuntimeError, subprocess.SubprocessError) as error:
|
||||
summary["detail"] = str(error) if isinstance(error, RuntimeError) else type(error).__name__
|
||||
(output / "snapshot-manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
(output / "clone-summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
print(summary["status"] + ": " + str(output / "clone-summary.json"))
|
||||
return 0 if summary["status"] == "PASS" else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare real WAITAOF waits on a new Redis/volume using current Compose settings."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def command(args, timeout=60):
|
||||
process = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if process.returncode:
|
||||
raise RuntimeError("diagnostic command failed: " + " ".join(args[:3]))
|
||||
return process.stdout
|
||||
|
||||
|
||||
def sources():
|
||||
paths = [*ROOT.glob("internal/**/*.go"), *ROOT.glob("cmd/**/*.go"),
|
||||
*ROOT.glob("db/**/*.sql"), ROOT / "compose.yaml", ROOT / "go.mod", ROOT / "go.sum"]
|
||||
return {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in paths if p.is_file() and not p.name.endswith("_test.go")}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
project = "lab2-test-waitaof-" + secrets.token_hex(6)
|
||||
container, volume = project + "-redis", project + "-data"
|
||||
label = "com.docker.compose.project=" + project
|
||||
before = sources()
|
||||
summary = {"project": project, "status": "FAIL", "source_before": before}
|
||||
volume_created = False
|
||||
try:
|
||||
# Read the Compose model in memory. Only the Redis profile is saved;
|
||||
# application environment/credentials never enter diagnostic artifacts.
|
||||
config = json.loads(command(["docker", "compose", "--project-directory", str(ROOT),
|
||||
"-p", project, "-f", str(ROOT / "compose.yaml"),
|
||||
"config", "--format", "json"]))
|
||||
redis = config["services"]["redis"]
|
||||
profile = {"image": redis["image"], "command": redis["command"]}
|
||||
if not isinstance(profile["command"], list):
|
||||
raise RuntimeError("Redis command must be an argv list")
|
||||
image = json.loads(command(["docker", "image", "inspect", profile["image"]]))[0]
|
||||
summary.update(redis_profile=profile, image_id=image["Id"], image_digests=image.get("RepoDigests", []))
|
||||
# Run the inspected image ID, so a mutable tag cannot change mid-run.
|
||||
with socket.socket() as reservation:
|
||||
reservation.bind(("127.0.0.1", 0))
|
||||
port = reservation.getsockname()[1]
|
||||
command(["docker", "volume", "create", "--label", label, volume])
|
||||
volume_created = True
|
||||
command(["docker", "run", "-d", "--name", container, "--label", label,
|
||||
"-p", f"127.0.0.1:{port}:6379", "--mount", f"type=volume,src={volume},dst=/data",
|
||||
image["Id"], *profile["command"]])
|
||||
for _ in range(60):
|
||||
ping = subprocess.run(["docker", "exec", container, "redis-cli", "ping"],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
if ping.returncode == 0 and ping.stdout.strip() == "PONG":
|
||||
break
|
||||
time.sleep(.2)
|
||||
else:
|
||||
raise RuntimeError("test Redis is not ready")
|
||||
with tempfile.TemporaryDirectory(prefix=project + "-") as directory:
|
||||
binary = Path(directory) / "compare-waitaof"
|
||||
command(["go", "build", "-o", str(binary), "./student-tests/diagnostics/waitaof"], timeout=120)
|
||||
env = dict(os.environ, WAITAOF_TEST_REDIS_ADDR=f"127.0.0.1:{port}")
|
||||
process = subprocess.Popen([str(binary), "-output", str(output)], cwd=ROOT, env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
# Per-command deadlines bound the client; 36 sequential samples.
|
||||
try:
|
||||
with (output / "client.log").open("w") as log:
|
||||
for line in process.stdout:
|
||||
log.write(line)
|
||||
log.flush()
|
||||
print(line, end="", flush=True)
|
||||
code = process.wait(timeout=10)
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
summary["client_exit"] = code
|
||||
summary["status"] = "COMPLETE" if code == 0 else "FAIL"
|
||||
except (OSError, RuntimeError, KeyError, ValueError, subprocess.SubprocessError) as error:
|
||||
summary["failure"] = str(error)
|
||||
finally:
|
||||
after = sources()
|
||||
summary["source_after"] = after
|
||||
summary["production_source_changes"] = sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k))
|
||||
inspected = subprocess.run(["docker", "inspect", container], capture_output=True, text=True)
|
||||
if inspected.returncode == 0:
|
||||
owned = json.loads(inspected.stdout)[0]["Config"]["Labels"].get("com.docker.compose.project") == project
|
||||
summary["container_cleanup"] = owned and subprocess.run(
|
||||
["docker", "rm", "-f", container], capture_output=True).returncode == 0
|
||||
else:
|
||||
summary["container_cleanup"] = True
|
||||
summary["volume_cleanup"] = not volume_created or subprocess.run(
|
||||
["docker", "volume", "rm", volume], capture_output=True).returncode == 0
|
||||
if not summary["container_cleanup"] or not summary["volume_cleanup"]:
|
||||
summary["status"] = "FAIL"
|
||||
(output / "runner-summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
||||
print(summary["status"] + ": " + str(output), flush=True)
|
||||
return 0 if summary["status"] == "COMPLETE" else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,206 @@
|
||||
// Standalone experiment; production constructors and timeouts are never used.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func ms(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) }
|
||||
func save(path string, v any) error {
|
||||
b, e := json.MarshalIndent(v, "", " ")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
return os.WriteFile(path, append(b, '\n'), 0600)
|
||||
}
|
||||
func snapshot(c *redis.Client, out, phase string) (map[string]any, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
|
||||
defer cancel()
|
||||
settings := map[string]string{}
|
||||
for _, pattern := range []string{"append*", "*aof*", "no-appendfsync-on-rewrite"} {
|
||||
values, e := c.ConfigGet(ctx, pattern).Result()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for k, v := range values {
|
||||
settings[k] = v
|
||||
}
|
||||
}
|
||||
info, e := c.Info(ctx, "persistence").Result()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
server, e := c.Info(ctx, "server").Result()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = os.WriteFile(filepath.Join(out, "persistence-"+phase+".info"), []byte(info), 0600); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = os.WriteFile(filepath.Join(out, "server-"+phase+".info"), []byte(server), 0600); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
s := map[string]any{"at_utc": time.Now().UTC().Format(time.RFC3339Nano), "aof_settings": settings, "info_persistence": info, "info_server": server}
|
||||
return s, save(filepath.Join(out, "snapshot-"+phase+".json"), s)
|
||||
}
|
||||
|
||||
func measure(c *redis.Client, number, round, budget, pause int) map[string]any {
|
||||
key := "waitaof-probe:" + uuid.NewString()
|
||||
errors := map[string]string{}
|
||||
s := map[string]any{"number": number, "round": round, "waitaof_timeout_ms": budget, "scheduled_pause_ms": pause, "synthetic_key": key, "errors": errors, "local_fsynced": nil, "replicas_fsynced": nil}
|
||||
// Conn pins all commands to one physical connection. IDs before/after also
|
||||
// detect reconnects; such samples are invalid rather than acknowledged.
|
||||
conn := c.Conn()
|
||||
defer conn.Close()
|
||||
initCtx, initCancel := context.WithTimeout(context.Background(), 12*time.Second)
|
||||
before, e := conn.ClientID(initCtx).Result()
|
||||
initCancel()
|
||||
if e != nil {
|
||||
errors["client_id_before"] = e.Error()
|
||||
return s
|
||||
}
|
||||
s["client_id_before"] = before
|
||||
paused := time.Now()
|
||||
time.Sleep(time.Duration(pause) * time.Millisecond)
|
||||
s["actual_pause_ms"] = ms(time.Since(paused))
|
||||
// The pause does not consume any of the command deadline.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
s["write_started_at_utc"] = start.UTC().Format(time.RFC3339Nano)
|
||||
e = conn.Set(ctx, key, "synthetic-waitaof-value", time.Minute).Err()
|
||||
s["set_ms"] = ms(time.Since(start))
|
||||
if e != nil {
|
||||
errors["set"] = e.Error()
|
||||
} else {
|
||||
t := time.Now()
|
||||
deleted, delErr := conn.Del(ctx, key).Result()
|
||||
s["del_ms"] = ms(time.Since(t))
|
||||
s["deleted"] = deleted
|
||||
if delErr != nil {
|
||||
errors["del"] = delErr.Error()
|
||||
} else {
|
||||
if deleted != 1 {
|
||||
errors["deleted_count"] = "expected exactly one newly written key"
|
||||
}
|
||||
t = time.Now()
|
||||
reply, waitErr := conn.Do(ctx, "WAITAOF", 1, 0, budget).Slice()
|
||||
s["waitaof_ms"] = ms(time.Since(t))
|
||||
if waitErr != nil {
|
||||
errors["waitaof"] = waitErr.Error()
|
||||
} else if len(reply) != 2 {
|
||||
errors["reply"] = "expected two counters"
|
||||
} else {
|
||||
local, okLocal := reply[0].(int64)
|
||||
replicas, okReplicas := reply[1].(int64)
|
||||
if !okLocal || !okReplicas {
|
||||
errors["reply"] = "expected integer counters"
|
||||
} else {
|
||||
s["local_fsynced"] = local
|
||||
s["replicas_fsynced"] = replicas
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s["write_delete_wait_ms"] = ms(time.Since(start))
|
||||
after, e := conn.ClientID(ctx).Result()
|
||||
s["client_id_after"] = after
|
||||
if e != nil {
|
||||
errors["client_id_after"] = e.Error()
|
||||
}
|
||||
if before != after {
|
||||
errors["pinned_connection"] = "connection ID changed"
|
||||
}
|
||||
exists, e := conn.Exists(ctx, key).Result()
|
||||
s["exists_after"] = exists
|
||||
if e != nil {
|
||||
errors["exists"] = e.Error()
|
||||
}
|
||||
if exists != 0 {
|
||||
errors["key_remains"] = "synthetic key was not deleted"
|
||||
cleanup, done := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
defer done()
|
||||
if e = conn.Del(cleanup, key).Err(); e != nil {
|
||||
errors["cleanup"] = e.Error()
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func run(out string) error {
|
||||
addr := os.Getenv("WAITAOF_TEST_REDIS_ADDR")
|
||||
if addr == "" {
|
||||
return fmt.Errorf("set WAITAOF_TEST_REDIS_ADDR for a dedicated test Redis")
|
||||
}
|
||||
c := redis.NewClient(&redis.Options{Addr: addr, DialTimeout: 8 * time.Second, ReadTimeout: 8 * time.Second, WriteTimeout: 8 * time.Second, PoolTimeout: 8 * time.Second, ContextTimeoutEnabled: true, MaxRetries: -1, PoolSize: 1})
|
||||
defer c.Close()
|
||||
before, e := snapshot(c, out, "before")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
file, e := os.OpenFile(filepath.Join(out, "samples.jsonl"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer file.Close()
|
||||
encoder := json.NewEncoder(file)
|
||||
pauses := []int{0, 137, 359, 613, 887, 1109}
|
||||
samples := []map[string]any{}
|
||||
invalid := 0
|
||||
for round := 1; round <= 3; round++ {
|
||||
for i := range pauses {
|
||||
pause := pauses[(i+round-1)%len(pauses)]
|
||||
budgets := []int{1000, 3000}
|
||||
if (round+i)%2 == 0 {
|
||||
budgets = []int{3000, 1000}
|
||||
}
|
||||
for _, budget := range budgets {
|
||||
s := measure(c, len(samples)+1, round, budget, pause)
|
||||
samples = append(samples, s)
|
||||
if len(s["errors"].(map[string]string)) > 0 {
|
||||
invalid++
|
||||
}
|
||||
if e = encoder.Encode(s); e != nil {
|
||||
return e
|
||||
}
|
||||
if e = file.Sync(); e != nil {
|
||||
return e
|
||||
}
|
||||
fmt.Printf("sample=%d round=%d timeout_ms=%d pause_ms=%d wait_ms=%v local=%v replicas=%v errors=%d\n", len(samples), round, budget, pause, s["waitaof_ms"], s["local_fsynced"], s["replicas_fsynced"], len(s["errors"].(map[string]string)))
|
||||
}
|
||||
}
|
||||
}
|
||||
after, e := snapshot(c, out, "after")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
result := map[string]any{"complete": true, "invalid_samples": invalid, "settings": map[string]any{"network_timeout_ms": 8000, "command_deadline_ms": 12000, "retries": 0, "pool_size": 1, "repetitions_per_pause_per_timeout": 3, "scheduled_pauses_ms": pauses, "ordering": "alternate timeout order and rotate pauses each round"}, "before": before, "after": after, "samples": samples}
|
||||
if e = save(filepath.Join(out, "experiment.json"), result); e != nil {
|
||||
return e
|
||||
}
|
||||
if invalid > 0 {
|
||||
return fmt.Errorf("%d invalid samples; inspect errors in raw results", invalid)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func main() {
|
||||
out := flag.String("output", "", "existing dedicated experiment directory")
|
||||
flag.Parse()
|
||||
if *out == "" {
|
||||
fmt.Fprintln(os.Stderr, "-output is required")
|
||||
os.Exit(2)
|
||||
}
|
||||
if e := run(*out); e != nil {
|
||||
fmt.Fprintln(os.Stderr, e)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
config.local.json
|
||||
output/
|
||||
*.secret
|
||||
@@ -0,0 +1,230 @@
|
||||
# Проверки lab2 и заготовки исследований на 5
|
||||
|
||||
Для завершённого трека 2 используется отдельный воспроизводимый запуск:
|
||||
|
||||
```sh
|
||||
.venv/bin/python student-tests/lab2/research.py --output evidence/grade5-sql-NEW
|
||||
```
|
||||
|
||||
Из корня репозитория он сам собирает sqlprobe, создаёт два изолированных
|
||||
PostgreSQL/volumes с синтетическими credentials, выполняет сравнение AB/BA на
|
||||
100k сообщений, backup/restore и restart новой цели, затем удаляет свои ресурсы.
|
||||
Образ postgres:18 должен присутствовать локально. Требуются Docker, Go из
|
||||
go.mod и Python-окружение scripts/setup-tests.sh. Output должен быть новым.
|
||||
CSV и агрегаты таблиц из сохранённого indexes.json пересчитываются без нового
|
||||
измерения: `python3 student-tests/lab2/summarize_research.py <output-directory>`.
|
||||
Точный метод и проверенные результаты —
|
||||
[исследовательский отчёт](../../evidence/grade5-sql-2026-10-28-verified/REPORT.md).
|
||||
Общая регрессия API по-прежнему запускается через student-tests/stack.py verify.
|
||||
Режим sqlprobe compare и приведённые ниже отдельные hooks остаются прототипами
|
||||
и точками расширения, а не подменой полного исследовательского запуска.
|
||||
|
||||
Ниже — тесты и тестовые адаптеры. Код приложения, обязательный контракт,
|
||||
публичные tests/ и основной Compose не меняются. Переносимый runner и активный
|
||||
workflow Gitea описаны в [RUNNING.md](../RUNNING.md).
|
||||
Основание: [требования лабораторной](../../README.md), README/COURSE,
|
||||
contracts/README и OpenAPI преподавателя. Ожидаемые API-статусы и границы
|
||||
не подгоняются под текущие ответы сервера.
|
||||
|
||||
## Что уже можно запускать
|
||||
|
||||
Python 3.9+, стандартная библиотека. Для SQL-адаптера нужен Go с зависимостями
|
||||
проекта и доступ к явно выбранному тестовому PostgreSQL. Новых Go/Python
|
||||
зависимостей этот набор не добавляет.
|
||||
|
||||
~~~sh
|
||||
python3 student-tests/lab2/run.py --list
|
||||
python3 -m unittest discover -s student-tests/lab2 -p test_harness.py -v
|
||||
go test ./student-tests/lab2/sqlprobe -count=1
|
||||
|
||||
export LAB2_BASE_URL=http://127.0.0.1:8080
|
||||
python3 student-tests/lab2/run.py \
|
||||
--suite business-boundaries --suite business-cursors --suite read-after-write
|
||||
~~~
|
||||
|
||||
Команды HTTP создают синтетических пользователей, чаты и сообщения. Удаления
|
||||
через API нет, поэтому нужен отдельный учебный стенд. Бенчмарки не следует
|
||||
проводить на общей/production БД. Этот runner сам Docker-стенд не поднимает.
|
||||
|
||||
`business-cursors` проверяет отдельно историю сообщений и список чатов:
|
||||
обход GET /chats с limit=2, точный порядок/состав, отсутствие дублей и чужих
|
||||
объектов, чужой cursor, смену limit 1 → 100 и завершение списка.
|
||||
`business-boundaries` включает совместимые JSON/UTF-8 cases из
|
||||
validation_edges.py с регистрационным password и Bearer; тела запросов с
|
||||
паролем в отчёт не сохраняются. `read-after-write` проверяет 100 сообщений от
|
||||
10 участников с config.concurrency одновременными запросами (по умолчанию 4).
|
||||
|
||||
`PASS` означает прохождение выбранного сценария, `FAIL` — наблюдаемое нарушение,
|
||||
`BLOCKED` — нет конфигурации/адаптера/выбранного трека. Exit: 0/1/2 соответственно;
|
||||
FAIL имеет приоритет над BLOCKED. Без --suite ничего не запускается. Пустой
|
||||
config.example.json не выдаёт зелёный результат. Отсутствующие Redis и hooks
|
||||
также не засчитываются как успешная проверка.
|
||||
|
||||
## Матрица покрытия
|
||||
|
||||
| Блок чек-листа | Автоматические проверки | Где потребуется адаптация/ручное подтверждение |
|
||||
| --- | --- | --- |
|
||||
| 1. Auth и ошибки | auth, postgres-failure; существующие Go/auth_tests | Исправления приложения делает автор |
|
||||
| 2. Воспроизводимость | persistence, compose_action, пример CI | Реальный restart.sh, чистый clone, площадка CI |
|
||||
| 3. Реальный Redis/Valkey | cache-usage, cache-failure, cache-restart | Роль, адрес, namespace и metrics adapter |
|
||||
| 4. Бюджеты | query-timeout, pool-timeout | Настоящий SQL lock и насыщение APPLICATION pool |
|
||||
| 5. SQL ≥10k | sql-plan: реальный repository SQL, первая/глубокая страницы | Обоснование плана и бюджета чтения |
|
||||
| 6. Регрессия | business-*, read-after-write, auth/expiry/persistence/dependency | Политика конкурентных вставок и дополнительные крайние случаи |
|
||||
| 7A. Трек cache | cache-experiment + restart/read-after-write | Детерминированный baseline/protected, счётчики, повторы |
|
||||
| 7B. Трек SQL | sql-experiment, backup-restore, sqlprobe seed | Backup/restore adapters, ресурсы, интерпретация результатов |
|
||||
| 8. Сдача | Публичные make check/validate/test, образец application CI | REPORT/PR, источники/ИИ, commit, secrets, защита |
|
||||
|
||||
В отчёте, корректности экспериментального вывода и объяснении на защите
|
||||
нет достоверной автоматической замены. Заготовки не выставляют оценку 5.
|
||||
Это также не полный fuzz всех UUID/HTTP framing/JSON и вариантов 100 участников.
|
||||
Зелёные офлайн self-tests проверяют инструментарий, а не приложение.
|
||||
|
||||
## Конфигурация
|
||||
|
||||
Скопируй config.example.json в config.local.json (он игнорируется Git).
|
||||
Укажи base_url, expiry_base_url отдельного API с фактическим TTL=2,
|
||||
cache_policy (`critical`/`fallback`), cache_target (`history`/`chat`/`me`),
|
||||
track (`cache`/`sql`) и выбранные hooks. LAB2_BASE_URL/LAB2_EXPIRY_BASE_URL
|
||||
могут переопределять адреса. Пути команд hooks разрешаются относительно
|
||||
директории config-файла. Формат hook — массив argv, **shell не вызывается**.
|
||||
Не клади пароли/токены в argv или JSON: строки подключения передаются через env.
|
||||
|
||||
~~~sh
|
||||
python3 student-tests/lab2/run.py --config student-tests/lab2/config.local.json \
|
||||
--suite all --allow-hooks --output student-tests/lab2/output/full.json
|
||||
~~~
|
||||
|
||||
`all` выбирает общий уровень 3/4 и один указанный трек. При track=null он
|
||||
добавляет BLOCKED research-track; два исследовательских трека одновременно
|
||||
для оценки не требуются. Тяжёлые SQL-операции запускаются только выбранной
|
||||
suite и с явно переданной тестовой БД. Порог данных 10k/100k не уменьшается
|
||||
автоматически ради прохождения. Размер пула/таймаут в секундах и scan budget —
|
||||
выбранные инженерные параметры, а не магические числа из задания.
|
||||
|
||||
Существующие проверки не дублируются: auth, expiry, persistence и dependency
|
||||
используют student-tests/auth_contract.py и неизменённый teacher client.
|
||||
Публичный make test и Go tests остаются отдельными обязательными шагами.
|
||||
|
||||
## Договорённости hooks
|
||||
|
||||
Все hooks запускаются только с --allow-hooks и только после явной настройки.
|
||||
Обычный успешный hook возвращает 0; ещё не реализованный — 2 (BLOCKED).
|
||||
Остальные ошибки — FAIL. stdout/stderr инфраструктуры не копируются в отчёт.
|
||||
Recovery вызывается даже при частично неудавшемся failure hook; сам hook
|
||||
должен корректно завершаться и при повторном вызове. Восстановление и готовность
|
||||
обязательны. Уменьшение срока жизни сессии рестартом недопустимо.
|
||||
|
||||
- restart_stack: перезапустить API и ВСЕ используемые stores, сохранить volumes;
|
||||
прикладывать реальные started_at/volume до и после, а не no-op.
|
||||
- stop/start_postgres и stop/start/restart_cache: управлять только своим тестовым
|
||||
проектом. [compose_action.py](adapters/compose_action.py) — рабочий пример для
|
||||
именованных disposable проектов; параметры сервисов/Compose-файлов явные.
|
||||
Он не создаёт стенд и никогда не выполняет down -v или flush.
|
||||
- block_query/unblock_query: держать/снимать блокировку SQL, действительно
|
||||
мешающую запросу API. Например ACCESS EXCLUSIVE на нужной таблице в отдельной
|
||||
управляемой транзакции. Не блокировать готовую БД навсегда; иметь cleanup.
|
||||
- exhaust_pool/release_pool: занять ВСЕ соединения именно пула приложения.
|
||||
Несколько независимых psql-соединений не исчерпывают pgxpool приложения!
|
||||
- evict_cache: удалить только ключи своего синтетического namespace/fixture,
|
||||
не FLUSHALL. Должен гарантированно охлаждать выбранную cached operation.
|
||||
- metrics: один JSON stdout с **настоящими накопительными целочисленными**
|
||||
sql_queries/cache_hits. Runner измеряет delta; сброс счётчика — ошибка.
|
||||
Определи область счётчиков и исключи постороннюю нагрузку. Не выводи ключи,
|
||||
URL с credentials, username/password, токены или данные сообщений.
|
||||
- prepare_cache_baseline/protected: переключить реальное поведение baseline/
|
||||
защиты на том же workload и ресурсах, дождаться готовности. Одного вывода
|
||||
«защита включена» недостаточно.
|
||||
- backup_database/restore_database: настоящий backup и restore в явно указанный
|
||||
пустой целевой storage. Никакого восстановления поверх источника.
|
||||
|
||||
Заготовка собственного hook: [custom.example.py](adapters/custom.example.py).
|
||||
Она намеренно возвращает BLOCKED, пока ты не привяжешь её к реализации.
|
||||
Пример массива для Compose (пути относительно config.local.json):
|
||||
|
||||
~~~json
|
||||
["python3", "adapters/compose_action.py", "--project", "lab2-test-dev", "--file", "../../compose.yaml", "--file", "/path/to/test.override.yaml", "--evidence", "output/restarts.jsonl", "restart-stack"]
|
||||
~~~
|
||||
|
||||
В override должны быть собственные порты, secrets и volume тестового проекта.
|
||||
Остановка реальных рабочих сервисов не нужна для этих тестов.
|
||||
|
||||
## SQL-план и трек 2
|
||||
|
||||
LAB2_TEST_DATABASE_URL содержит DSN отдельной тестовой БД. В argv DSN не передаётся.
|
||||
Примеры ниже предполагают, что оператор уже безопасно задал эту env-переменную.
|
||||
|
||||
~~~sh
|
||||
python3 student-tests/lab2/run.py --suite sql-plan --output student-tests/lab2/output/plan.json
|
||||
python3 student-tests/lab2/run.py --suite sql-experiment --output student-tests/lab2/output/indexes.json
|
||||
~~~
|
||||
|
||||
SQL-адаптер создаёт свежую lab2_test_* схему, применяет реальные embedded Goose
|
||||
миграции, генерирует 10k/100k сообщений с распределением чатов 70/20/6/3/1%.
|
||||
Вызов существующего MessageRepository фиксирует реальный sqlc SQL и параметры;
|
||||
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) выполняется для первой и глубокой страниц.
|
||||
OFFSET используется только при выборе fixture cursor, не в измеряемом запросе.
|
||||
Бюджет учитывает строки, отфильтрованные под LIMIT, и Actual Loops; это эвристика
|
||||
настройки теста, а не замена прочтению самого плана. Generic prepared plans и
|
||||
другие распределения/состояния cache надо исследовать отдельно при необходимости.
|
||||
|
||||
compare меняет индексы ТОЛЬКО внутри своей свежей схемы: chat_id против
|
||||
(chat_id,created_at,id), фиксирует планы/размер индекса и p50/p95/p99 чтения и
|
||||
вставки 200 сообщений с COMMIT. Есть 3 warmup-запроса и заданное число повторов.
|
||||
Очистка вставок может оставить bloat; порядок вариантов и прогретость влияют
|
||||
на результат. Это исходная методика, которую нужно обосновать/повторить,
|
||||
а не гарантированное доказательство превосходства индекса. При обычном
|
||||
завершении схема удаляется; при SIGKILL может потребоваться ручная очистка
|
||||
только созданного тестового namespace. Сбой cleanup не считается PASS.
|
||||
|
||||
Для backup/restore нужен сохраняемый источник с 100k сообщений. Команда seed
|
||||
**явно оставляет** новую тестовую схему и сообщает её имя без DSN:
|
||||
|
||||
~~~sh
|
||||
# LAB2_SQL_DATABASE_URL — env выбранной тестовой БД, не строка в аргументах.
|
||||
go run ./student-tests/lab2/sqlprobe -mode seed -rows 100000 -schema lab2_test_backup_fixture
|
||||
~~~
|
||||
|
||||
Задай sql.source_schema/restore_schema этим именем, LAB2_TEST_DATABASE_URL
|
||||
источником, LAB2_RESTORED_DATABASE_URL новым целевым storage, подключи backup/
|
||||
restore hooks и запусти --suite backup-restore --allow-hooks. Перед тестом
|
||||
целевые application tables должны отсутствовать. Источник на время проверки
|
||||
должен быть без посторонних записей. Бэкап-файл не добавляется в Git/evidence.
|
||||
|
||||
snapshot использует read-only repeatable-read транзакцию и сравнивает количества
|
||||
и SHA-256 упорядоченного содержимого четырёх PostgreSQL-таблиц: users, chats,
|
||||
chat_members, messages. Сессии теперь в Redis; этот SQL backup не обещает их
|
||||
восстановления. Пароли/hash не печатаются: только агрегаты/digest. Состояние источника проверяется повторно;
|
||||
источник и цель должны иметь разные database identity. Это предохранители,
|
||||
но они не доказывают новый volume: приложи создание целевого storage и его scope.
|
||||
В отчёте отдельно объясни время восстановления и возможную потерю данных.
|
||||
|
||||
## Кэш и трек 1
|
||||
|
||||
Выбери cache_experiment.scenario = stale_read или stampede. Для stampede задай
|
||||
обоснованный max_protected_sql_queries с учётом auth и области метрик.
|
||||
Runner синхронизирует конкурентные чтения, измеряет SQL/cache-hit delta и
|
||||
latency до/после; для stale read требуется действительно увидеть отсутствие
|
||||
подтверждённого сообщения. Произвольная ошибка сети не засчитывается как stale read.
|
||||
Защита должна пройти read-after-write и restart cache. Переключение вариантов,
|
||||
scope метрик, размер/прогрев набора данных и повторы остаются частью методики.
|
||||
Под свою выбранную cached operation адаптируй cache_read/fixtures в одном месте.
|
||||
|
||||
## CI и ручная приёмка
|
||||
|
||||
[ci.application.example.yml](ci.application.example.yml) — неактивированный
|
||||
пример job: настоящая PostgreSQL, Go storage/migration tests без пропусков,
|
||||
сборка, миграции, HTTP smoke/business/auth и sql-plan. Redis и исследовательские
|
||||
hooks туда подключаются после выбора реализации. Файл размещён среди тестов;
|
||||
основной workflow не менялся. Для Gitea/GitLab используй эквивалент своей площадки.
|
||||
|
||||
Отдельно нужны REPORT.md/описание архитектуры и источников/ИИ, переносимый
|
||||
scripts/restart.sh, чистый clone, версии/ресурсы/commit, реальные доказательства
|
||||
действий hooks, отсутствие secrets в Git и объяснение результатов на защите.
|
||||
Рекомендации production (разделение ролей, secret manager и т.п.) не превращены
|
||||
здесь в новые обязательные критерии lab2. Результат тестов не заменяет эти пункты.
|
||||
# Переносимый запуск
|
||||
|
||||
Для текущего PostgreSQL/Redis/auth-набора есть готовый локальный и Gitea сценарий:
|
||||
[RUNNING.md](../RUNNING.md). Он поднимает отдельный стенд, выполняет проверки
|
||||
и очищает свои ресурсы. Заготовки исследования на 5 подключаются отдельно.
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit test-project restart/outage adapter. Never removes volumes/data."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--project", required=True)
|
||||
p.add_argument("--file", action="append", type=Path, required=True)
|
||||
p.add_argument("--api-service", default="api")
|
||||
p.add_argument("--database-service", default="postgres")
|
||||
p.add_argument("--cache-service", default="redis")
|
||||
p.add_argument("--evidence", type=Path)
|
||||
p.add_argument("action", choices=("restart-stack", "stop-db", "start-db", "stop-cache", "start-cache", "restart-cache"))
|
||||
args = p.parse_args()
|
||||
if not args.project.startswith(("lab2-test-", "highload-auth-retest-", "highload-lab2-test-")):
|
||||
print("Use an explicitly named disposable test project (lab2-test-*).", file=sys.stderr)
|
||||
return 2
|
||||
base = ["docker", "compose", "--project-name", args.project]
|
||||
for file in args.file:
|
||||
base.extend(("--file", str(file.resolve())))
|
||||
|
||||
def call(argv):
|
||||
result = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=70)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Docker action failed; output suppressed")
|
||||
return result.stdout
|
||||
|
||||
config = json.loads(call(base + ["config", "--format", "json"]))
|
||||
services = config["services"]
|
||||
stores = [args.database_service]
|
||||
if args.cache_service in services:
|
||||
stores.append(args.cache_service)
|
||||
elif "cache" in args.action:
|
||||
print("Cache service is not configured; adapt --cache-service.", file=sys.stderr)
|
||||
return 2
|
||||
targets = [args.api_service] + stores if args.action == "restart-stack" else [
|
||||
args.database_service if args.action.endswith("db") else args.cache_service]
|
||||
if any(name not in services for name in targets):
|
||||
return 2
|
||||
|
||||
def snapshot():
|
||||
result = {}
|
||||
for service in targets:
|
||||
ident = call(base + ["ps", "--all", "--quiet", service]).strip()
|
||||
if not ident or "\n" in ident:
|
||||
raise RuntimeError("expected one existing container per test service")
|
||||
raw = json.loads(call(["docker", "inspect", ident]))[0]
|
||||
if raw["Config"]["Labels"].get("com.docker.compose.project") != args.project:
|
||||
raise RuntimeError("container project mismatch")
|
||||
result[service] = {"id": ident, "started_at": raw["State"]["StartedAt"],
|
||||
"running": raw["State"]["Running"],
|
||||
"volumes": [mount["Name"] for mount in raw["Mounts"] if mount["Type"] == "volume"]}
|
||||
return result
|
||||
|
||||
before = snapshot()
|
||||
operation = "restart" if args.action.startswith("restart") else args.action.split("-")[0]
|
||||
call(base + [operation] + targets)
|
||||
proof = {"action": args.action, "project": args.project, "before": before, "after": snapshot()}
|
||||
if args.evidence:
|
||||
args.evidence.parent.mkdir(parents=True, exist_ok=True)
|
||||
with args.evidence.open("a") as output:
|
||||
output.write(json.dumps(proof) + "\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError):
|
||||
print("Test infrastructure action failed; private details suppressed.", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Copy and implement one explicit test adapter; never prints credentials."""
|
||||
import sys
|
||||
|
||||
# Expected metrics stdout: {"sql_queries": 1234, "cache_hits": 56}.
|
||||
# Counts must come from the real observed implementation, not constants here.
|
||||
# Other hooks: evict only this test namespace; hold/release a real SQL lock or
|
||||
# all APPLICATION pool connections; switch baseline/protected implementation;
|
||||
# back up the source and restore only to the explicitly empty test target.
|
||||
# See README.md for contracts and cleanup obligations. No destructive defaults.
|
||||
print("BLOCKED: implement the selected adapter for the chosen application/storage.", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded closed-loop HTTP latency matrix. Tokens stay only in memory."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
sys.path[:0]=[str(ROOT/'tests'),str(ROOT/'student-tests'),str(ROOT/'student-tests/lab2')]
|
||||
from client import Client,Failure
|
||||
from auth_contract import basic
|
||||
from resources import Sampler
|
||||
spec=importlib.util.spec_from_file_location('budget_harness',ROOT/'student-tests/lab2/run.py')
|
||||
harness=importlib.util.module_from_spec(spec);spec.loader.exec_module(harness)
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--base-url',required=True);p.add_argument('--output',type=Path,required=True)
|
||||
p.add_argument('--repeats',type=int,default=2);p.add_argument('--per-worker',type=int,default=3)
|
||||
p.add_argument('--history',type=int,default=1000);p.add_argument('--client-timeout',type=float,default=15)
|
||||
a=p.parse_args()
|
||||
if not 2<=a.repeats<=3 or not 2<=a.per_worker<=10 or not 1000<=a.history<=10000:p.error('bounded profile: repeats 2..3, per-worker 2..10, history 1000..10000')
|
||||
a.output.mkdir(parents=True,exist_ok=False)
|
||||
factory=lambda:Client(a.base_url,timeout=a.client_timeout)
|
||||
c=factory();actors=[c.user('bud'+uuid.uuid4().hex[:4]) for _ in range(10)]
|
||||
chat=c.call('POST','/api/v1/chats',201,actor=actors[0],body={'title':'Budget history','member_ids':[x['id'] for x in actors]},schema='Chat')['json']
|
||||
for index in range(a.history):c.message(actors[0],chat,'history fixture '+str(index)+' '+('x'*100))
|
||||
cursor=None
|
||||
traversed=set()
|
||||
for _ in range((a.history*8//10)//100):
|
||||
path='/api/v1/chats/'+chat['id']+'/messages?limit=100'+('&cursor='+cursor if cursor else '')
|
||||
page=c.call('GET',path,actor=actors[0],schema='MessagePage')['json']
|
||||
ids={m['id'] for m in page['items']}
|
||||
if traversed & ids:raise RuntimeError('deep fixture repeated a page')
|
||||
traversed.update(ids);cursor=page['next_cursor']
|
||||
if not cursor or len(traversed)!=((a.history*8//10)//100)*100:raise RuntimeError('deep-page fixture lacks correct cursor position')
|
||||
path='/api/v1/chats/'+chat['id']+'/messages'
|
||||
names=['registration','login','me','create_chat','send_message','history_first','history_deep','logout']
|
||||
samples=[];phases=[];resource_errors={};resources={}
|
||||
samplers={}
|
||||
config=json.loads(os.environ.get('LAB2_RESOURCE_CONTAINERS','{}'))
|
||||
for role,entry in config.items():
|
||||
sampler=Sampler(entry['name'],1.0);samplers[role]=(sampler,entry['cpus']);sampler.thread.start()
|
||||
began=time.monotonic()
|
||||
try:
|
||||
for concurrency in [1,5,10]:
|
||||
# Logout credentials are prepared before measuring the logout phase;
|
||||
# preparation latency is not misreported as logout throughput.
|
||||
logout_tokens=[[] for _ in range(concurrency)]
|
||||
for worker in range(concurrency):
|
||||
actor=actors[worker]
|
||||
for _ in range(1+a.repeats*a.per_worker):
|
||||
session=c.call('POST','/api/v1/auth/sessions',201,headers=basic(actor['registration']['username'],actor['registration']['password']),schema='Session')['json']
|
||||
logout_tokens[worker].append(session['token'])
|
||||
for operation in names:
|
||||
for repeat in range(0,a.repeats+1):
|
||||
count=1 if repeat==0 else a.per_worker
|
||||
barrier=threading.Barrier(concurrency)
|
||||
phase_clients=[factory() for _ in range(concurrency)]
|
||||
def worker(number):
|
||||
local=phase_clients[number];actor=actors[number];records=[];barrier.wait(timeout=30)
|
||||
for request in range(count):
|
||||
start=time.monotonic();status=None;kind=None
|
||||
try:
|
||||
if operation=='registration':result=local.call('POST','/api/v1/users',201,body={'username':'budget_'+uuid.uuid4().hex[:20],'display_name':'Budget fixture','password':'Synthetic:password-for-measurement'},schema='User')
|
||||
elif operation=='login':result=local.call('POST','/api/v1/auth/sessions',201,headers=basic(actor['registration']['username'],actor['registration']['password']),schema='Session')
|
||||
elif operation=='me':result=local.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
elif operation=='create_chat':result=local.call('POST','/api/v1/chats',201,actor=actor,body={'title':'Unique '+uuid.uuid4().hex,'member_ids':[actor['id']]},schema='Chat')
|
||||
elif operation=='send_message':result=local.message(actor,chat,'Synthetic '+uuid.uuid4().hex+' '+('x'*80))
|
||||
elif operation=='history_first':result=local.call('GET',path+'?limit=50',actor=actor,schema='MessagePage')
|
||||
elif operation=='history_deep':result=local.call('GET',path+'?limit=50&cursor='+cursor,actor=actor,schema='MessagePage')
|
||||
else:result=local.call('DELETE','/api/v1/auth/sessions/current',204,actor=dict(actor,token=logout_tokens[number].pop()))
|
||||
status=result['status']
|
||||
except TimeoutError:kind='client_timeout'
|
||||
except Failure as exc:
|
||||
message=str(exc);match=re.search(r'received (\d+)',message)
|
||||
if match:status=int(match.group(1));kind='http_'+str(status)
|
||||
else:kind='client_timeout' if 'Timeout' in message else ('transport' if 'connection/TLS' in message else 'contract')
|
||||
except OSError:kind='transport'
|
||||
records.append({'operation':operation,'clients':concurrency,'repeat':repeat,'warmup':repeat==0,'worker':number,'request':request,'elapsed_ms':1000*(time.monotonic()-start),'status':status,'error':kind,'success':kind is None})
|
||||
return records
|
||||
start=time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
records=[row for group in pool.map(worker,range(concurrency)) for row in group]
|
||||
elapsed=time.monotonic()-start;samples.extend(records)
|
||||
phases.append({'operation':operation,'clients':concurrency,'repeat':repeat,'warmup':repeat==0,'requests':len(records),'elapsed_seconds':elapsed,'successful_rps':sum(r['success'] for r in records)/elapsed,'errors':dict(Counter(r['error'] for r in records if r['error']))})
|
||||
print(operation,'clients='+str(concurrency),'complete',flush=True)
|
||||
finally:
|
||||
ended=time.monotonic()
|
||||
for role,(sampler,cpus) in samplers.items():
|
||||
try:resources[role]=sampler.finish(began,ended,cpus)
|
||||
except RuntimeError as exc:resource_errors[role]=str(exc)
|
||||
measured=[r for r in samples if not r['warmup']];table=[]
|
||||
for concurrency in [1,5,10]:
|
||||
for operation in names:
|
||||
rows=[r for r in measured if r['operation']==operation and r['clients']==concurrency];ok=[r for r in rows if r['success']]
|
||||
elapsed=sum(p['elapsed_seconds'] for p in phases if not p['warmup'] and p['operation']==operation and p['clients']==concurrency)
|
||||
table.append({'operation':operation,'clients':concurrency,'requests':len(rows),'successes':len(ok),'errors':dict(Counter(r['error'] for r in rows if r['error'])),'elapsed_seconds':elapsed,'successful_rps':len(ok)/elapsed,'success_latency_ms':harness.percentiles([r['elapsed_ms']/1000 for r in ok]) if ok else None,'all_request_latency_ms':harness.percentiles([r['elapsed_ms']/1000 for r in rows])})
|
||||
report={'generator':'Python urllib public Client; closed loop, no retries, concurrency is clients not arrival rate','method':{'concurrency':[1,5,10],'repeats':a.repeats,'requests_per_worker_per_repeat':a.per_worker,'warmup_requests_per_worker_per_operation':1,'initial_history_messages':a.history,'deep_cursor_after_messages':((a.history*8//10)//100)*100,'message_payload_codepoints':123,'message_payload_padding_chars':80,'seed_payload_padding_chars':100,'client_timeout_seconds':a.client_timeout,'limits':config},'elapsed_seconds':ended-began,'table':table,'phases':phases,'samples':samples,'resources':resources,'resource_errors':resource_errors,'internal_sql_or_pool_times':'not instrumented: HTTP latency is not storage latency','limitations':['Small sample, p99 often equals observed maximum; no p99.9 or SLO claims.','Closed loop has coordinated omission and does not measure maximum capacity.','HTTP elapsed includes client validation and connection/scheduling overhead.','Resource sampler executes inside cgroups; sampled peaks include sampling overhead.','History and database grow during create/write operations; only seeded cursor position is fixed.']}
|
||||
(a.output/'results.json').write_text(json.dumps(report,indent=2))
|
||||
lines=['# HTTP latency matrix','','Preliminary closed-loop measurements, not selected application budgets.','','| Operation | Clients | n | Errors | Successful RPS | p50 ms | p95 ms | p99 ms |','|---|---:|---:|---:|---:|---:|---:|---:|']
|
||||
for row in table:
|
||||
t=row['success_latency_ms'] or dict(p50=0,p95=0,p99=0);lines.append('| %s | %d | %d | %d | %.2f | %.2f | %.2f | %.2f |'%(row['operation'],row['clients'],row['requests'],row['requests']-row['successes'],row['successful_rps'],t['p50'],t['p95'],t['p99']))
|
||||
lines+=['','Full conditions, warmup/error timings and CPU/RAM samples: results.json. HTTP times are not SQL times. Small n does not support stable tail estimates.']
|
||||
(a.output/'TABLE.md').write_text('\n'.join(lines)+'\n')
|
||||
failures=any(not r['success'] for r in samples) or bool(resource_errors) or any(v.get('oom_kill_count',0)>0 for v in resources.values())
|
||||
print('FAIL' if failures else 'COMPLETE',flush=True)
|
||||
return 1 if failures else 0
|
||||
|
||||
if __name__=='__main__':raise SystemExit(main())
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Additional lab2 API cases, using the unchanged teacher client."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import LAB, check, timestamp
|
||||
from validation_edges import acceptance as json_acceptance
|
||||
|
||||
|
||||
def message_headers():
|
||||
return {"Idempotency-Key": uuid.uuid4().hex} if LAB >= 3 else {}
|
||||
|
||||
|
||||
def room(c, actor, members=None, title="Lab2 business fixture"):
|
||||
return c.call("POST", "/api/v1/chats", 201, actor=actor,
|
||||
body={"title": title, "member_ids": members or [actor["id"]]}, schema="Chat")["json"]
|
||||
|
||||
|
||||
def history(c, actor, chat, limit=100):
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=" + str(limit)
|
||||
items, cursors = [], set()
|
||||
for _ in range(2000):
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
check(len({x["id"] for x in items}) == len(items), "history duplicates message IDs")
|
||||
return items
|
||||
check(cursor not in cursors, "cursor cycle")
|
||||
cursors.add(cursor)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=" + str(limit) + "&cursor=" + quote(cursor, safe="")
|
||||
raise AssertionError("history traversal exceeded test bound")
|
||||
|
||||
|
||||
def boundaries(c):
|
||||
actor, other = c.user("bounds"), c.user("other")
|
||||
for title in ("", " \t\n", "😀" * 101):
|
||||
c.call("POST", "/api/v1/chats", 400, actor=actor,
|
||||
body={"title": title, "member_ids": [actor["id"]]})
|
||||
for members in ([], [other["id"]], [actor["id"], actor["id"]],
|
||||
[actor["id"], str(uuid.uuid4())], [actor["id"], "invalid"]):
|
||||
c.call("POST", "/api/v1/chats", 400, actor=actor,
|
||||
body={"title": "Invalid members", "member_ids": members})
|
||||
chat = room(c, actor, title="😀" * 100)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
for text in ("", " \t\n", "😀" * 4001):
|
||||
c.call("POST", path, 400, actor=actor, body={"text": text}, headers=message_headers())
|
||||
message = c.message(actor, chat, "😀" * 4000)["json"]
|
||||
check(message["text"] == "😀" * 4000, "Unicode message boundary changed")
|
||||
c.call("POST", path, 400, actor=actor, body={"text": "forged", "sender_id": other["id"]}, headers=message_headers())
|
||||
for limit in ("0", "101", "-1", "abc", ""):
|
||||
c.call("GET", path + "?limit=" + limit, 400, actor=actor)
|
||||
for raw in (b'{"text":"x","extra":1}', b'{"Text":"x"}', b'{"text":null}',
|
||||
b'{"text":1}', b'{"text":"x"} {}', b'{"text":"\xff"}'):
|
||||
c.call("POST", path, 400, actor=actor, raw=raw,
|
||||
headers={"Content-Type": "application/json", **message_headers()})
|
||||
for target, body in (("/api/v1/chats", {"title": "Media", "member_ids": [actor["id"]]}),
|
||||
(path, {"text": "Media"})):
|
||||
c.call("POST", target, 415, actor=actor, body=body,
|
||||
headers={"Content-Type": "text/plain", **(message_headers() if target == path else {})})
|
||||
c.call("GET", "/api/v1/does-not-exist", 404, actor=actor)
|
||||
return json_acceptance(c)
|
||||
|
||||
|
||||
def chat_pagination(c):
|
||||
owner, outsider = c.user("chatpages"), c.user("chatother")
|
||||
empty = c.call("GET", "/api/v1/chats", actor=owner, schema="ChatPage")["json"]
|
||||
check(empty == {"items": [], "next_cursor": None}, "empty chat list is not a finished empty page")
|
||||
expected = [room(c, owner, title="Chat page " + str(i)) for i in range(7)]
|
||||
room(c, outsider, title="Must not appear in owner's list")
|
||||
ordered = sorted(expected, key=lambda x: (timestamp(x["created_at"]), uuid.UUID(x["id"]).int))
|
||||
seen, cursors, cursor = [], set(), None
|
||||
for _ in range(len(expected) + 1):
|
||||
path = "/api/v1/chats?limit=2"
|
||||
if cursor is not None:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = c.call("GET", path, actor=owner, schema="ChatPage")["json"]
|
||||
check(0 < len(page["items"]) <= 2, "invalid chat page size")
|
||||
seen.extend(page["items"])
|
||||
check(len(seen) <= len(expected), "chat pagination repeated or leaked items")
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
check(cursor not in cursors, "chat cursor cycle")
|
||||
cursors.add(cursor)
|
||||
rejected = c.call("GET", "/api/v1/chats?cursor=" + quote(cursor, safe=""),
|
||||
400, actor=outsider)
|
||||
check(rejected["json"]["error"]["code"] == "invalid_request", "foreign chat-list cursor returned wrong error")
|
||||
else:
|
||||
check(False, "chat pagination exceeded fixture bound")
|
||||
check(len({item["id"] for item in seen}) == len(expected), "chat list omitted or repeated IDs")
|
||||
check(seen == ordered, "chat pagination lost, repeated, changed or reordered items")
|
||||
|
||||
first = c.call("GET", "/api/v1/chats?limit=1", actor=owner, schema="ChatPage")["json"]
|
||||
check(first["next_cursor"] is not None, "chat cursor ended before remaining items")
|
||||
rest = c.call("GET", "/api/v1/chats?limit=100&cursor=" + quote(first["next_cursor"], safe=""),
|
||||
actor=owner, schema="ChatPage")["json"]
|
||||
check(first["items"] + rest["items"] == ordered and rest["next_cursor"] is None,
|
||||
"changing chat-list limit lost, repeated or reordered items")
|
||||
for query in ("limit=0", "limit=101", "limit=-1", "limit=abc", "limit=", "cursor=", "cursor=invalid"):
|
||||
rejected = c.call("GET", "/api/v1/chats?" + query, 400, actor=owner)
|
||||
check(rejected["json"]["error"]["code"] == "invalid_request", "invalid chat-list query returned wrong error")
|
||||
return {"items": len(seen), "page_limit": 2, "foreign_cursors_rejected": len(cursors),
|
||||
"changed_limit": [1, 100]}
|
||||
|
||||
|
||||
def cursors(c):
|
||||
actor, outsider = c.user("cursor"), c.user("outside")
|
||||
first, second = room(c, actor), room(c, actor)
|
||||
empty = c.call("GET", "/api/v1/chats/" + second["id"] + "/messages", actor=actor, schema="MessagePage")["json"]
|
||||
check(empty == {"items": [], "next_cursor": None}, "empty history is not an empty finished page")
|
||||
sent = [c.message(actor, first, "Page " + str(i))["json"] for i in range(7)]
|
||||
path = "/api/v1/chats/" + first["id"] + "/messages"
|
||||
page = c.call("GET", path + "?limit=1", actor=actor, schema="MessagePage")["json"]
|
||||
cursor = quote(page["next_cursor"], safe="")
|
||||
rest = c.call("GET", path + "?limit=100&cursor=" + cursor, actor=actor, schema="MessagePage")["json"]
|
||||
ordered = sorted(sent, key=lambda x: (timestamp(x["created_at"]), uuid.UUID(x["id"]).int))
|
||||
check(page["items"] + rest["items"] == ordered and rest["next_cursor"] is None,
|
||||
"changing limit lost/repeated/reordered messages")
|
||||
c.call("GET", "/api/v1/chats/" + second["id"] + "/messages?cursor=" + cursor, 400, actor=actor)
|
||||
for value in ("", "not-a-cursor"):
|
||||
c.call("GET", path + "?cursor=" + value, 400, actor=actor)
|
||||
c.call("GET", path, 404, actor=outsider)
|
||||
c.call("POST", path, 404, actor=outsider, body={"text": "hidden"}, headers=message_headers())
|
||||
check(history(c, actor, first, limit=2) == ordered, "complete keyset traversal differs")
|
||||
return {"message_items": len(sent), "chat_list": chat_pagination(c)}
|
||||
|
||||
|
||||
def read_after_write(c, client_factory, concurrency=4):
|
||||
members = [c.user("writer") for _ in range(10)]
|
||||
actor = members[0]
|
||||
chat = room(c, actor, members=[m["id"] for m in members])
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
# Warm the empty-history cache before starting concurrent writes.
|
||||
c.call("GET", path, actor=actor, schema="MessagePage")
|
||||
|
||||
def write_then_read(index):
|
||||
local = client_factory()
|
||||
writer = members[index % len(members)]
|
||||
confirmed = local.message(writer, chat, "Read-after-write " + str(index))["json"]
|
||||
check(confirmed["sender_id"] == writer["id"], "message sender differs from authenticated writer")
|
||||
page = local.call("GET", path, actor=writer, schema="MessagePage")["json"]
|
||||
check(any(m == confirmed for m in page["items"]), "confirmed message absent from next read")
|
||||
return confirmed
|
||||
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
messages = list(pool.map(write_then_read, range(100)))
|
||||
stored = history(c, actor, chat, limit=37)
|
||||
check(len({m["id"] for m in messages}) == 100, "concurrent writes reused message IDs")
|
||||
check(stored == sorted(messages, key=lambda m: (timestamp(m["created_at"]), uuid.UUID(m["id"]).int)),
|
||||
"concurrent writes lost, duplicated, changed or reordered confirmations")
|
||||
check({m["sender_id"] for m in stored} == {m["id"] for m in members}, "not all writers contributed")
|
||||
return {"writers": len(members), "messages": len(stored), "concurrency": concurrency}
|
||||
@@ -0,0 +1,62 @@
|
||||
# Example only. This is NOT installed into .github/workflows by the test task.
|
||||
# PostgreSQL acceptance job; add the chosen cache service/adapters for grade 4/5.
|
||||
name: Lab2 application example
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
postgres-acceptance:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18
|
||||
env:
|
||||
POSTGRES_USER: lab2_ci
|
||||
POSTGRES_DB: lab2_ci
|
||||
# Public synthetic fixture credential for this disposable CI service.
|
||||
POSTGRES_PASSWORD: ci-fixture-only
|
||||
ports: ["5432:5432"]
|
||||
options: >-
|
||||
--health-cmd="pg_isready -U lab2_ci -d lab2_ci"
|
||||
--health-interval=5s --health-timeout=3s --health-retries=10
|
||||
env:
|
||||
AUTH_TEST_DATABASE_URL: postgres://lab2_ci:ci-fixture-only@127.0.0.1:5432/lab2_ci?sslmode=disable
|
||||
MIGRATE_TEST_DATABASE_URL: postgres://lab2_ci:ci-fixture-only@127.0.0.1:5432/lab2_ci?sslmode=disable
|
||||
LAB2_TEST_DATABASE_URL: postgres://lab2_ci:ci-fixture-only@127.0.0.1:5432/lab2_ci?sslmode=disable
|
||||
LAB2_BASE_URL: http://127.0.0.1:8080
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
SESSION_TTL_SECONDS: "3600"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.27.1"
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: python -m pip install -r requirements-dev.txt
|
||||
- run: make check validate PYTHON=python
|
||||
- run: python -m unittest discover -s student-tests/lab2 -p test_harness.py -v
|
||||
- run: go test -race ./... -count=1
|
||||
- name: Build, migrate, run actual HTTP checks
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
go build -o "$RUNNER_TEMP/lab2-api" ./cmd/api
|
||||
go build -o "$RUNNER_TEMP/lab2-migrate" ./cmd/migrate
|
||||
export DATABASE_URL_FILE="$RUNNER_TEMP/lab2-database-url"
|
||||
umask 077
|
||||
printf '%s' "$LAB2_TEST_DATABASE_URL" > "$DATABASE_URL_FILE"
|
||||
"$RUNNER_TEMP/lab2-migrate"
|
||||
"$RUNNER_TEMP/lab2-api" > "$RUNNER_TEMP/lab2-api.log" 2>&1 &
|
||||
api_pid=$!
|
||||
trap 'kill "$api_pid" 2>/dev/null || true' EXIT
|
||||
ready=0
|
||||
for attempt in {1..60}; do
|
||||
if curl -fsS "$LAB2_BASE_URL/health/ready" >/dev/null; then ready=1; break; fi
|
||||
sleep 0.5
|
||||
done
|
||||
test "$ready" -eq 1
|
||||
make test BASE_URL="$LAB2_BASE_URL"
|
||||
python student-tests/lab2/run.py --suite auth --suite business-boundaries --suite business-cursors --suite read-after-write --suite sql-plan --output student-tests/lab2/output/ci.json
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"base_url": null,
|
||||
"expiry_base_url": null,
|
||||
"ca_file": null,
|
||||
"ttl_seconds": 3600,
|
||||
"request_timeout_seconds": 10,
|
||||
"hook_timeout_seconds": 90,
|
||||
"operation_budget_seconds": 3,
|
||||
"cache_policy": null,
|
||||
"cache_target": "history",
|
||||
"track": null,
|
||||
"concurrency": 4,
|
||||
"read_repetitions": 20,
|
||||
"cache_experiment": {
|
||||
"scenario": null,
|
||||
"max_protected_sql_queries": null
|
||||
},
|
||||
"sql": {
|
||||
"database_url_env": "LAB2_TEST_DATABASE_URL",
|
||||
"restore_database_url_env": "LAB2_RESTORED_DATABASE_URL",
|
||||
"source_schema": "public",
|
||||
"restore_schema": "public",
|
||||
"plan_rows": 10000,
|
||||
"research_rows": 100000,
|
||||
"scan_budget_rows": 1000,
|
||||
"repetitions": 5
|
||||
},
|
||||
"hooks": {
|
||||
"restart_stack": null,
|
||||
"stop_postgres": null,
|
||||
"start_postgres": null,
|
||||
"stop_cache": null,
|
||||
"start_cache": null,
|
||||
"restart_cache": null,
|
||||
"block_query": null,
|
||||
"unblock_query": null,
|
||||
"exhaust_pool": null,
|
||||
"release_pool": null,
|
||||
"evict_cache": null,
|
||||
"metrics": null,
|
||||
"prepare_cache_baseline": null,
|
||||
"prepare_cache_protected": null,
|
||||
"backup_database": null,
|
||||
"restore_database": null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 2: disposable PostgreSQL A/B experiment and verified backup/restore.
|
||||
|
||||
Uses sqlprobe and the existing snapshot comparator. Credentials and the actual
|
||||
dump remain in an automatically removed private temporary directory. Only the
|
||||
two containers and volumes created by this invocation can be removed.
|
||||
"""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from resources import Sampler
|
||||
from run import compare_snapshots
|
||||
|
||||
|
||||
def command(argv, *, env=None, stdin=None, stdout=None, timeout=180):
|
||||
try:
|
||||
result = subprocess.run(argv, cwd=ROOT, env=env, stdin=stdin,
|
||||
stdout=stdout or subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, timeout=timeout)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
raise RuntimeError('Command unavailable or timed out: ' + argv[0]) from exc
|
||||
if result.returncode:
|
||||
# Process arguments/output may contain connection details. Do not print them.
|
||||
safe = [s for s in result.stderr.decode(errors='replace').splitlines()
|
||||
if s.startswith(('research:', 'sqlstate:'))]
|
||||
raise RuntimeError('Command failed: ' + Path(argv[0]).name + ' (exit ' + str(result.returncode) + ')' + ('; ' + '; '.join(safe) if safe else ''))
|
||||
return result.stdout.decode() if stdout is None else ''
|
||||
|
||||
|
||||
def save(path, value):
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
|
||||
|
||||
|
||||
def wait_postgres(name):
|
||||
deadline = time.monotonic() + 75
|
||||
while time.monotonic() < deadline:
|
||||
result = subprocess.run(['docker', 'exec', name, 'pg_isready', '-U', 'messenger', '-d', 'messenger'],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
time.sleep(.3)
|
||||
raise RuntimeError('PostgreSQL did not become ready')
|
||||
|
||||
|
||||
def container_state(name):
|
||||
fields = '{{json .State}}\n{{json .Mounts}}\n{{.Id}}'
|
||||
state, mounts, identifier = command(['docker', 'inspect', '--format', fields, name]).splitlines()
|
||||
state, mounts = json.loads(state), json.loads(mounts)
|
||||
return {'id': identifier, 'started_at': state['StartedAt'], 'running': state['Running'],
|
||||
'oom_killed': state['OOMKilled'],
|
||||
'volumes': [m['Name'] for m in mounts if m['Type'] == 'volume']}
|
||||
|
||||
|
||||
def selected_messages(name, schema):
|
||||
if not schema.startswith('lab2_test_') or not schema.replace('_', '').isalnum():
|
||||
raise RuntimeError('Unexpected fixture schema')
|
||||
# Values stay in process memory. Evidence retains IDs and content fingerprints.
|
||||
sql = f'''SELECT row_to_json(chosen)::text FROM (
|
||||
SELECT id,chat_id,sender_id,text,created_at,rn,total FROM (
|
||||
SELECT m.*,row_number() OVER (PARTITION BY chat_id ORDER BY created_at,id) rn,
|
||||
count(*) OVER (PARTITION BY chat_id) total FROM "{schema}".messages m
|
||||
) ranked WHERE rn IN (1,(total+1)/2,total) ORDER BY chat_id,rn
|
||||
) chosen'''
|
||||
raw = command(['docker', 'exec', name, 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-c', sql])
|
||||
result = []
|
||||
for line in raw.splitlines():
|
||||
row = json.loads(line)
|
||||
result.append({'id': row['id'], 'chat_id': row['chat_id'], 'position': row['rn'],
|
||||
'chat_rows': row['total'], 'sha256': hashlib.sha256(
|
||||
json.dumps(row, sort_keys=True, ensure_ascii=False).encode()).hexdigest()})
|
||||
if len(result) != 15:
|
||||
raise RuntimeError('Expected first/middle/last samples from all five chats')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--output', type=Path, required=True)
|
||||
p.add_argument('--postgres-image', default='postgres:18')
|
||||
p.add_argument('--rows', type=int, default=100000)
|
||||
p.add_argument('--repetitions', type=int, default=60)
|
||||
p.add_argument('--series', type=int, default=4)
|
||||
p.add_argument('--write-batches', type=int, default=20)
|
||||
args = p.parse_args()
|
||||
if args.rows < 100000 or args.rows % 100 or args.repetitions < 30 or args.series < 4 or args.series % 2 or args.write_batches < 10:
|
||||
p.error('need >=100k rows divisible by 100, >=30 reads, even >=4 series and >=10 write batches')
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
run_id = 'lab2-research-' + secrets.token_hex(6)
|
||||
names = [run_id + '-source', run_id + '-target']
|
||||
volumes = [run_id + '-source-data', run_id + '-target-data']
|
||||
owned_containers, owned_volumes = [], []
|
||||
summary = {'status': 'FAIL', 'run_id': run_id, 'rows': args.rows,
|
||||
'started_at': datetime.now(timezone.utc).isoformat(), 'stages': []}
|
||||
sampler = None
|
||||
try:
|
||||
image_info = json.loads(command(['docker', 'image', 'inspect', args.postgres_image]))[0]
|
||||
# Run the immutable locally resolved image ID; the chosen digest is in evidence.
|
||||
image_id = image_info['Id']
|
||||
hardware = {}
|
||||
if sys.platform == 'darwin':
|
||||
for key in ('hw.model', 'hw.ncpu', 'hw.memsize', 'machdep.cpu.brand_string'):
|
||||
hardware[key] = command(['sysctl', '-n', key]).strip()
|
||||
environment = {'platform': platform.platform(), 'hardware': hardware,
|
||||
'go': command(['go', 'version']).strip(),
|
||||
'docker': command(['docker', 'version', '--format', '{{.Server.Version}}']).strip(),
|
||||
'image': {'id': image_id, 'digests': image_info.get('RepoDigests', []),
|
||||
'architecture': image_info['Architecture']},
|
||||
'limits_per_postgres': {'cpus': 1, 'memory_mib': 512},
|
||||
'other_running_containers_at_start': command(['docker', 'ps', '--format', '{{.Names}}']).splitlines()}
|
||||
save(output / 'environment.json', environment)
|
||||
with tempfile.TemporaryDirectory(prefix=run_id + '-') as directory:
|
||||
tmp = Path(directory)
|
||||
env_file = tmp / 'postgres.env'
|
||||
password = secrets.token_hex(24)
|
||||
env_file.write_text('POSTGRES_USER=messenger\nPOSTGRES_DB=messenger\nPOSTGRES_PASSWORD=' + password + '\n')
|
||||
env_file.chmod(0o600)
|
||||
probe = tmp / 'sqlprobe'
|
||||
build_env = dict(os.environ, GOCACHE=os.environ.get('GOCACHE', '/tmp/highload-research-go-cache'))
|
||||
command(['go', 'build', '-mod=readonly', '-o', str(probe), './student-tests/lab2/sqlprobe'], env=build_env)
|
||||
|
||||
def start(index):
|
||||
name, volume = names[index], volumes[index]
|
||||
command(['docker', 'volume', 'create', '--label', 'highload.research=' + run_id, volume])
|
||||
owned_volumes.append(volume)
|
||||
command(['docker', 'run', '-d', '--name', name, '--label', 'highload.research=' + run_id,
|
||||
'--cpus', '1', '--memory', '512m', '--memory-swap', '512m',
|
||||
'--env-file', str(env_file), '-p', '127.0.0.1::5432',
|
||||
'-v', volume + ':/var/lib/postgresql', image_id])
|
||||
owned_containers.append(name)
|
||||
wait_postgres(name)
|
||||
return connection_url(name)
|
||||
|
||||
def connection_url(name):
|
||||
port = command(['docker', 'port', name, '5432/tcp']).strip().rsplit(':', 1)[1]
|
||||
return f'postgres://messenger:{password}@127.0.0.1:{port}/messenger?sslmode=disable'
|
||||
|
||||
source_url = start(0)
|
||||
|
||||
def sqlprobe(mode, url, extra=()):
|
||||
argv = [str(probe), '-mode', mode, '-rows', str(args.rows),
|
||||
'-repetitions', str(args.repetitions), '-series', str(args.series),
|
||||
'-write-batches', str(args.write_batches), '-timeout', '12m', *extra]
|
||||
env = dict(os.environ, LAB2_SQL_DATABASE_URL=url)
|
||||
started = time.monotonic()
|
||||
result = json.loads(command(argv, env=env, timeout=750))
|
||||
summary['stages'].append({'stage': mode, 'status': 'PASS', 'seconds': time.monotonic() - started})
|
||||
return result
|
||||
|
||||
print('PostgreSQL source ready; preparing and comparing >=100k rows', flush=True)
|
||||
sampler = Sampler(names[0], .5)
|
||||
began = time.monotonic()
|
||||
sampler.thread.start()
|
||||
comparison = sqlprobe('research', source_url)
|
||||
ended = time.monotonic()
|
||||
comparison['resources'] = sampler.finish(began, ended, 1)
|
||||
sampler = None
|
||||
save(output / 'indexes.json', comparison)
|
||||
print('Index comparison PASS; preparing persistent backup fixture', flush=True)
|
||||
schema = 'lab2_test_backup_' + secrets.token_hex(5)
|
||||
seed = sqlprobe('seed', source_url, ('-schema', schema))
|
||||
save(output / 'dataset.json', seed)
|
||||
before = sqlprobe('snapshot', source_url, ('-schema', schema))
|
||||
selected_before = selected_messages(names[0], schema)
|
||||
save(output / 'source-snapshot.json', before)
|
||||
save(output / 'source-selected.json', selected_before)
|
||||
target_url = start(1)
|
||||
empty = sqlprobe('snapshot', target_url, ('-schema', schema))
|
||||
if not empty['empty'] or before['identity_sha256'] == empty['identity_sha256']:
|
||||
raise RuntimeError('Restore target must be a distinct empty PostgreSQL instance')
|
||||
before_states = {n: container_state(n) for n in names}
|
||||
if set(before_states[names[0]]['volumes']) & set(before_states[names[1]]['volumes']):
|
||||
raise RuntimeError('Source and target share a volume')
|
||||
save(output / 'storage-before-restore.json', before_states)
|
||||
dump = tmp / 'backup.dump'
|
||||
began = time.monotonic()
|
||||
with dump.open('wb') as stream:
|
||||
dump.chmod(0o600)
|
||||
command(['docker', 'exec', names[0], 'pg_dump', '-U', 'messenger', '-d', 'messenger',
|
||||
'-n', schema, '-Fc', '--no-owner', '--no-acl'], stdout=stream)
|
||||
backup_seconds = time.monotonic() - began
|
||||
dump_hash = hashlib.sha256(dump.read_bytes()).hexdigest()
|
||||
began = time.monotonic()
|
||||
with dump.open('rb') as stream:
|
||||
command(['docker', 'exec', '-i', names[1], 'pg_restore', '-U', 'messenger', '-d', 'messenger',
|
||||
'--exit-on-error', '--no-owner', '--no-acl'], stdin=stream)
|
||||
restore_seconds = time.monotonic() - began
|
||||
restored = sqlprobe('snapshot', target_url, ('-schema', schema))
|
||||
compare_snapshots(before, restored)
|
||||
selected_after = selected_messages(names[1], schema)
|
||||
if selected_before != selected_after or before != sqlprobe('snapshot', source_url, ('-schema', schema)):
|
||||
raise RuntimeError('Selected messages differ or source changed during backup/restore')
|
||||
save(output / 'restored-snapshot.json', restored)
|
||||
save(output / 'restored-selected.json', selected_after)
|
||||
# Start from disk again, retaining only the new target's own volume.
|
||||
began = time.monotonic()
|
||||
command(['docker', 'restart', '--time', '20', names[1]])
|
||||
wait_postgres(names[1])
|
||||
# Docker can allocate a different ephemeral host port after restart.
|
||||
target_url = connection_url(names[1])
|
||||
restarted = sqlprobe('snapshot', target_url, ('-schema', schema))
|
||||
compare_snapshots(before, restarted)
|
||||
restart_seconds = time.monotonic() - began
|
||||
save(output / 'storage-after-restart.json', {n: container_state(n) for n in names})
|
||||
restore = {'status': 'PASS', 'backup_seconds': backup_seconds, 'restore_seconds': restore_seconds,
|
||||
'target_restart_and_verification_seconds': restart_seconds,
|
||||
'archive_bytes': dump.stat().st_size, 'archive_sha256': dump_hash,
|
||||
'source_unchanged': True, 'selected_messages_equal': len(selected_before),
|
||||
'all_four_table_counts_and_digests_equal': True, 'target_restart_pass': True,
|
||||
'archive_retained': False, 'scope': 'quiescent synthetic PostgreSQL schema; Redis sessions and post-snapshot writes not included'}
|
||||
save(output / 'backup-restore.json', restore)
|
||||
summary['status'] = 'PASS'
|
||||
print('Backup/restore and target restart PASS', flush=True)
|
||||
except Exception as exc:
|
||||
summary['failure'] = str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__
|
||||
print('FAIL: ' + summary['failure'], flush=True)
|
||||
finally:
|
||||
if sampler is not None:
|
||||
sampler.stop_event.set()
|
||||
sampler.thread.join(timeout=5)
|
||||
cleanup_errors = []
|
||||
for name in reversed(owned_containers):
|
||||
try:
|
||||
command(['docker', 'rm', '-f', name], timeout=45)
|
||||
except RuntimeError:
|
||||
cleanup_errors.append('container ' + name)
|
||||
for name in reversed(owned_volumes):
|
||||
try:
|
||||
command(['docker', 'volume', 'rm', name], timeout=30)
|
||||
except RuntimeError:
|
||||
cleanup_errors.append('volume ' + name)
|
||||
summary['cleanup_errors'] = cleanup_errors
|
||||
if cleanup_errors:
|
||||
summary['status'] = 'FAIL'
|
||||
summary['finished_at'] = datetime.now(timezone.utc).isoformat()
|
||||
save(output / 'summary.json', summary)
|
||||
return 0 if summary['status'] == 'PASS' else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Container resource sampling shared by the lab2 HTTP measurements."""
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class Sampler:
|
||||
"""PID 1 RSS and cgroup-v2 CPU/memory. Only samples inside the phase are used."""
|
||||
|
||||
files = ("/proc/1/status", "/sys/fs/cgroup/cpu.stat",
|
||||
"/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory.events")
|
||||
|
||||
def __init__(self, name, interval):
|
||||
self.name, self.interval = name, interval
|
||||
self.stop_event = threading.Event()
|
||||
self.samples, self.errors = [], []
|
||||
self.thread = threading.Thread(target=self.loop, daemon=True)
|
||||
|
||||
def loop(self):
|
||||
while not self.stop_event.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = subprocess.run(["docker", "exec", self.name, "awk",
|
||||
'FNR == 1 {print "FILE " FILENAME} {print}', *self.files],
|
||||
timeout=4, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError("resource sampling failed (container stopped or cgroup v2 unavailable)")
|
||||
sections, current = {}, None
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith("FILE "):
|
||||
current = line[5:]
|
||||
sections[current] = []
|
||||
elif current:
|
||||
sections[current].append(line)
|
||||
status = dict(line.split(":", 1) for line in sections[self.files[0]] if ":" in line)
|
||||
cpu = dict(line.split() for line in sections[self.files[1]])
|
||||
events = dict(line.split() for line in sections[self.files[3]])
|
||||
self.samples.append({"started": started, "finished": time.monotonic(),
|
||||
"rss_bytes": int(status["VmRSS"].split()[0]) * 1024,
|
||||
"cgroup_memory_bytes": int(sections[self.files[2]][0]),
|
||||
"cpu_usage_usec": int(cpu["usage_usec"]),
|
||||
"oom_kill_count": int(events.get("oom_kill", 0))})
|
||||
except (RuntimeError, ValueError, KeyError, subprocess.SubprocessError) as exc:
|
||||
self.errors.append(str(exc))
|
||||
self.stop_event.wait(max(0, self.interval - (time.monotonic() - started)))
|
||||
|
||||
def finish(self, started, ended, cpus):
|
||||
self.stop_event.set()
|
||||
self.thread.join(timeout=5)
|
||||
samples = [s for s in self.samples if s["started"] >= started and s["finished"] <= ended]
|
||||
if self.errors or len(samples) < 2:
|
||||
raise RuntimeError(self.errors[0] if self.errors else "fewer than two resource samples; increase duration")
|
||||
first, last = samples[0], samples[-1]
|
||||
window = last["finished"] - first["finished"]
|
||||
cores = (last["cpu_usage_usec"] - first["cpu_usage_usec"]) / 1e6 / window
|
||||
rows = [{"seconds": round(s["finished"] - started, 4),
|
||||
"rss_bytes": s["rss_bytes"], "cgroup_memory_bytes": s["cgroup_memory_bytes"],
|
||||
"cpu_usage_usec": s["cpu_usage_usec"], "oom_kill_count": s["oom_kill_count"]}
|
||||
for s in samples]
|
||||
return {"sample_interval_seconds": self.interval, "sample_count": len(rows),
|
||||
"sample_window_seconds": window, "mean_cpu_cores": cores,
|
||||
"mean_cpu_percent_of_limit": 100 * cores / cpus,
|
||||
"rss_first_bytes": first["rss_bytes"],
|
||||
"rss_peak_observed_bytes": max(s["rss_bytes"] for s in samples),
|
||||
"cgroup_memory_peak_observed_bytes": max(s["cgroup_memory_bytes"] for s in samples),
|
||||
"oom_kill_count": max(s["oom_kill_count"] for s in samples), "samples": rows,
|
||||
"method": "RSS: /proc/1/status VmRSS. CPU: delta cgroup-v2 usage_usec / sample window. cgroup memory includes cache and sampling processes; it is not RSS. Peaks are sampled, not exact maxima."}
|
||||
@@ -0,0 +1,449 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Opt-in lab2 test/experiment runner. No application or teacher-contract edits."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
import business # noqa: E402
|
||||
|
||||
|
||||
class Blocked(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def bounded_command(argv, cwd, timeout, env=None):
|
||||
"""Never invoke a shell or include command output/credentials in exceptions."""
|
||||
try:
|
||||
p = subprocess.Popen(argv, cwd=cwd, env=env, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, start_new_session=True)
|
||||
except OSError:
|
||||
raise Blocked("command unavailable; check local tools/adapter") from None
|
||||
try:
|
||||
out, _ = p.communicate(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(p.pid, signal.SIGTERM)
|
||||
try:
|
||||
p.communicate(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(p.pid, signal.SIGKILL)
|
||||
p.communicate()
|
||||
raise Failure("command/adapter exceeded its execution budget") from None
|
||||
if p.returncode == 2:
|
||||
raise Blocked("adapter reports missing implementation/configuration")
|
||||
if p.returncode:
|
||||
raise Failure("command/adapter failed (exit %d); output suppressed" % p.returncode)
|
||||
return out
|
||||
|
||||
|
||||
def percentiles(values):
|
||||
check(bool(values), "no successful latency samples")
|
||||
values = sorted(values)
|
||||
return {"p" + str(p): round(1000 * values[max(0, math.ceil(len(values) * p / 100) - 1)], 3)
|
||||
for p in (50, 95, 99)}
|
||||
|
||||
|
||||
def counter_delta(before, after, key):
|
||||
a, b = before.get(key), after.get(key)
|
||||
check(isinstance(a, int) and not isinstance(a, bool) and a >= 0 and
|
||||
isinstance(b, int) and not isinstance(b, bool) and b >= a,
|
||||
"metrics adapter must return nondecreasing integer counter " + key)
|
||||
return b - a
|
||||
|
||||
|
||||
def compare_snapshots(source, restored):
|
||||
for snapshot in (source, restored):
|
||||
tables = snapshot.get("tables", {})
|
||||
check(set(tables) == {"users", "chats", "chat_members", "messages"},
|
||||
"snapshot must cover all four PostgreSQL application tables")
|
||||
for value in tables.values():
|
||||
check(isinstance(value.get("rows"), int) and not isinstance(value["rows"], bool) and value["rows"] >= 0 and
|
||||
isinstance(value.get("sha256"), str) and len(value["sha256"]) == 64,
|
||||
"snapshot has invalid counts/content digest")
|
||||
check(source.get("identity_sha256") != restored.get("identity_sha256"),
|
||||
"restore target must be a different database/storage endpoint")
|
||||
check(not source.get("empty") and not restored.get("empty"), "restore contains no application tables")
|
||||
check(source.get("tables") == restored.get("tables"), "restored table counts or ordered content digests differ")
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, config, config_path, allow_hooks=False):
|
||||
self.c = config
|
||||
self.directory = config_path.resolve().parent
|
||||
self.allow_hooks = allow_hooks
|
||||
|
||||
def client(self, expiry=False, timeout=None):
|
||||
key, env = ("expiry_base_url", "LAB2_EXPIRY_BASE_URL") if expiry else ("base_url", "LAB2_BASE_URL")
|
||||
url = os.environ.get(env) or self.c.get(key)
|
||||
if not url:
|
||||
raise Blocked("configure " + key + " for a dedicated synthetic test API")
|
||||
return Client(url, self.c.get("ca_file"), timeout=timeout or self.c["request_timeout_seconds"])
|
||||
|
||||
def require_hooks(self, *names):
|
||||
if not self.allow_hooks:
|
||||
raise Blocked("infrastructure adapters require explicit --allow-hooks")
|
||||
for name in names:
|
||||
argv = self.c.get("hooks", {}).get(name)
|
||||
if not isinstance(argv, list) or not argv or not all(isinstance(x, str) and x for x in argv):
|
||||
raise Blocked("configure executable argv array for hook " + name)
|
||||
|
||||
def hook(self, name, metrics=False):
|
||||
self.require_hooks(name)
|
||||
out = bounded_command(self.c["hooks"][name], self.directory, self.c["hook_timeout_seconds"])
|
||||
if metrics:
|
||||
check(len(out) <= 65536, "metrics adapter output exceeds limit")
|
||||
try:
|
||||
value = json.loads(out)
|
||||
except ValueError:
|
||||
raise Failure("metrics adapter must output one JSON object") from None
|
||||
check(isinstance(value, dict), "metrics adapter must output a JSON object")
|
||||
# Only these numeric counters may enter evidence, never raw adapter output.
|
||||
return {key: value.get(key) for key in ("sql_queries", "cache_hits")}
|
||||
|
||||
@contextlib.contextmanager
|
||||
def disruption(self, failure, recovery):
|
||||
self.require_hooks(failure, recovery)
|
||||
try:
|
||||
self.hook(failure)
|
||||
yield
|
||||
finally:
|
||||
self.hook(recovery)
|
||||
|
||||
def wait_ready(self):
|
||||
deadline = time.monotonic() + self.c["hook_timeout_seconds"]
|
||||
while True:
|
||||
try:
|
||||
self.client(timeout=2).call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "API did not recover readiness")
|
||||
time.sleep(.2)
|
||||
|
||||
def auth_module(self, expiry=False):
|
||||
spec = importlib.util.spec_from_file_location("lab2_auth_existing", ROOT / "student-tests/auth_contract.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.ARGS = types.SimpleNamespace(
|
||||
base_url=self.client(expiry=expiry).base, ca_file=self.c.get("ca_file"),
|
||||
timeout=self.c["request_timeout_seconds"], ttl=self.c["ttl_seconds"],
|
||||
hook_timeout=self.c["hook_timeout_seconds"], restart_hook="restart_stack",
|
||||
failure_hook=None, recovery_hook=None, dependency=None, cache_policy=self.c.get("cache_policy"), session_store="redis")
|
||||
module.hook = self.hook
|
||||
return module
|
||||
|
||||
def auth(self, suite):
|
||||
if suite == "persistence":
|
||||
self.require_hooks("restart_stack")
|
||||
module = self.auth_module(expiry=suite == "expiry")
|
||||
if suite == "auth":
|
||||
result = unittest.TextTestRunner(stream=io.StringIO()).run(
|
||||
unittest.defaultTestLoader.loadTestsFromTestCase(module.AuthContract))
|
||||
check(result.wasSuccessful(), "auth tests failed: " + ", ".join(t._testMethodName for t, _ in result.failures + result.errors))
|
||||
return {"tests": result.testsRun}
|
||||
if suite == "expiry":
|
||||
module.ARGS.base_url = self.client(expiry=True).base
|
||||
module.ARGS.ttl = 2
|
||||
module.expiry()
|
||||
else:
|
||||
module.persistence()
|
||||
|
||||
def dependency(self, name):
|
||||
failure, recovery = ("stop_postgres", "start_postgres") if name == "postgres" else ("stop_cache", "start_cache")
|
||||
self.require_hooks(failure, recovery)
|
||||
if name == "redis" and self.c.get("cache_policy") not in ("critical", "fallback"):
|
||||
raise Blocked("declare cache_policy critical or fallback")
|
||||
module = self.auth_module()
|
||||
module.ARGS.dependency = name
|
||||
module.ARGS.failure_hook, module.ARGS.recovery_hook = failure, recovery
|
||||
module.dependency()
|
||||
|
||||
def timeout(self, mode):
|
||||
failure, recovery = ("block_query", "unblock_query") if mode == "query" else ("exhaust_pool", "release_pool")
|
||||
self.require_hooks(failure, recovery)
|
||||
budget = self.c["operation_budget_seconds"]
|
||||
client = self.client(timeout=budget + 1)
|
||||
actor = client.user("budget")
|
||||
with self.disruption(failure, recovery):
|
||||
client.call("GET", "/health/live", schema="Health")
|
||||
client.call("GET", "/api/v1/users/me", 401)
|
||||
started = time.monotonic()
|
||||
response = client.call("GET", "/api/v1/users/me", 503, actor=actor)
|
||||
elapsed = time.monotonic() - started
|
||||
check(elapsed <= budget, "API exceeded configured test operation budget")
|
||||
check(response["json"]["error"]["code"] == "unavailable", "blocked operation returned wrong error")
|
||||
self.wait_ready()
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
return {"elapsed_seconds": round(elapsed, 4), "budget_seconds": budget, "mode": mode}
|
||||
|
||||
def cache_read(self, client, actor, chat):
|
||||
target = self.c.get("cache_target")
|
||||
if target == "history":
|
||||
return client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=actor, schema="MessagePage")
|
||||
if target == "chat":
|
||||
return client.call("GET", "/api/v1/chats/" + chat["id"], actor=actor, schema="Chat")
|
||||
if target == "me":
|
||||
return client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
raise Blocked("adapt cache_target to the actually cached operation")
|
||||
|
||||
def cache_usage(self):
|
||||
self.require_hooks("metrics", "evict_cache")
|
||||
client = self.client()
|
||||
actor = client.user("cache_use")
|
||||
chat = business.room(client, actor)
|
||||
self.hook("evict_cache")
|
||||
self.cache_read(client, actor, chat)
|
||||
before = self.hook("metrics", metrics=True)
|
||||
for _ in range(self.c["read_repetitions"]):
|
||||
self.cache_read(client, actor, chat)
|
||||
after = self.hook("metrics", metrics=True)
|
||||
hits = counter_delta(before, after, "cache_hits")
|
||||
check(hits > 0, "no actual cache hit observed on the selected API operation")
|
||||
return {"cache_hits": hits, "sql_queries": counter_delta(before, after, "sql_queries")}
|
||||
|
||||
def cache_restart(self):
|
||||
self.require_hooks("restart_cache")
|
||||
client = self.client()
|
||||
actor, revoked = client.user("cache_restart"), client.user("revoked")
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=revoked)
|
||||
chat = business.room(client, actor)
|
||||
original = client.message(actor, chat, "Before cache restart")["json"]
|
||||
self.cache_read(client, actor, chat)
|
||||
self.hook("restart_cache")
|
||||
self.wait_ready()
|
||||
check(client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["json"] == actor["user"], "cache restart lost session")
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=revoked)
|
||||
check(original in business.history(client, actor, chat), "cache restart lost confirmed message")
|
||||
|
||||
def cache_experiment(self):
|
||||
self.require_hooks("metrics", "evict_cache", "prepare_cache_baseline", "prepare_cache_protected", "restart_cache")
|
||||
scenario = self.c["cache_experiment"].get("scenario")
|
||||
if scenario not in ("stale_read", "stampede"):
|
||||
raise Blocked("choose cache_experiment.scenario stale_read or stampede")
|
||||
limit = self.c["cache_experiment"].get("max_protected_sql_queries")
|
||||
if scenario == "stampede" and (not isinstance(limit, int) or isinstance(limit, bool) or limit < 0):
|
||||
raise Blocked("declare a justified SQL-query budget for the protected stampede workload")
|
||||
variants = []
|
||||
for variant in ("baseline", "protected"):
|
||||
self.hook("prepare_cache_" + variant)
|
||||
self.wait_ready()
|
||||
client = self.client()
|
||||
actor = client.user("experiment")
|
||||
chat = business.room(client, actor)
|
||||
self.hook("evict_cache")
|
||||
before = self.hook("metrics", metrics=True)
|
||||
timings, lock = [], threading.Lock()
|
||||
|
||||
class TimedClient(Client):
|
||||
def call(inner, *args, **kwargs):
|
||||
result = super().call(*args, **kwargs)
|
||||
if args[0] == "GET":
|
||||
with lock:
|
||||
timings.append(result["elapsed"])
|
||||
return result
|
||||
|
||||
def factory():
|
||||
return TimedClient(client.base, self.c.get("ca_file"), timeout=self.c["request_timeout_seconds"])
|
||||
|
||||
consistent = True
|
||||
if scenario == "stale_read":
|
||||
try:
|
||||
business.read_after_write(client, factory, self.c["concurrency"])
|
||||
except Failure as exc:
|
||||
if variant == "protected" or str(exc) != "confirmed message absent from next read":
|
||||
raise
|
||||
consistent = False
|
||||
else:
|
||||
barrier = threading.Barrier(self.c["concurrency"])
|
||||
|
||||
def read(_):
|
||||
local = factory()
|
||||
barrier.wait(timeout=self.c["request_timeout_seconds"])
|
||||
for _ in range(self.c["read_repetitions"]):
|
||||
self.cache_read(local, actor, chat)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=self.c["concurrency"]) as pool:
|
||||
list(pool.map(read, range(self.c["concurrency"])))
|
||||
after = self.hook("metrics", metrics=True)
|
||||
variants.append({"variant": variant, "consistent": consistent,
|
||||
"sql_queries": counter_delta(before, after, "sql_queries"),
|
||||
"cache_hits": counter_delta(before, after, "cache_hits"),
|
||||
"read_latency_ms": percentiles(timings)})
|
||||
if scenario == "stale_read":
|
||||
check(not variants[0]["consistent"] and variants[1]["consistent"], "baseline did not reproduce stale read or protection failed")
|
||||
else:
|
||||
check(variants[1]["sql_queries"] <= limit and variants[1]["sql_queries"] < variants[0]["sql_queries"],
|
||||
"SQL reduction/budget not demonstrated; adapt deterministic stampede adapter")
|
||||
business.read_after_write(self.client(), self.client, self.c["concurrency"])
|
||||
self.cache_restart()
|
||||
return {"scenario": scenario, "variants": variants,
|
||||
"review": "Repeat under fixed resources; review counter scope and experimental limits."}
|
||||
|
||||
def probe(self, mode, restore=False):
|
||||
if not shutil.which("go"):
|
||||
raise Blocked("Go toolchain is required for SQL experiments")
|
||||
sql = self.c["sql"]
|
||||
variable = sql["restore_database_url_env" if restore else "database_url_env"]
|
||||
if not os.environ.get(variable):
|
||||
raise Blocked("set " + variable + " for an explicitly selected test database")
|
||||
env = dict(os.environ, LAB2_SQL_DATABASE_URL=os.environ[variable])
|
||||
args = ["go", "run", "./student-tests/lab2/sqlprobe", "-mode", mode,
|
||||
"-schema", sql["restore_schema" if restore else "source_schema"],
|
||||
"-rows", str(sql["research_rows"] if mode in ("compare", "seed") else sql["plan_rows"]),
|
||||
"-scan-budget", str(sql["scan_budget_rows"]), "-repetitions", str(sql["repetitions"])]
|
||||
out = bounded_command(args, ROOT, 300, env)
|
||||
try:
|
||||
return json.loads(out)
|
||||
except ValueError:
|
||||
raise Failure("SQL probe did not return valid JSON") from None
|
||||
|
||||
def restore(self):
|
||||
self.require_hooks("backup_database", "restore_database")
|
||||
source, empty_target = self.probe("snapshot"), self.probe("snapshot", restore=True)
|
||||
check(source["identity_sha256"] != empty_target["identity_sha256"], "source and restore target are the same database")
|
||||
check(empty_target["empty"], "restore target must contain no application tables")
|
||||
check(source["tables"].get("messages", {}).get("rows", 0) >= 100000, "track 2 needs at least 100000 source messages")
|
||||
started = time.monotonic()
|
||||
self.hook("backup_database")
|
||||
backup_seconds = time.monotonic() - started
|
||||
started = time.monotonic()
|
||||
self.hook("restore_database")
|
||||
restore_seconds = time.monotonic() - started
|
||||
restored = self.probe("snapshot", restore=True)
|
||||
compare_snapshots(source, restored)
|
||||
check(source == self.probe("snapshot"), "source changed during backup/restore; quiesce the fixture")
|
||||
return {"backup_seconds": round(backup_seconds, 4), "restore_seconds": round(restore_seconds, 4),
|
||||
"tables": restored["tables"], "review": "Document recovery/loss boundaries and verify fresh storage scope."}
|
||||
|
||||
|
||||
SUITES = {
|
||||
"auth": "Existing normal auth cases",
|
||||
"business-boundaries": "Title/text/member validation and strict lab2 JSON/UTF-8 cases",
|
||||
"business-cursors": "Both chat-list and message-history pagination, bound cursors, changing limit and ACL",
|
||||
"read-after-write": "100 concurrent confirmations from 10 members are visible immediately",
|
||||
"persistence": "Full restart with original/revoked sessions",
|
||||
"expiry": "Separate API with actual TTL=2",
|
||||
"postgres-failure": "Real PostgreSQL outage and recovery",
|
||||
"cache-usage": "Actual cache hits through an observable API operation",
|
||||
"cache-failure": "Declared critical/fallback cache outage",
|
||||
"cache-restart": "Cache restart preserves confirmations and logout",
|
||||
"query-timeout": "Blocked SQL must produce bounded HTTP 503",
|
||||
"pool-timeout": "Exhausted application pool must produce bounded HTTP 503",
|
||||
"sql-plan": "Actual repository SQL on >=10000 rows, including deep pages",
|
||||
"cache-experiment": "Track 1: reproducible baseline/protection and counters",
|
||||
"sql-experiment": "Track 2: >=100000 skewed rows, two indexes, read/write costs",
|
||||
"backup-restore": "Track 2: fresh target, counts and full ordered digests"
|
||||
}
|
||||
|
||||
|
||||
def execute(h, name):
|
||||
if name in ("auth", "expiry", "persistence"):
|
||||
return h.auth(name)
|
||||
if name == "business-boundaries":
|
||||
return business.boundaries(h.client())
|
||||
if name == "business-cursors":
|
||||
return business.cursors(h.client())
|
||||
if name == "read-after-write":
|
||||
return business.read_after_write(h.client(), h.client, h.c["concurrency"])
|
||||
if name in ("postgres-failure", "cache-failure"):
|
||||
return h.dependency("postgres" if name == "postgres-failure" else "redis")
|
||||
if name in ("query-timeout", "pool-timeout"):
|
||||
return h.timeout("query" if name == "query-timeout" else "pool")
|
||||
if name == "sql-plan":
|
||||
return h.probe("plan")
|
||||
if name == "sql-experiment":
|
||||
return h.probe("compare")
|
||||
if name == "backup-restore":
|
||||
return h.restore()
|
||||
return getattr(h, name.replace("-", "_"))()
|
||||
|
||||
|
||||
def validate_config(config):
|
||||
for key in ("request_timeout_seconds", "hook_timeout_seconds", "operation_budget_seconds"):
|
||||
check(isinstance(config.get(key), (int, float)) and not isinstance(config[key], bool) and config[key] > 0,
|
||||
"positive numeric config value required: " + key)
|
||||
for key, low, high in (("concurrency", 1, 32), ("read_repetitions", 1, 1000)):
|
||||
value = config.get(key)
|
||||
check(isinstance(value, int) and not isinstance(value, bool) and low <= value <= high, "invalid config value: " + key)
|
||||
ttl = config.get("ttl_seconds")
|
||||
check(isinstance(ttl, int) and not isinstance(ttl, bool) and ttl >= 300, "normal suites need ttl_seconds >= 300")
|
||||
check(config.get("track") in (None, "cache", "sql"), "track must be cache, sql or null")
|
||||
sql = config["sql"]
|
||||
for key, minimum in (("plan_rows", 10000), ("research_rows", 100000), ("scan_budget_rows", 1), ("repetitions", 2)):
|
||||
check(isinstance(sql.get(key), int) and not isinstance(sql[key], bool) and sql[key] >= minimum, "invalid SQL parameter: " + key)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", type=Path, default=Path(__file__).with_name("config.example.json"))
|
||||
parser.add_argument("--suite", action="append", choices=["all"] + list(SUITES))
|
||||
parser.add_argument("--list", action="store_true")
|
||||
parser.add_argument("--allow-hooks", action="store_true")
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.list:
|
||||
for name, purpose in SUITES.items():
|
||||
print(name + ": " + purpose)
|
||||
return 0
|
||||
if not args.suite:
|
||||
parser.error("choose --suite or --list; no infrastructure actions run by default")
|
||||
try:
|
||||
config = json.loads(args.config.read_text())
|
||||
validate_config(config)
|
||||
except (OSError, ValueError, KeyError, Failure):
|
||||
print("BLOCKED: invalid/missing test configuration; credentials suppressed")
|
||||
return 2
|
||||
names = list(args.suite)
|
||||
missing_track = False
|
||||
if "all" in names:
|
||||
names = [name for name in SUITES if name not in ("cache-experiment", "sql-experiment", "backup-restore")]
|
||||
if config["track"] == "cache":
|
||||
names.append("cache-experiment")
|
||||
elif config["track"] == "sql":
|
||||
names.extend(("sql-experiment", "backup-restore"))
|
||||
else:
|
||||
missing_track = True
|
||||
harness, results = Harness(config, args.config, args.allow_hooks), []
|
||||
for name in names:
|
||||
started = time.monotonic()
|
||||
item = {"suite": name}
|
||||
try:
|
||||
item.update(status="PASS", observation=execute(harness, name))
|
||||
except Blocked as exc:
|
||||
item.update(status="BLOCKED", reason=str(exc))
|
||||
except Failure as exc:
|
||||
item.update(status="FAIL", reason=str(exc))
|
||||
except Exception as exc:
|
||||
item.update(status="FAIL", reason="test adapter/runtime error (" + type(exc).__name__ + "); details suppressed")
|
||||
item["duration_seconds"] = round(time.monotonic() - started, 4)
|
||||
results.append(item)
|
||||
print(name + ": " + item["status"] + (" — " + item["reason"] if "reason" in item else ""), flush=True)
|
||||
if missing_track:
|
||||
results.append({"suite": "research-track", "status": "BLOCKED", "reason": "select exactly one track: cache or sql"})
|
||||
report = {"scope": "observed automated scenarios, not an automatic grade or manual report/CI review", "results": results}
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
if any(item["status"] == "FAIL" for item in results):
|
||||
return 1
|
||||
return 2 if any(item["status"] == "BLOCKED" for item in results) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,499 @@
|
||||
// SQL experiment adapter. Mutating modes create only fresh lab2_test_* schemas.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
repository2 "highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"highload/db/migrations"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
type recorder struct {
|
||||
mu sync.Mutex
|
||||
active bool
|
||||
SQL string
|
||||
args []any
|
||||
}
|
||||
|
||||
func (r *recorder) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.active {
|
||||
r.SQL, r.args = data.SQL, append([]any(nil), data.Args...)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
func (*recorder) TraceQueryEnd(context.Context, *pgx.Conn, pgx.TraceQueryEndData) {}
|
||||
|
||||
type fixture struct {
|
||||
admin *pgx.Conn
|
||||
pool *pgxpool.Pool
|
||||
schema string
|
||||
owns bool
|
||||
user string
|
||||
chats []string
|
||||
record recorder
|
||||
researchBudget time.Duration
|
||||
}
|
||||
|
||||
func (f *fixture) cleanup() error {
|
||||
if f.pool != nil {
|
||||
f.pool.Close()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
var cleanupErr error
|
||||
if f.admin != nil {
|
||||
if f.owns {
|
||||
_, cleanupErr = f.admin.Exec(ctx, "DROP SCHEMA "+pgx.Identifier{f.schema}.Sanitize()+" CASCADE")
|
||||
}
|
||||
_ = f.admin.Close(ctx)
|
||||
}
|
||||
return cleanupErr
|
||||
}
|
||||
|
||||
func createFixture(ctx context.Context, url, schema string, rows int) (_ *fixture, err error) {
|
||||
f := &fixture{schema: schema}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
f.cleanup()
|
||||
}
|
||||
}()
|
||||
f.admin, err = pgx.Connect(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = f.admin.Exec(ctx, "CREATE SCHEMA "+pgx.Identifier{schema}.Sanitize())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.owns = true // Never drop a schema unless this invocation created it.
|
||||
cfg, err := pgx.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.RuntimeParams["search_path"] = schema
|
||||
cfg.RuntimeParams["timezone"] = "UTC"
|
||||
cfg.ConnectTimeout = 5 * time.Second
|
||||
db := stdlib.OpenDB(*cfg)
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.Files,
|
||||
goose.WithVerbose(false), goose.WithDisableGlobalRegistry(true),
|
||||
goose.WithSlog(slog.New(slog.NewJSONHandler(io.Discard, nil))))
|
||||
if err == nil {
|
||||
_, err = provider.Up(ctx)
|
||||
}
|
||||
db.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg.MaxConns = 2
|
||||
poolCfg.ConnConfig = cfg
|
||||
poolCfg.ConnConfig.Tracer = &f.record
|
||||
f.pool, err = pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.user = uuid.NewString()
|
||||
_, err = f.pool.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)",
|
||||
f.user, "sql_fixture", "Synthetic SQL fixture", "not-a-login-credential")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
id := uuid.NewString()
|
||||
f.chats = append(f.chats, id)
|
||||
if _, err = f.pool.Exec(ctx, "INSERT INTO chats(id,title) VALUES($1,$2)", id, fmt.Sprintf("SQL chat %d", i)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = f.pool.Exec(ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", id, f.user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
_, err = f.pool.Exec(ctx, `INSERT INTO messages(chat_id,sender_id,text,created_at)
|
||||
SELECT CASE WHEN n%100<70 THEN $1::uuid WHEN n%100<90 THEN $2::uuid
|
||||
WHEN n%100<96 THEN $3::uuid WHEN n%100<99 THEN $4::uuid ELSE $5::uuid END,
|
||||
$6::uuid, 'sql-fixture-'||n, timestamptz '2026-01-01 00:00:00+00'+n*interval '1 millisecond'
|
||||
FROM generate_series(1,$7::integer) n`, f.chats[0], f.chats[1], f.chats[2], f.chats[3], f.chats[4], f.user, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = f.pool.Exec(ctx, "ANALYZE messages")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (f *fixture) position(ctx context.Context) (*repository2.MessagePosition, error) {
|
||||
var p repository2.MessagePosition
|
||||
err := f.pool.QueryRow(ctx, `SELECT id::text,created_at FROM messages WHERE chat_id=$1
|
||||
ORDER BY created_at,id OFFSET (SELECT count(*)*8/10 FROM messages WHERE chat_id=$1) LIMIT 1`, f.chats[0]).Scan(&p.ID, &p.CreatedAt)
|
||||
// OFFSET is used only to select a fixture cursor, never in the measured query.
|
||||
return &p, err
|
||||
}
|
||||
|
||||
func (f *fixture) read(ctx context.Context, after *repository2.MessagePosition) (time.Duration, error) {
|
||||
return f.readChat(ctx, f.chats[0], after)
|
||||
}
|
||||
|
||||
func (f *fixture) readChat(ctx context.Context, chatID string, after *repository2.MessagePosition) (time.Duration, error) {
|
||||
repo := postgres.NewMessageRepository(sqlc.New(f.pool), f.pool)
|
||||
f.record.mu.Lock()
|
||||
f.record.active = true
|
||||
f.record.mu.Unlock()
|
||||
started := time.Now()
|
||||
var items []*model.Message
|
||||
var err error
|
||||
if f.researchBudget > 0 {
|
||||
items, err = f.researchRead(ctx, chatID, after)
|
||||
} else {
|
||||
items, err = repo.GetMessagesByChatID(ctx, chatID, 51, after)
|
||||
}
|
||||
elapsed := time.Since(started)
|
||||
f.record.mu.Lock()
|
||||
f.record.active = false
|
||||
f.record.mu.Unlock()
|
||||
if err == nil && len(items) != 51 {
|
||||
err = fmt.Errorf("fixture history returned %d rows instead of 51", len(items))
|
||||
}
|
||||
for i := 1; err == nil && i < len(items); i++ {
|
||||
if items[i].CreatedAt.Before(items[i-1].CreatedAt) {
|
||||
err = errors.New("history out of order")
|
||||
}
|
||||
}
|
||||
return elapsed, err
|
||||
}
|
||||
|
||||
func maxVisited(node map[string]any) float64 {
|
||||
number := func(key string) float64 { value, _ := node[key].(float64); return value }
|
||||
visited := (number("Actual Rows") + number("Rows Removed by Filter") + number("Rows Removed by Index Recheck")) * number("Actual Loops")
|
||||
children, _ := node["Plans"].([]any)
|
||||
for _, child := range children {
|
||||
if child, ok := child.(map[string]any); ok {
|
||||
visited = max(visited, maxVisited(child))
|
||||
}
|
||||
}
|
||||
return visited
|
||||
}
|
||||
|
||||
func (f *fixture) plan(ctx context.Context, after *repository2.MessagePosition) (map[string]any, error) {
|
||||
return f.planChat(ctx, f.chats[0], after)
|
||||
}
|
||||
|
||||
func (f *fixture) planChat(ctx context.Context, chatID string, after *repository2.MessagePosition) (map[string]any, error) {
|
||||
if _, err := f.readChat(ctx, chatID, after); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.record.mu.Lock()
|
||||
query, args := f.record.SQL, append([]any(nil), f.record.args...)
|
||||
f.record.mu.Unlock()
|
||||
if !strings.Contains(query, "GetMessagesByChatID") {
|
||||
return nil, errors.New("adapt query recorder to repository SQL")
|
||||
}
|
||||
var raw []byte
|
||||
err := f.pool.QueryRow(ctx, "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) "+query, args...).Scan(&raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var plan []map[string]any
|
||||
if err = json.Unmarshal(raw, &plan); err != nil || len(plan) != 1 {
|
||||
return nil, errors.New("invalid EXPLAIN output")
|
||||
}
|
||||
node, ok := plan[0]["Plan"].(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.New("missing EXPLAIN plan")
|
||||
}
|
||||
return map[string]any{"explain": plan[0], "max_visited_rows": maxVisited(node)}, nil
|
||||
}
|
||||
|
||||
func latency(values []time.Duration) map[string]float64 {
|
||||
sort.Slice(values, func(i, j int) bool { return values[i] < values[j] })
|
||||
result := map[string]float64{}
|
||||
for _, p := range []int{50, 95, 99} {
|
||||
i := (len(values)*p+99)/100 - 1
|
||||
result[fmt.Sprintf("p%d", p)] = float64(values[i].Microseconds()) / 1000
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (f *fixture) compare(ctx context.Context, repetitions int) ([]map[string]any, error) {
|
||||
position, err := f.position(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Only this fresh fixture schema is changed; application migrations stay intact.
|
||||
if _, err = f.pool.Exec(ctx, "DROP INDEX idx_messages_chat_created_id"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var results []map[string]any
|
||||
for _, columns := range []string{"chat_id", "chat_id,created_at,id"} {
|
||||
if _, err = f.pool.Exec(ctx, "CREATE INDEX lab2_history_variant ON messages("+columns+")"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = f.pool.Exec(ctx, "ANALYZE messages"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err = f.read(ctx, position); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var reads, writes []time.Duration
|
||||
for i := 0; i < repetitions; i++ {
|
||||
duration, err := f.read(ctx, position)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reads = append(reads, duration)
|
||||
prefix := "write-fixture-" + uuid.NewString() + "-"
|
||||
started := time.Now()
|
||||
tx, err := f.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO messages(chat_id,sender_id,text)
|
||||
SELECT $1::uuid,$2::uuid,$3::text||n FROM generate_series(1,200) n`, f.chats[0], f.user, prefix)
|
||||
if err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
writes = append(writes, time.Since(started))
|
||||
if _, err = f.pool.Exec(ctx, "DELETE FROM messages WHERE text LIKE $1", prefix+"%"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
first, err := f.plan(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
deep, err := f.plan(ctx, position)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var size int64
|
||||
if err = f.pool.QueryRow(ctx, "SELECT pg_relation_size('lab2_history_variant')").Scan(&size); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
results = append(results, map[string]any{"columns": columns, "read_ms": latency(reads), "insert_200_with_commit_ms": latency(writes), "index_bytes": size, "first_page": first, "deep_page": deep})
|
||||
if _, err = f.pool.Exec(ctx, "DROP INDEX lab2_history_variant"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func snapshot(ctx context.Context, url, schema string) (map[string]any, error) {
|
||||
cfg, err := pgx.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.RuntimeParams["timezone"] = "UTC"
|
||||
cfg.RuntimeParams["datestyle"] = "ISO, YMD"
|
||||
cfg.ConnectTimeout = 5 * time.Second
|
||||
conn, err := pgx.ConnectConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close(context.Background())
|
||||
tx, err := conn.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
identity := sha256.Sum256([]byte(fmt.Sprintf("%s:%d/%s", cfg.Host, cfg.Port, cfg.Database)))
|
||||
tables := map[string]any{}
|
||||
missing := 0
|
||||
for _, table := range []struct{ name, order string }{{"users", "id"}, {"chats", "id"}, {"chat_members", "chat_id,user_id"}, {"messages", "id"}} {
|
||||
qualified := pgx.Identifier{schema, table.name}.Sanitize()
|
||||
var exists bool
|
||||
if err = tx.QueryRow(ctx, "SELECT to_regclass($1) IS NOT NULL", qualified).Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
missing++
|
||||
continue
|
||||
}
|
||||
rows, err := tx.Query(ctx, "SELECT row_to_json(t)::text FROM "+qualified+" t ORDER BY "+table.order)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
digest := sha256.New()
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
var row string
|
||||
if err = rows.Scan(&row); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
_, _ = io.WriteString(digest, row+"\n")
|
||||
count++
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tables[table.name] = map[string]any{"rows": count, "sha256": hex.EncodeToString(digest.Sum(nil))}
|
||||
}
|
||||
if missing != 0 && missing != 4 {
|
||||
return nil, errors.New("snapshot schema contains only part of the application tables")
|
||||
}
|
||||
return map[string]any{"identity_sha256": hex.EncodeToString(identity[:]), "empty": missing == 4, "tables": tables}, nil
|
||||
}
|
||||
|
||||
func execute(ctx context.Context, mode, url, schema string, rows, budget, repetitions int) (result map[string]any, err error) {
|
||||
if mode == "snapshot" {
|
||||
return snapshot(ctx, url, schema)
|
||||
}
|
||||
if rows < 10000 || ((mode == "compare" || mode == "seed") && rows < 100000) || repetitions < 2 || budget < 1 {
|
||||
return nil, errors.New("invalid experiment limits")
|
||||
}
|
||||
if schema == "public" || mode != "seed" {
|
||||
schema = "lab2_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
}
|
||||
if !strings.HasPrefix(schema, "lab2_test_") {
|
||||
return nil, errors.New("fixture schema must start with lab2_test_")
|
||||
}
|
||||
f, err := createFixture(ctx, url, schema, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if cleanupErr := f.cleanup(); err == nil {
|
||||
err = cleanupErr
|
||||
}
|
||||
}()
|
||||
result = map[string]any{"mode": mode, "rows": rows, "schema": schema, "chat_distribution_percent": []int{70, 20, 6, 3, 1}}
|
||||
var actualRows int
|
||||
var postgresVersion string
|
||||
if err = f.pool.QueryRow(ctx, "SELECT count(*) FROM messages").Scan(&actualRows); err != nil || actualRows != rows {
|
||||
return nil, errors.New("fixture row count differs from the requested dataset")
|
||||
}
|
||||
if err = f.pool.QueryRow(ctx, "SHOW server_version").Scan(&postgresVersion); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
distribution, queryErr := f.pool.Query(ctx, "SELECT count(*) FROM messages GROUP BY chat_id ORDER BY count(*) DESC")
|
||||
if queryErr != nil {
|
||||
return nil, queryErr
|
||||
}
|
||||
var chatCounts []int
|
||||
for distribution.Next() {
|
||||
var count int
|
||||
if err = distribution.Scan(&count); err != nil {
|
||||
distribution.Close()
|
||||
return nil, err
|
||||
}
|
||||
chatCounts = append(chatCounts, count)
|
||||
}
|
||||
err = distribution.Err()
|
||||
distribution.Close()
|
||||
if err != nil || len(chatCounts) != 5 || chatCounts[0] <= chatCounts[4] {
|
||||
return nil, errors.New("fixture does not demonstrate skewed chat sizes")
|
||||
}
|
||||
result["actual_rows"], result["chat_message_counts"] = actualRows, chatCounts
|
||||
result["postgres_version"], result["go_version"] = postgresVersion, runtime.Version()
|
||||
if mode == "seed" {
|
||||
f.owns = false
|
||||
result["kept_fixture"] = true
|
||||
return result, nil
|
||||
}
|
||||
if mode == "compare" {
|
||||
variants, err := f.compare(ctx, repetitions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result["variants"] = variants
|
||||
result["limitations"] = "Warm single-host prototype; write cleanup can leave bloat. Repeat under fixed resources and review plans, cold/generic plans and loss boundaries."
|
||||
return result, nil
|
||||
}
|
||||
if mode != "plan" {
|
||||
return nil, errors.New("unknown mode")
|
||||
}
|
||||
position, err := f.position(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
first, err := f.plan(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
deep, err := f.plan(ctx, position)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if first["max_visited_rows"].(float64) > float64(budget) || deep["max_visited_rows"].(float64) > float64(budget) {
|
||||
return nil, errors.New("history exceeds chosen scan budget")
|
||||
}
|
||||
result["first_page"], result["deep_page"], result["scan_budget_rows"] = first, deep, budget
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
mode := flag.String("mode", "snapshot", "snapshot, plan, compare or seed")
|
||||
schema := flag.String("schema", "public", "snapshot schema or fresh lab2_test_* seed schema")
|
||||
rows := flag.Int("rows", 10000, "fixture message count")
|
||||
budget := flag.Int("scan-budget", 1000, "engineering threshold, not a teacher-mandated constant")
|
||||
repetitions := flag.Int("repetitions", 5, "measurement samples per variant")
|
||||
series := flag.Int("series", 4, "independent AB/BA research rounds (even, >= 4)")
|
||||
writeBatches := flag.Int("write-batches", 20, "committed batches of 200 rows per research trial")
|
||||
timeout := flag.Duration("timeout", 3*time.Minute, "total SQL probe execution budget")
|
||||
flag.Parse()
|
||||
url := os.Getenv("LAB2_SQL_DATABASE_URL")
|
||||
if url == "" {
|
||||
fmt.Fprintln(os.Stderr, "set LAB2_SQL_DATABASE_URL for a dedicated test database")
|
||||
os.Exit(2)
|
||||
}
|
||||
if *mode != "snapshot" && *mode != "plan" && *mode != "compare" && *mode != "seed" && *mode != "research" {
|
||||
os.Exit(2)
|
||||
}
|
||||
signals, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
ctx, cancel := context.WithTimeout(signals, *timeout)
|
||||
defer cancel()
|
||||
var result map[string]any
|
||||
var err error
|
||||
if *mode == "research" {
|
||||
result, err = research(ctx, url, *rows, *repetitions, *series, *writeBatches)
|
||||
} else {
|
||||
result, err = execute(ctx, *mode, url, *schema, *rows, *budget, *repetitions)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "SQL probe failed; private error details suppressed")
|
||||
os.Exit(1)
|
||||
}
|
||||
if err = json.NewEncoder(os.Stdout).Encode(result); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPlanBudgetIncludesFilteredRowsAndLoops(t *testing.T) {
|
||||
plan := map[string]any{"Actual Rows": float64(51), "Actual Loops": float64(1),
|
||||
"Plans": []any{map[string]any{"Actual Rows": float64(51), "Actual Loops": float64(2),
|
||||
"Rows Removed by Filter": float64(8000)}}}
|
||||
if maxVisited(plan) != 16102 {
|
||||
t.Fatal("deep scan hidden by LIMIT or ignored loop count")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanBudgetDoesNotDoubleCountParentAndChild(t *testing.T) {
|
||||
plan := map[string]any{"Actual Rows": float64(51), "Actual Loops": float64(1),
|
||||
"Plans": []any{map[string]any{"Actual Rows": float64(51), "Actual Loops": float64(1)}}}
|
||||
if maxVisited(plan) != 51 {
|
||||
t.Fatal("same tuples double-counted through the plan hierarchy")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
repository2 "highload/internal/repository"
|
||||
)
|
||||
|
||||
// Research reuses the actual repository SQL. No application index is changed:
|
||||
// the fixture owns a fresh schema and removes it when the experiment finishes.
|
||||
func research(ctx context.Context, url string, rows, repetitions, series, batches int) (result map[string]any, err error) {
|
||||
stage := "validate"
|
||||
defer func() {
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "research: failed at "+stage)
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
fmt.Fprintln(os.Stderr, "sqlstate: "+pgErr.Code)
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
fmt.Fprintln(os.Stderr, "research: deadline exceeded")
|
||||
}
|
||||
if errors.Is(err, repository2.ErrServiceUnavailable) {
|
||||
fmt.Fprintln(os.Stderr, "research: repository unavailable")
|
||||
}
|
||||
for _, text := range []string{"timeout", "context deadline exceeded", "invalid input", "unexpected page", "history out of order"} {
|
||||
if strings.Contains(err.Error(), text) {
|
||||
fmt.Fprintln(os.Stderr, "research: "+text)
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(err.Error(), "fixture history returned ") {
|
||||
fmt.Fprintln(os.Stderr, "research: "+err.Error())
|
||||
}
|
||||
}
|
||||
}()
|
||||
if rows < 100000 || rows%100 != 0 || repetitions < 30 || series < 4 || series%2 != 0 || batches < 10 {
|
||||
return nil, errors.New("research needs >=100k rows, >=30 reads, even >=4 series, >=10 write batches")
|
||||
}
|
||||
schema := "lab2_test_" + uuid.NewString()[:8] + "_research"
|
||||
stage = "create-fixture"
|
||||
f, err := createFixture(ctx, url, schema, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Preserve the API's one-second policy. Only the offline SQL experiment uses
|
||||
// a larger, identical budget for both indexes, so slow baselines are measurable.
|
||||
f.researchBudget = 10 * time.Second
|
||||
defer func() {
|
||||
if cleanupErr := f.cleanup(); err == nil {
|
||||
err = cleanupErr
|
||||
}
|
||||
}()
|
||||
stage = "drop-original-index"
|
||||
if _, err = f.pool.Exec(ctx, "DROP INDEX idx_messages_chat_created_id"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Disable autovacuum only for the disposable table to control trial cleanup.
|
||||
if _, err = f.pool.Exec(ctx, "ALTER TABLE messages SET (autovacuum_enabled=false)"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Fixed message body size; index keys and logical rows remain identical in A/B.
|
||||
stage = "payload"
|
||||
if _, err = f.pool.Exec(ctx, "UPDATE messages SET text=rpad(text,256,'x')"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var version string
|
||||
if err = f.pool.QueryRow(ctx, "SHOW server_version").Scan(&version); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type readCase struct {
|
||||
name, chat string
|
||||
after *repository2.MessagePosition
|
||||
}
|
||||
var cases []readCase
|
||||
for _, item := range []struct {
|
||||
name string
|
||||
index int
|
||||
}{{"large", 0}, {"medium", 2}, {"small", 4}} {
|
||||
stage = "cursor-" + item.name
|
||||
chatID := f.chats[item.index]
|
||||
position := &repository2.MessagePosition{}
|
||||
if err = f.pool.QueryRow(ctx, `SELECT id::text,created_at FROM messages WHERE chat_id=$1
|
||||
ORDER BY created_at,id OFFSET (SELECT count(*)*8/10 FROM messages WHERE chat_id=$1) LIMIT 1`, chatID).Scan(&position.ID, &position.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cases = append(cases, readCase{item.name + "_first", chatID, nil}, readCase{item.name + "_deep", chatID, position})
|
||||
}
|
||||
stage = "initial-digest"
|
||||
before, err := f.messageDigest(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var trials []map[string]any
|
||||
for round := 0; round < series; round++ {
|
||||
order := []string{"A", "B"}
|
||||
if round%2 == 1 {
|
||||
order = []string{"B", "A"}
|
||||
}
|
||||
for ordinal, variant := range order {
|
||||
stage = "vacuum-" + variant
|
||||
// Remove dead tuples and reset physical bloat between trials, outside timing.
|
||||
if _, err = f.pool.Exec(ctx, "VACUUM (FULL, ANALYZE) messages"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
columns := "chat_id"
|
||||
if variant == "B" {
|
||||
columns = "chat_id,created_at,id"
|
||||
}
|
||||
buildStart := time.Now()
|
||||
stage = "build-index-" + variant
|
||||
if _, err = f.pool.Exec(ctx, "CREATE INDEX lab2_history_variant ON messages("+columns+")"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buildMS := float64(time.Since(buildStart).Microseconds()) / 1000
|
||||
if _, err = f.pool.Exec(ctx, "ANALYZE messages"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var indexBytes, tableBytes int64
|
||||
if err = f.pool.QueryRow(ctx, "SELECT pg_relation_size('lab2_history_variant'),pg_relation_size('messages')").Scan(&indexBytes, &tableBytes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
readResults := map[string]any{}
|
||||
for _, c := range cases {
|
||||
stage = "warmup-" + variant + "-" + c.name
|
||||
for warmup := 0; warmup < 5; warmup++ {
|
||||
if _, err = f.readChat(ctx, c.chat, c.after); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var timings []time.Duration
|
||||
var raw []float64
|
||||
started := time.Now()
|
||||
stage = "read-" + variant + "-" + c.name
|
||||
for n := 0; n < repetitions; n++ {
|
||||
d, readErr := f.readChat(ctx, c.chat, c.after)
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
timings = append(timings, d)
|
||||
raw = append(raw, float64(d.Microseconds())/1000)
|
||||
}
|
||||
elapsed := time.Since(started).Seconds()
|
||||
stage = "plan-" + variant + "-" + c.name
|
||||
plan, planErr := f.planChat(ctx, c.chat, c.after)
|
||||
if planErr != nil {
|
||||
return nil, planErr
|
||||
}
|
||||
readResults[c.name] = map[string]any{"samples_ms": raw, "latency_ms": latency(timings), "successful_rps": float64(repetitions) / elapsed, "elapsed_seconds": elapsed, "plan": plan}
|
||||
}
|
||||
var writes []time.Duration
|
||||
var writeMS []float64
|
||||
var walBytes []int64
|
||||
for n := 0; n < batches; n++ {
|
||||
stage = "write-" + variant
|
||||
var lsn string
|
||||
if err = f.pool.QueryRow(ctx, "SELECT pg_current_wal_insert_lsn()::text").Scan(&lsn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
started := time.Now()
|
||||
tx, txErr := f.pool.Begin(ctx)
|
||||
if txErr != nil {
|
||||
return nil, txErr
|
||||
}
|
||||
_, txErr = tx.Exec(ctx, `INSERT INTO messages(chat_id,sender_id,text)
|
||||
SELECT $1::uuid,$2::uuid,rpad('research-write-'||n,256,'x') FROM generate_series(1,200) n`, f.chats[0], f.user)
|
||||
if txErr == nil {
|
||||
txErr = tx.Commit(ctx)
|
||||
} else {
|
||||
_ = tx.Rollback(context.Background())
|
||||
}
|
||||
if txErr != nil {
|
||||
return nil, txErr
|
||||
}
|
||||
d := time.Since(started)
|
||||
writes = append(writes, d)
|
||||
writeMS = append(writeMS, float64(d.Microseconds())/1000)
|
||||
var delta int64
|
||||
if err = f.pool.QueryRow(ctx, "SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(),$1::pg_lsn)::bigint", lsn).Scan(&delta); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
walBytes = append(walBytes, delta)
|
||||
}
|
||||
stage = "delete-fixture-writes-" + variant
|
||||
if _, err = f.pool.Exec(ctx, "DELETE FROM messages WHERE text LIKE 'research-write-%'"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stage = "verify-dataset-" + variant
|
||||
after, digestErr := f.messageDigest(ctx)
|
||||
if digestErr != nil || after != before {
|
||||
return nil, errors.New("logical dataset changed between trials")
|
||||
}
|
||||
trials = append(trials, map[string]any{"series": round + 1, "order": ordinal + 1, "variant": variant, "columns": columns, "read_cases": readResults, "index_bytes": indexBytes, "table_bytes": tableBytes, "build_ms": buildMS, "insert_200_with_commit_ms": latency(writes), "write_samples_ms": writeMS, "write_wal_bytes": walBytes, "dataset_sha256": before})
|
||||
fmt.Fprintf(os.Stderr, "series %d variant %s complete\n", round+1, variant)
|
||||
stage = "drop-index-" + variant
|
||||
if _, err = f.pool.Exec(ctx, "DROP INDEX lab2_history_variant"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return map[string]any{"mode": "research", "rows": rows, "chat_counts": []int{rows * 70 / 100, rows * 20 / 100, rows * 6 / 100, rows * 3 / 100, rows / 100}, "payload_bytes": 256, "postgres_version": version, "series": series, "reads_per_case": repetitions, "write_batches_per_trial": batches, "rows_per_write_batch": 200, "warmup_per_case": 5, "concurrent_clients": 1, "sql_experiment_timeout_seconds": 10, "application_repository_timeout_seconds": 1, "dataset_sha256": before, "trials": trials, "limitations": "Warm sequential closed-loop SQL through the same generated sqlc query; no HTTP/KDF. Offline query budget 10s, application repository unchanged at 1s. Same logical rows, VACUUM FULL and rebuild before trials. pgx prepared-plan behavior is retained. WAL is cluster-wide on a dedicated quiet instance; sampled CPU includes administration. No cold-cache or sustained-capacity claim."}, nil
|
||||
}
|
||||
|
||||
func (f *fixture) researchRead(ctx context.Context, chatID string, after *repository2.MessagePosition) ([]*model.Message, error) {
|
||||
queryCtx, cancel := context.WithTimeout(ctx, f.researchBudget)
|
||||
defer cancel()
|
||||
var id pgtype.UUID
|
||||
if err := id.Scan(chatID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
params := sqlc.GetMessagesByChatIDParams{ChatID: id, LimitCount: 51}
|
||||
if after != nil {
|
||||
params.AfterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
||||
if err := params.AfterID.Scan(after.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
rows, err := sqlc.New(f.pool).GetMessagesByChatID(queryCtx, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]*model.Message, len(rows))
|
||||
for i, m := range rows {
|
||||
items[i] = &model.Message{ID: m.ID.String(), ChatID: m.ChatID.String(), SenderID: m.SenderID.String(), Text: m.Text, CreatedAt: m.CreatedAt.Time}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (f *fixture) messageDigest(ctx context.Context) (string, error) {
|
||||
rows, err := f.pool.Query(ctx, "SELECT row_to_json(m)::text FROM messages m ORDER BY id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
h := sha256.New()
|
||||
for rows.Next() {
|
||||
var line string
|
||||
if err = rows.Scan(&line); err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, _ = fmt.Fprintln(h, line)
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rebuild the report's index-comparison aggregates from retained raw samples.
|
||||
|
||||
This reads evidence only; it never starts a database or changes test assertions.
|
||||
Nearest-rank percentiles match sqlprobe. No confidence/SLO claim is implied.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
|
||||
|
||||
def percentile(values, percent):
|
||||
ordered = sorted(values)
|
||||
if not ordered or any(not math.isfinite(v) or v < 0 for v in ordered):
|
||||
raise ValueError('Missing or invalid timing samples')
|
||||
return ordered[max(0, math.ceil(len(ordered) * percent / 100) - 1)]
|
||||
|
||||
|
||||
def summarize(directory):
|
||||
data = json.loads((directory / 'indexes.json').read_text())
|
||||
trials = data['trials']
|
||||
if len(trials) != data['series'] * 2 or any(t['dataset_sha256'] != data['dataset_sha256'] for t in trials):
|
||||
raise ValueError('Incomplete trials or changed logical dataset')
|
||||
rows, writes = [], []
|
||||
for variant in ('A', 'B'):
|
||||
selected = [t for t in trials if t['variant'] == variant]
|
||||
if len(selected) != data['series']:
|
||||
raise ValueError('Unbalanced A/B series')
|
||||
for case in ('large_first', 'large_deep', 'medium_first', 'medium_deep', 'small_first', 'small_deep'):
|
||||
if any(len(t['read_cases'][case]['samples_ms']) != data['reads_per_case'] for t in selected):
|
||||
raise ValueError('Read sample count differs from the protocol')
|
||||
samples = [x for t in selected for x in t['read_cases'][case]['samples_ms']]
|
||||
elapsed = sum(t['read_cases'][case]['elapsed_seconds'] for t in selected)
|
||||
rows.append({'case': case, 'variant': variant, 'n': len(samples),
|
||||
**{'p' + str(p) + '_ms': percentile(samples, p) for p in (50, 95, 99)},
|
||||
'successful_rps': len(samples) / elapsed,
|
||||
'trial_p50_min': min(t['read_cases'][case]['latency_ms']['p50'] for t in selected),
|
||||
'trial_p50_max': max(t['read_cases'][case]['latency_ms']['p50'] for t in selected)})
|
||||
if any(len(t['write_samples_ms']) != data['write_batches_per_trial'] for t in selected):
|
||||
raise ValueError('Write sample count differs from the protocol')
|
||||
samples = [x for t in selected for x in t['write_samples_ms']]
|
||||
wal = [x for t in selected for x in t['write_wal_bytes']]
|
||||
writes.append({'variant': variant, 'batches': len(samples), 'rows_per_batch': data['rows_per_write_batch'],
|
||||
**{'p' + str(p) + '_ms': percentile(samples, p) for p in (50, 95, 99)},
|
||||
'median_wal_bytes': statistics.median(wal), 'index_bytes': selected[0]['index_bytes'],
|
||||
'median_build_ms': statistics.median(t['build_ms'] for t in selected)})
|
||||
rows.sort(key=lambda row: (row['case'], row['variant']))
|
||||
report = {'status': 'PASS', 'scope': 'index observations only; full run status is summary.json',
|
||||
'read_requests': sum(r['n'] for r in rows), 'read_errors': 0,
|
||||
'read_cases': rows, 'write_variants': writes}
|
||||
with (directory / 'READS.csv').open('w', newline='') as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
(directory / 'comparison-summary.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||||
print('PASS: aggregates rebuilt from ' + str(report['read_requests']) + ' retained read samples')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('directory', type=Path)
|
||||
summarize(parser.parse_args().directory.resolve())
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Offline regression tests for the test harness, not evidence about the API."""
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import run as harness
|
||||
|
||||
|
||||
class HarnessTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.config = json.loads(Path(__file__).with_name("config.example.json").read_text())
|
||||
|
||||
def test_default_all_is_blocked_and_does_not_pretend_success(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory) / "result.json"
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if key not in ("LAB2_BASE_URL", "LAB2_EXPIRY_BASE_URL", "LAB2_TEST_DATABASE_URL", "LAB2_RESTORED_DATABASE_URL")}
|
||||
result = subprocess.run([sys.executable, str(Path(harness.__file__)), "--suite", "all", "--output", str(output)],
|
||||
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
items = json.loads(output.read_text())["results"]
|
||||
self.assertGreater(len(items), 10)
|
||||
self.assertTrue(all(item["status"] == "BLOCKED" for item in items))
|
||||
|
||||
def test_hooks_need_both_explicit_opt_in_and_real_configuration(self):
|
||||
h = harness.Harness(self.config, Path(__file__))
|
||||
with self.assertRaises(harness.Blocked):
|
||||
h.require_hooks("stop_postgres")
|
||||
h.allow_hooks = True
|
||||
with self.assertRaises(harness.Blocked):
|
||||
h.require_hooks("stop_postgres")
|
||||
|
||||
def test_recovery_runs_even_when_failure_hook_partially_fails(self):
|
||||
config = copy.deepcopy(self.config)
|
||||
config["hooks"].update(stop_postgres=["not-executed"], start_postgres=["not-executed"])
|
||||
h = harness.Harness(config, Path(__file__), True)
|
||||
calls = []
|
||||
|
||||
def hook(name):
|
||||
calls.append(name)
|
||||
if name == "stop_postgres":
|
||||
raise harness.Failure("synthetic partial failure")
|
||||
|
||||
h.hook = hook
|
||||
with self.assertRaises(harness.Failure):
|
||||
with h.disruption("stop_postgres", "start_postgres"):
|
||||
self.fail("failed setup must not execute test body")
|
||||
self.assertEqual(calls, ["stop_postgres", "start_postgres"])
|
||||
|
||||
def test_adapter_output_is_not_exposed_on_failure(self):
|
||||
with self.assertRaises(harness.Failure) as error:
|
||||
harness.bounded_command([sys.executable, "-c", "print('synthetic-private-marker'); raise SystemExit(7)"],
|
||||
Path(__file__).parent, 3)
|
||||
self.assertNotIn("synthetic-private-marker", str(error.exception))
|
||||
|
||||
def test_unimplemented_adapter_is_blocked(self):
|
||||
with self.assertRaises(harness.Blocked):
|
||||
harness.bounded_command([sys.executable, "-c", "raise SystemExit(2)"], Path(__file__).parent, 3)
|
||||
|
||||
def test_counter_reset_missing_and_boolean_do_not_pass(self):
|
||||
for before, after in (({}, {}), ({"sql_queries": 5}, {"sql_queries": 4}),
|
||||
({"sql_queries": False}, {"sql_queries": True})):
|
||||
with self.subTest(before=before):
|
||||
with self.assertRaises(harness.Failure):
|
||||
harness.counter_delta(before, after, "sql_queries")
|
||||
self.assertEqual(harness.counter_delta({"sql_queries": 5}, {"sql_queries": 8}, "sql_queries"), 3)
|
||||
|
||||
def test_snapshot_comparison_rejects_missing_changed_or_same_database(self):
|
||||
tables = {name: {"rows": 3, "sha256": "a" * 64}
|
||||
for name in ("users", "chats", "chat_members", "messages")}
|
||||
source = {"identity_sha256": "source", "empty": False, "tables": tables}
|
||||
restored = dict(source, identity_sha256="target")
|
||||
harness.compare_snapshots(source, restored)
|
||||
for broken in (source, dict(restored, tables={}), dict(restored, empty=True)):
|
||||
with self.assertRaises(harness.Failure):
|
||||
harness.compare_snapshots(source, broken)
|
||||
broken = copy.deepcopy(restored)
|
||||
broken["tables"]["messages"]["sha256"] = "b" * 64
|
||||
with self.assertRaises(harness.Failure):
|
||||
harness.compare_snapshots(source, broken)
|
||||
|
||||
def test_client_timeout_is_failure_not_a_successful_server_timeout(self):
|
||||
config = copy.deepcopy(self.config)
|
||||
config["hooks"].update(block_query=["not-executed"], unblock_query=["not-executed"])
|
||||
h = harness.Harness(config, Path(__file__), True)
|
||||
calls = []
|
||||
h.hook = lambda name: calls.append(name)
|
||||
|
||||
class FakeClient:
|
||||
def user(self, _):
|
||||
return {"id": "fixture", "token": "never-printed"}
|
||||
|
||||
def call(self, method, path, expected=200, **kwargs):
|
||||
if expected == 503:
|
||||
raise harness.Failure("connection timeout")
|
||||
return {}
|
||||
|
||||
h.client = lambda **_: FakeClient()
|
||||
with self.assertRaises(harness.Failure):
|
||||
h.timeout("query")
|
||||
self.assertEqual(calls, ["block_query", "unblock_query"])
|
||||
|
||||
def test_fixture_size_thresholds_are_not_silently_lowered(self):
|
||||
for key, value in (("plan_rows", 9999), ("research_rows", 99999), ("repetitions", 1)):
|
||||
config = copy.deepcopy(self.config)
|
||||
config["sql"][key] = value
|
||||
with self.assertRaises(harness.Failure):
|
||||
harness.validate_config(config)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,179 @@
|
||||
# Собственные проверки lab3 на оценку «4»
|
||||
|
||||
`run.py` создаёт только синтетические данные через **публичный адрес LB** из
|
||||
`base_url`. Адрес прямой API-реплики недопустим. Нужны Python 3.9+, запущенный
|
||||
стенд и действующий TTL сессии не менее 300 секунд. Тестовые пользователи,
|
||||
токены и сообщения не удаляются, так как контракт не содержит delete для них.
|
||||
|
||||
```sh
|
||||
cp student-tests/lab3/config.example.json student-tests/lab3/config.local.json
|
||||
# В config.local.json указать реальный публичный адрес LB и hooks.
|
||||
python3 student-tests/lab3/run.py \
|
||||
--config student-tests/lab3/config.local.json \
|
||||
--output student-tests/output/lab3-run-01 --scenario all
|
||||
|
||||
# Только повтор того же сообщения/ключа с прежним токеном после restart hook:
|
||||
python3 student-tests/lab3/run.py \
|
||||
--config student-tests/lab3/config.example.json \
|
||||
--output student-tests/output/lab3-restart --scenario restart
|
||||
|
||||
# Публичный persistence + Docker StartedAt/volumes + повтор по исходному ключу:
|
||||
python3 student-tests/lab3/prove_persistence.py \
|
||||
--project highload-lab3 --base-url http://127.0.0.1:8080 \
|
||||
--output student-tests/output/lab3-persistence
|
||||
```
|
||||
|
||||
`config.local.json` содержит только пути/адреса, но его не нужно коммитить.
|
||||
Каждый запуск пишет `events.jsonl` (сырые счётчики, длительности, ID реплик),
|
||||
`summary.json` и stdout/stderr публичных make-команд в указанный каталог.
|
||||
Токены и пароли в артефакты не записываются. Ненулевой exit code означает
|
||||
`FAIL` **или** `PENDING_INFRA`; пропуск не становится PASS.
|
||||
|
||||
## Покрытие
|
||||
|
||||
**Обязательный уровень 3:** отрицательные/граничные ключи 1–128 ASCII,
|
||||
исходный `201` и тот же Message при повторе, `409` без записи, независимость
|
||||
пользователя/чата, конкурентный повтор через разные `X-Instance-Id`, повтор
|
||||
через другую реплику, повтор после потерянного ответа, рестарта, отказа,
|
||||
реального клиентского таймаута с управляемой задержкой,
|
||||
повторную проверку отозванной сессии и доступа. Сценарий обрыва закрывает
|
||||
соединение после передачи полного запроса; он проверяет безопасный повтор
|
||||
независимо от того, успел ли первый запрос завершиться. Проверка доступа после
|
||||
изменения членства требует `revoke_access`/`restore_access`: обязательный API
|
||||
не позволяет менять участников. В одноразовом проекте собственный адаптер
|
||||
временно переносит ровно одно синтетическое сообщение другому участнику того
|
||||
же чата, удаляет исходного участника, а затем восстанавливает членство и
|
||||
отправителя. Все операции ограничены точными UUID и проверяют затронутые
|
||||
строки; вне одноразового проекта этот адаптер отказывается работать.
|
||||
|
||||
**Обязательный уровень 4:** два наблюдаемых процесса за LB; поочерёдная
|
||||
остановка и восстановление каждой реплики с прежним токеном и данными;
|
||||
успешные RPS, ошибки, время восстановления чтения и записи от начала stop;
|
||||
`live=200`/`ready=503` на неготовой реплике и её исключение LB; проверка
|
||||
прекращения приёма после SIGTERM; CPU/RAM-лимиты всех Compose-сервисов,
|
||||
закрытые порты API, отсутствие `container_name`, healthcheck и stop grace;
|
||||
поочерёдное обновление под нагрузкой; фактический однократный старт миграций.
|
||||
Текущий `compose.yaml` задаёт две API-реплики за LB. Сценарии с отдельными
|
||||
fault-injection/rolling adapters остаются `PENDING_INFRA`, пока не настроены
|
||||
соответствующие hooks; наличие двух контейнеров само по себе их не заменяет.
|
||||
|
||||
**Дополнительная проверка качества:** во время rolling update требуется ноль
|
||||
ошибок HTTP. Это строже буквального критерия «проверена под нагрузкой»;
|
||||
она выводится отдельным `rolling_update_zero_http_errors_quality`, а смена
|
||||
Docker ID и работа под нагрузкой — отдельным `rolling_update_under_load`.
|
||||
|
||||
Публичные `make test`, `make test-persistence ACTION_SCRIPT=...` и
|
||||
`make test-failover ACTION_SCRIPT=...` входят в `--scenario all` и запускаются
|
||||
также отдельно через `--scenario public`. Для второго и третьего требуются
|
||||
hooks `restart`, `stop_one`; после публичного failover обязательно вызывается
|
||||
`recover_all`. Собственный failover вызывает `stop_one`/`start_one` для каждого
|
||||
наблюдаемого alias. Action script должен быстро вернуть 0 и оставить выбранную
|
||||
реплику остановленной до `start_one`. Нельзя делать `down -v` или менять чужие
|
||||
данные.
|
||||
|
||||
`prove_persistence.py` явно принимает имя Compose-проекта и сохраняет
|
||||
`summary.json`, `lifecycle.jsonl`, stdout/stderr обоих HTTP-сценариев. Проверка
|
||||
сравнивает **каждый** API-контейнер, PostgreSQL, Redis и LB по Docker ID,
|
||||
`StartedAt` и именам volumes; публичный сценарий проверяет прежний токен и
|
||||
сообщение, lab3-сценарий — исходный `201`/Message при повторе ключа после
|
||||
перезапуска. Эти файлы можно цитировать в `REPORT.md`, без токенов и паролей.
|
||||
Изолированный `student-tests/stack.py verify` создаёт отдельный Compose-проект
|
||||
с собственным публичным портом LB и одной API-репликой для прежнего lab2
|
||||
профиля. Только в этом одноразовом проекте loopback-порт API используется
|
||||
старыми проверками dependency/TTL, которым нужен ответ самого API при
|
||||
исключении всех backend из LB. Публичные и lab3-сценарии идут через LB.
|
||||
Runner записывает lifecycle-снимки вокруг persistence-этапов.
|
||||
Для короткой проверки именно этих этапов в одноразовом проекте:
|
||||
|
||||
```sh
|
||||
.venv/bin/python student-tests/stack.py verify --persistence-only --pull never \
|
||||
--output student-tests/output/lab3-isolated-persistence
|
||||
|
||||
# Полный lab3-прогон в отдельном проекте с двумя API и LB:
|
||||
.venv/bin/python student-tests/stack.py verify --lab3-only --pull never \
|
||||
--output student-tests/output/lab3-isolated-level4
|
||||
|
||||
# Только rolling и отдельный строгий порог нуля ошибок в новом проекте:
|
||||
.venv/bin/python student-tests/stack.py verify --lab3-only \
|
||||
--lab3-scenario rolling --pull never \
|
||||
--output student-tests/output/lab3-isolated-rolling
|
||||
|
||||
# Только идемпотентность, включая повторную проверку доступа:
|
||||
.venv/bin/python student-tests/stack.py verify --lab3-only \
|
||||
--lab3-scenario idempotency --pull never \
|
||||
--output student-tests/output/lab3-isolated-idempotency
|
||||
|
||||
# Один rolling в двухсетевой схеме полного профиля с Docker/API/LB логами:
|
||||
.venv/bin/python student-tests/stack.py verify --lab3-only \
|
||||
--lab3-scenario rolling-dual --pull never \
|
||||
--output student-tests/output/lab3-rolling-dual-diagnostic
|
||||
```
|
||||
|
||||
Полный изолированный профиль использует сети `front` и `state`, чтобы
|
||||
отключить только доступ выбранного API к хранилищам и получить локальные
|
||||
`live=200`, `ready=503`, сохранив путь LB к этой реплике. Рабочий rolling-скрипт
|
||||
рассчитан на одну сеть, поэтому временный Docker CLI адаптер полного профиля
|
||||
возвращает ему реальный IP сети `front` для его одного шаблона `docker inspect`;
|
||||
остальные команды передаются без изменений. Целевой `--lab3-scenario rolling`
|
||||
использует одну сеть, как основной Compose-проект, и запускает скрипт напрямую.
|
||||
`--lab3-scenario rolling-dual` сохраняет двухсетевую схему, timeout клиента
|
||||
1 с и строгий нулевой порог, а также записывает UTC миллисекунды для ошибок,
|
||||
шагов Docker, Docker events и поточные логи LB/API до удаления проекта.
|
||||
|
||||
В `summary.json` при этом стоит `scope=persistence-only`; такой PASS не
|
||||
обозначает прохождение полного `verify`.
|
||||
|
||||
## Формат hooks
|
||||
|
||||
В `hooks` задаются массивы аргументов без shell interpolation, например:
|
||||
|
||||
```json
|
||||
{
|
||||
"stop_one": ["scripts/stop-one.sh"],
|
||||
"start_one": ["scripts/start-one.sh"],
|
||||
"recover_all": ["scripts/recover-all.sh"],
|
||||
"restart": ["scripts/restart.sh"],
|
||||
"make_unready": ["scripts/test-make-unready.sh"],
|
||||
"restore_ready": ["scripts/test-restore-ready.sh"],
|
||||
"probe_health": ["scripts/test-probe-health.sh"],
|
||||
"lb_timing_evidence": ["scripts/test-lb-timing.sh"],
|
||||
"sigterm_one": ["scripts/test-sigterm-one.sh"],
|
||||
"probe_stopped": ["scripts/test-probe-stopped.sh"],
|
||||
"rolling_update": ["scripts/test-rolling-update.sh"],
|
||||
"migration_evidence": ["scripts/test-migration-evidence.sh"],
|
||||
"revoke_access": ["scripts/test-revoke-access.sh"],
|
||||
"restore_access": ["scripts/test-restore-access.sh"]
|
||||
}
|
||||
```
|
||||
|
||||
Это **примеры имён адаптеров, не файлы, которые тест создаёт**. Для выбранной
|
||||
Compose/Swarm схемы оператор реализует их отдельно. `TARGET_INSTANCE_ID`
|
||||
передаётся в hooks выбранной реплики. Для изменения членства дополнительно
|
||||
передаются `TEST_CHAT_ID` и `TEST_USER_ID` синтетической фикстуры.
|
||||
Таймаут проверяется встроенным одноразовым HTTP-прокси: он пересылает запрос
|
||||
на публичный LB, дожидается HTTP 201 от сервера, задерживает ответ клиенту и
|
||||
подтверждает запись в истории перед повтором. Отдельный fault hook не нужен.
|
||||
`probe_health` возвращает `{"live_status":200,"ready_status":503}` на выбранной частной
|
||||
реплике; `probe_stopped` возвращает `{"accepting":false}` после SIGTERM.
|
||||
`migration_evidence` возвращает JSON с реально записанным числом стартов
|
||||
мигратора и порядком запуска:
|
||||
|
||||
```json
|
||||
{"migration_starts":1,"migration_exit_code":0,"api_started_before_migration_complete":false}
|
||||
```
|
||||
|
||||
`lb_timing_evidence` возвращает
|
||||
`{"health_interval_seconds":1,"health_timeout_seconds":1,"configured_max_detection_seconds":5}`
|
||||
по действующей конфигурации LB. `rolling_update` возвращает JSON
|
||||
`{"replaced_processes":2,"min_ready_during_update":1}` после завершения
|
||||
поочерёдной замены; runner параллельно измеряет HTTP-ответы через LB.
|
||||
|
||||
Текущего состояния `compose ps` недостаточно для доказательства числа запусков.
|
||||
Метод регистрации lifecycle и совместимость миграции с работающей версией
|
||||
объясняются в `REPORT.md`; тест не подменяет это доказательство. Там же нужны
|
||||
версии образов, параметры LB health interval/timeout и максимальное время
|
||||
обнаружения, аппаратные ресурсы и привязка alias к реальным контейнерам.
|
||||
|
||||
Проверка RPS использует простой последовательный closed-loop клиент. Он
|
||||
показывает доступность при отказе, а не предельную пропускную способность.
|
||||
Сравнение производительности для уровня 5 требует отдельного эксперимента.
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"base_url": "http://127.0.0.1:8080",
|
||||
"request_timeout_seconds": 3,
|
||||
"concurrency": 12,
|
||||
"failover_window_seconds": 15,
|
||||
"rolling_window_seconds": 20,
|
||||
"compose_config_argv": ["docker", "compose", "config", "--format", "json"],
|
||||
"api_services": ["api"],
|
||||
"lb_services": ["lb"],
|
||||
"hooks": {
|
||||
"restart": ["scripts/restart.sh"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fault adapters restricted to a disposable lab3 Compose project."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
import stack # noqa: E402
|
||||
|
||||
|
||||
def execute(argv, allow_failure=False, timeout=30):
|
||||
result = subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if result.returncode and not allow_failure:
|
||||
raise RuntimeError("test Docker action failed")
|
||||
return result
|
||||
|
||||
|
||||
def owned_project():
|
||||
project = os.environ.get("COMPOSE_PROJECT_NAME", "")
|
||||
if not re.fullmatch(r"lab3-test-[a-f0-9]{12}", project):
|
||||
raise RuntimeError("fault hooks require an isolated lab3-test-* Compose project")
|
||||
if not os.environ.get("COMPOSE_FILE"):
|
||||
raise RuntimeError("COMPOSE_FILE must identify the isolated project override")
|
||||
return project, stack.compose_base(os.environ)
|
||||
|
||||
|
||||
def inspect(identifier):
|
||||
value = json.loads(execute(["docker", "inspect", identifier]).stdout)
|
||||
if len(value) != 1:
|
||||
raise RuntimeError("Docker inspect did not select one container")
|
||||
return value[0]
|
||||
|
||||
|
||||
def api_map(project, base):
|
||||
ids = execute(base + ["ps", "-aq", "api"]).stdout.split()
|
||||
if len(ids) != 2:
|
||||
raise RuntimeError("isolated project needs exactly two API containers")
|
||||
mapped = {}
|
||||
for identifier in ids:
|
||||
value = inspect(identifier)
|
||||
labels = value["Config"]["Labels"]
|
||||
if labels.get("com.docker.compose.project") != project or labels.get("com.docker.compose.service") != "api":
|
||||
raise RuntimeError("API container ownership mismatch")
|
||||
alias = value["Config"]["Hostname"]
|
||||
if alias in mapped:
|
||||
raise RuntimeError("duplicate API alias")
|
||||
mapped[alias] = value
|
||||
return mapped
|
||||
|
||||
|
||||
def target(project, base):
|
||||
alias = os.environ.get("TARGET_INSTANCE_ID", "")
|
||||
mapped = api_map(project, base)
|
||||
if alias not in mapped:
|
||||
raise RuntimeError("TARGET_INSTANCE_ID is not an owned API alias")
|
||||
return mapped[alias]
|
||||
|
||||
|
||||
def wait_healthy(identifier, seconds=30):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
state = inspect(identifier)["State"]
|
||||
if state["Running"] and state.get("Health", {}).get("Status") == "healthy":
|
||||
return
|
||||
time.sleep(.2)
|
||||
raise RuntimeError("API did not regain Docker readiness")
|
||||
|
||||
|
||||
def state_network(project):
|
||||
name = os.environ.get("HL_STATE_NETWORK", "")
|
||||
if name != project + "_state":
|
||||
raise RuntimeError("state network must belong to isolated project")
|
||||
network = json.loads(execute(["docker", "network", "inspect", name]).stdout)[0]
|
||||
if network["Labels"].get("com.docker.compose.project") != project:
|
||||
raise RuntimeError("state network ownership mismatch")
|
||||
return name
|
||||
|
||||
|
||||
def http_status_inside(identifier, path):
|
||||
result = execute(["docker", "exec", identifier, "wget", "-S", "-O", "/dev/null",
|
||||
"http://127.0.0.1:8080" + path], allow_failure=True, timeout=5)
|
||||
found = re.findall(r"HTTP/\d(?:\.\d)?\s+(\d{3})", result.stderr + result.stdout)
|
||||
if not found:
|
||||
raise RuntimeError("cannot read internal HTTP status")
|
||||
return int(found[-1])
|
||||
|
||||
|
||||
def lb_timing():
|
||||
source = (ROOT / "infra/haproxy.cfg").read_text()
|
||||
check = re.search(r"timeout check\s+(\d+)s", source)
|
||||
server = re.search(r"server-template[^\n]*\binter\s+(\d+)s\s+fall\s+(\d+)", source)
|
||||
if not check or not server:
|
||||
raise RuntimeError("cannot derive LB health timing from HAProxy config")
|
||||
timeout, interval, failures = int(check[1]), int(server[1]), int(server[2])
|
||||
print(json.dumps({"health_interval_seconds": interval, "health_timeout_seconds": timeout,
|
||||
"configured_max_detection_seconds": interval * failures + timeout}))
|
||||
|
||||
|
||||
def migration_evidence(project):
|
||||
path = Path(os.environ["HL_MIGRATION_EVIDENCE"])
|
||||
value = json.loads(path.read_text())
|
||||
if value.get("project") != project:
|
||||
raise RuntimeError("migration evidence belongs to another project")
|
||||
print(json.dumps(value))
|
||||
|
||||
|
||||
def access_action(project, base, action):
|
||||
chat = str(uuid.UUID(os.environ["TEST_CHAT_ID"]))
|
||||
owner = str(uuid.UUID(os.environ["TEST_USER_ID"]))
|
||||
replacement = str(uuid.UUID(os.environ["TEST_REPLACEMENT_USER_ID"]))
|
||||
message = str(uuid.UUID(os.environ["TEST_MESSAGE_ID"]))
|
||||
key = os.environ["TEST_IDEMPOTENCY_KEY"]
|
||||
if owner == replacement or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
|
||||
raise RuntimeError("invalid isolated access fixture")
|
||||
ids = execute(base + ["ps", "-q", "postgres"]).stdout.split()
|
||||
if len(ids) != 1:
|
||||
raise RuntimeError("isolated project must have exactly one running PostgreSQL")
|
||||
raw = inspect(ids[0])
|
||||
labels = raw["Config"]["Labels"]
|
||||
if labels.get("com.docker.compose.project") != project or labels.get("com.docker.compose.service") != "postgres":
|
||||
raise RuntimeError("PostgreSQL container ownership mismatch")
|
||||
if action == "revoke_access":
|
||||
statement = f"""
|
||||
DO $lab3$ DECLARE affected integer; BEGIN
|
||||
IF (SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}') <> 1 OR
|
||||
(SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{replacement}') <> 1 OR
|
||||
(SELECT count(*) FROM messages WHERE chat_id='{chat}' AND sender_id='{owner}') <> 1 OR
|
||||
(SELECT count(*) FROM messages WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}') <> 1 OR
|
||||
(SELECT count(*) FROM message_idempotency WHERE user_id='{owner}' AND chat_id='{chat}'
|
||||
AND idempotency_key='{key}' AND message_id='{message}') <> 1 THEN
|
||||
RAISE EXCEPTION 'synthetic access fixture precondition failed';
|
||||
END IF;
|
||||
UPDATE messages SET sender_id='{replacement}' WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}';
|
||||
GET DIAGNOSTICS affected = ROW_COUNT;
|
||||
IF affected <> 1 THEN RAISE EXCEPTION 'message reassignment was not unique'; END IF;
|
||||
DELETE FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}';
|
||||
GET DIAGNOSTICS affected = ROW_COUNT;
|
||||
IF affected <> 1 THEN RAISE EXCEPTION 'membership deletion was not unique'; END IF;
|
||||
END $lab3$;
|
||||
"""
|
||||
else:
|
||||
statement = f"""
|
||||
DO $lab3$ DECLARE affected integer; BEGIN
|
||||
INSERT INTO chat_members(chat_id,user_id) VALUES('{chat}','{owner}') ON CONFLICT DO NOTHING;
|
||||
UPDATE messages SET sender_id='{owner}' WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{replacement}';
|
||||
GET DIAGNOSTICS affected = ROW_COUNT;
|
||||
IF affected > 1 OR
|
||||
(SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}') <> 1 OR
|
||||
(SELECT count(*) FROM messages WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}') <> 1 OR
|
||||
(SELECT count(*) FROM message_idempotency WHERE user_id='{owner}' AND chat_id='{chat}'
|
||||
AND idempotency_key='{key}' AND message_id='{message}') <> 1 THEN
|
||||
RAISE EXCEPTION 'synthetic access fixture restoration failed';
|
||||
END IF;
|
||||
END $lab3$;
|
||||
"""
|
||||
execute(["docker", "exec", ids[0], "psql", "-X", "-v", "ON_ERROR_STOP=1", "-U", "messenger",
|
||||
"-d", "messenger", "-c", statement])
|
||||
print(json.dumps({"action": action, "project": project, "chat_id": chat,
|
||||
"user_id": owner, "replacement_user_id": replacement,
|
||||
"message_id": message, "validated_exact_message": True,
|
||||
"membership_present_after": action == "restore_access"}))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("start_one", "recover_all", "sigterm_one",
|
||||
"probe_stopped", "make_unready", "restore_ready",
|
||||
"probe_health",
|
||||
"lb_timing_evidence", "migration_evidence",
|
||||
"revoke_access", "restore_access"))
|
||||
args = parser.parse_args()
|
||||
project, base = owned_project()
|
||||
action = args.action
|
||||
if action == "lb_timing_evidence":
|
||||
lb_timing()
|
||||
elif action == "migration_evidence":
|
||||
migration_evidence(project)
|
||||
elif action in ("revoke_access", "restore_access"):
|
||||
access_action(project, base, action)
|
||||
elif action == "recover_all":
|
||||
for value in api_map(project, base).values():
|
||||
if not value["State"]["Running"]:
|
||||
execute(["docker", "start", value["Id"]])
|
||||
wait_healthy(value["Id"])
|
||||
else:
|
||||
value = target(project, base)
|
||||
identifier = value["Id"]
|
||||
if action == "start_one":
|
||||
if not value["State"]["Running"]:
|
||||
execute(["docker", "start", identifier])
|
||||
wait_healthy(identifier)
|
||||
elif action == "sigterm_one":
|
||||
execute(["docker", "stop", "--time", "18", identifier], timeout=25)
|
||||
if inspect(identifier)["State"]["Running"]:
|
||||
raise RuntimeError("SIGTERM did not stop selected API")
|
||||
elif action == "probe_stopped":
|
||||
print(json.dumps({"accepting": bool(inspect(identifier)["State"]["Running"])}))
|
||||
elif action == "make_unready":
|
||||
execute(["docker", "network", "disconnect", state_network(project), identifier])
|
||||
elif action == "restore_ready":
|
||||
execute(["docker", "network", "connect", state_network(project), identifier])
|
||||
wait_healthy(identifier)
|
||||
elif action == "probe_health":
|
||||
print(json.dumps({"live_status": http_status_inside(identifier, "/health/live"),
|
||||
"ready_status": http_status_inside(identifier, "/health/ready")}))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, ValueError, KeyError, RuntimeError, subprocess.TimeoutExpired) as exc:
|
||||
print("FAIL: lab3 Docker action " + type(exc).__name__, file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run public persistence and lab3 replay with Docker lifecycle evidence."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
import stack # noqa: E402
|
||||
|
||||
TARGETS = ["api", "postgres", "redis", "lb"]
|
||||
|
||||
|
||||
def run_case(name, argv, base, env, output, summary):
|
||||
before = stack.snapshot(base, env, TARGETS)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
process = subprocess.run(argv, cwd=ROOT, env=env, capture_output=True,
|
||||
text=True, timeout=180, check=False)
|
||||
(output / (name + ".stdout.log")).write_text(process.stdout)
|
||||
(output / (name + ".stderr.log")).write_text(process.stderr)
|
||||
exit_code = process.returncode
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
def decoded(value):
|
||||
return value.decode(errors="replace") if isinstance(value, bytes) else (value or "")
|
||||
(output / (name + ".stdout.log")).write_text(decoded(exc.stdout))
|
||||
(output / (name + ".stderr.log")).write_text(decoded(exc.stderr))
|
||||
exit_code = -1
|
||||
after = stack.snapshot(base, env, TARGETS)
|
||||
proof = {"exit_code": exit_code, "seconds": round(time.monotonic() - started, 3),
|
||||
"before": before, "after": after}
|
||||
try:
|
||||
stack.record_lifecycle(output / "lifecycle.jsonl", "restart", env["COMPOSE_PROJECT_NAME"],
|
||||
before, after, source=name)
|
||||
proof["docker_transition"] = "PASS"
|
||||
except stack.CheckFailure as exc:
|
||||
proof["docker_transition"] = "FAIL"
|
||||
proof["transition_error"] = str(exc)
|
||||
proof["status"] = "PASS" if exit_code == 0 and proof["docker_transition"] == "PASS" else "FAIL"
|
||||
summary[name] = proof
|
||||
print(proof["status"] + " " + name + " (HTTP exit " + str(exit_code) + ")", flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--project", required=True, help="explicit Compose project, e.g. highload-lab3")
|
||||
parser.add_argument("--compose-file", action="append", help="Compose file(s); defaults to HighLoad/compose.yaml")
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8080", help="public LB URL")
|
||||
parser.add_argument("--output", required=True)
|
||||
args = parser.parse_args()
|
||||
output = Path(args.output).resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
env = os.environ.copy()
|
||||
env["COMPOSE_PROJECT_NAME"] = args.project
|
||||
env["COMPOSE_FILE"] = os.pathsep.join(args.compose_file or [str(ROOT / "compose.yaml")])
|
||||
env["BASE_URL"] = args.base_url
|
||||
base = stack.compose_base(env)
|
||||
config = output / "lab3-restart-config.json"
|
||||
config.write_text(json.dumps({"base_url": args.base_url,
|
||||
"hooks": {"restart": [str(ROOT / "scripts/restart.sh")]}}))
|
||||
summary = {"project": args.project, "base_url": args.base_url,
|
||||
"scope": "public LB and Docker Compose service containers",
|
||||
"results": {}}
|
||||
try:
|
||||
run_case("public-persistence",
|
||||
["make", "test-persistence", "ACTION_SCRIPT=scripts/restart.sh",
|
||||
"BASE_URL=" + args.base_url], base, env, output, summary["results"])
|
||||
run_case("lab3-idempotency-restart",
|
||||
[sys.executable, "student-tests/lab3/run.py", "--config", str(config),
|
||||
"--output", str(output / "lab3-run"), "--scenario", "restart"],
|
||||
base, env, output, summary["results"])
|
||||
except (OSError, stack.CheckFailure, subprocess.SubprocessError) as exc:
|
||||
summary["error"] = type(exc).__name__ + ": " + str(exc)
|
||||
summary["status"] = "PASS" if len(summary["results"]) == 2 and all(
|
||||
item["status"] == "PASS" for item in summary["results"].values()) else "FAIL"
|
||||
path = output / "summary.json"
|
||||
path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
|
||||
print(summary["status"] + ": " + str(path), flush=True)
|
||||
return 0 if summary["status"] == "PASS" else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,951 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 3 black-box checks. All traffic uses the configured public LB URL."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timezone
|
||||
import http.client
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote, urlsplit
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
|
||||
class Pending(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Evidence:
|
||||
def __init__(self, directory):
|
||||
self.directory = Path(directory).resolve()
|
||||
self.directory.mkdir(parents=True, exist_ok=True)
|
||||
self.path = self.directory / "events.jsonl"
|
||||
self.summary = {}
|
||||
|
||||
def record(self, event, **fields):
|
||||
now = datetime.now(timezone.utc)
|
||||
item = {"time_utc": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"time_utc_ms": now.isoformat(timespec="milliseconds"),
|
||||
"event": event, **fields}
|
||||
with self.path.open("a", encoding="utf-8") as stream:
|
||||
stream.write(json.dumps(item, ensure_ascii=False, sort_keys=True) + "\n")
|
||||
|
||||
def case(self, name, fn):
|
||||
start = time.monotonic()
|
||||
try:
|
||||
fn()
|
||||
status, detail = "PASS", ""
|
||||
except Pending as exc:
|
||||
status, detail = "PENDING_INFRA", str(exc)
|
||||
except (Failure, AssertionError, ValueError, OSError, subprocess.SubprocessError) as exc:
|
||||
status, detail = "FAIL", str(exc)
|
||||
except Exception as exc:
|
||||
status, detail = "FAIL", "unexpected " + type(exc).__name__
|
||||
self.summary[name] = {"status": status, "detail": detail,
|
||||
"elapsed_seconds": round(time.monotonic() - start, 3)}
|
||||
self.record("case", name=name, **self.summary[name])
|
||||
print(status + " " + name + (": " + detail if detail else ""), flush=True)
|
||||
|
||||
def finish(self):
|
||||
path = self.directory / "summary.json"
|
||||
path.write_text(json.dumps(self.summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
||||
encoding="utf-8")
|
||||
print("Evidence:", path)
|
||||
return 0 if self.summary and all(x["status"] == "PASS" for x in self.summary.values()) else 1
|
||||
|
||||
|
||||
def message_path(chat):
|
||||
return "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
|
||||
def history(client, actor, chat):
|
||||
path = message_path(chat) + "?limit=100"
|
||||
result, cursors = [], set()
|
||||
for _ in range(1000):
|
||||
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
result.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return result
|
||||
check(cursor not in cursors, "history cursor cycle")
|
||||
cursors.add(cursor)
|
||||
path = message_path(chat) + "?limit=100&cursor=" + quote(cursor, safe="")
|
||||
raise Failure("history exceeded pagination safety bound")
|
||||
|
||||
|
||||
def occurrences(client, actor, chat, text):
|
||||
return [m for m in history(client, actor, chat) if m["text"] == text]
|
||||
|
||||
|
||||
def post(client, actor, chat, body, key, expected=201):
|
||||
headers = {} if key is None else {"Idempotency-Key": key}
|
||||
response = client.call("POST", message_path(chat), expected, actor=actor,
|
||||
body=body, headers=headers, schema="Message" if expected == 201 else None)
|
||||
if expected in (400, 401, 404, 409):
|
||||
code = {400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict"}[expected]
|
||||
check(response["json"]["error"]["code"] == code, "wrong error code for %d" % expected)
|
||||
return response
|
||||
|
||||
|
||||
def hook(config, name, evidence, target=None, timeout=45):
|
||||
argv = config.get("hooks", {}).get(name)
|
||||
if not isinstance(argv, list) or not argv or not all(isinstance(x, str) and x for x in argv):
|
||||
raise Pending("configure hooks.%s as an executable argv array" % name)
|
||||
env = dict(os.environ)
|
||||
if target:
|
||||
env["TARGET_INSTANCE_ID"] = target
|
||||
env.update(config.get("hook_context", {}))
|
||||
start = time.monotonic()
|
||||
try:
|
||||
result = subprocess.run(argv, cwd=ROOT, env=env, capture_output=True,
|
||||
timeout=timeout, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise Failure("hook %s unavailable or timed out (%s)" % (name, type(exc).__name__)) from None
|
||||
elapsed = round(time.monotonic() - start, 3)
|
||||
evidence.record("hook", name=name, target_instance=target, elapsed_seconds=elapsed,
|
||||
exit_code=result.returncode)
|
||||
check(result.returncode == 0, "hook %s exited %d; inspect it locally" % (name, result.returncode))
|
||||
if name in ("revoke_access", "restore_access"):
|
||||
try:
|
||||
detail = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
raise Failure("access hook must return validated fixture JSON") from None
|
||||
check(detail.get("action") == name and detail.get("validated_exact_message") is True,
|
||||
"access hook did not confirm exact fixture mutation")
|
||||
evidence.record("access_sql", **detail)
|
||||
return elapsed
|
||||
|
||||
|
||||
def probe(config, evidence, name, target):
|
||||
argv = config.get("hooks", {}).get(name)
|
||||
if not isinstance(argv, list) or not argv:
|
||||
raise Pending("configure hooks.%s to probe the selected private replica" % name)
|
||||
env = dict(os.environ)
|
||||
env["TARGET_INSTANCE_ID"] = target
|
||||
proc = subprocess.run(argv, cwd=ROOT, env=env, capture_output=True, timeout=10, check=False)
|
||||
check(proc.returncode == 0, "probe hook failed")
|
||||
try:
|
||||
value = json.loads(proc.stdout)
|
||||
except ValueError:
|
||||
raise Failure("probe hook must return JSON") from None
|
||||
check(isinstance(value, dict), "probe hook must return a JSON object")
|
||||
evidence.record("replica_probe", name=name, target_instance=target,
|
||||
live_status=value.get("live_status"), ready_status=value.get("ready_status"),
|
||||
accepting=value.get("accepting"))
|
||||
return value
|
||||
|
||||
|
||||
def client_for(config, timeout=None):
|
||||
url = config.get("base_url")
|
||||
if not isinstance(url, str) or not url.startswith(("http://", "https://")):
|
||||
raise Pending("configure base_url to the PUBLIC LB address")
|
||||
return Client(url, config.get("ca_file"), timeout=timeout or config.get("request_timeout_seconds", 3))
|
||||
|
||||
|
||||
def docker_output(argv, timeout=15):
|
||||
try:
|
||||
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=timeout, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise Pending("Docker inspection unavailable (%s)" % type(exc).__name__) from None
|
||||
if proc.returncode:
|
||||
raise Pending("Docker inspection failed; check daemon/project selection")
|
||||
return proc.stdout.decode("utf-8")
|
||||
|
||||
|
||||
def compose_ids(config, service, all_containers=False):
|
||||
base = config.get("compose_base_argv", ["docker", "compose"])
|
||||
flag = "-aq" if all_containers else "-q"
|
||||
return docker_output(base + ["ps", flag, service]).split()
|
||||
|
||||
|
||||
def inspect_container(identifier):
|
||||
value = json.loads(docker_output(["docker", "inspect", identifier]))
|
||||
check(isinstance(value, list) and len(value) == 1, "Docker inspect returned no unique container")
|
||||
return value[0]
|
||||
|
||||
|
||||
def api_by_alias(config):
|
||||
result = {}
|
||||
for identifier in compose_ids(config, "api", all_containers=True):
|
||||
raw = inspect_container(identifier)
|
||||
alias = raw["Config"]["Hostname"]
|
||||
check(alias not in result, "duplicate API hostname/instance alias")
|
||||
result[alias] = raw
|
||||
return result
|
||||
|
||||
|
||||
def volume_names(raw):
|
||||
return sorted(m["Name"] for m in raw.get("Mounts", []) if m.get("Type") == "volume")
|
||||
|
||||
|
||||
def public_ready(config):
|
||||
client = client_for(config)
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
except Failure as exc:
|
||||
if "connection/TLS failure" in str(exc):
|
||||
raise Pending("PUBLIC LB address is not reachable") from None
|
||||
raise
|
||||
return client
|
||||
|
||||
|
||||
def bootstrap(config):
|
||||
client = public_ready(config)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
other_chat = client.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "Lab3 independent scope", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat")["json"]
|
||||
return client, alice, bob, eve, chat, other_chat
|
||||
|
||||
|
||||
def idempotency(config, evidence, only=None):
|
||||
client, alice, bob, eve, chat, other_chat = bootstrap(config)
|
||||
prefix = "lab3-" + uuid.uuid4().hex
|
||||
executed = []
|
||||
def unique(label):
|
||||
return prefix + ":" + label
|
||||
def case(name, fn):
|
||||
if only is None or name == only:
|
||||
evidence.case(name, fn)
|
||||
executed.append(name)
|
||||
|
||||
def invalid_keys():
|
||||
for key in [None, "", " ", "bad/key", "é", "a" * 129, "a\tb"]:
|
||||
post(client, alice, chat, {"text": unique("invalid")}, key, 400)
|
||||
check(not occurrences(client, alice, chat, unique("invalid")), "invalid key created a message")
|
||||
for key in ["a", "A._:-09", "x" * 128]:
|
||||
text = unique("valid-" + str(len(key))) + key[:2]
|
||||
first = post(client, alice, chat, {"text": text}, key)
|
||||
check(first["json"]["text"] == text, "valid boundary key rejected")
|
||||
case("idempotency_key_boundaries", invalid_keys)
|
||||
|
||||
def replay_conflict():
|
||||
key, text = unique("key"), unique("original")
|
||||
first = post(client, alice, chat, {"text": text}, key)
|
||||
second = post(client, alice, chat, {"text": text}, key)
|
||||
check(first["status"] == second["status"] == 201 and first["json"] == second["json"],
|
||||
"replay did not return original 201 and Message")
|
||||
raw = b'{ "text" : ' + json.dumps(text, ensure_ascii=False).encode("utf-8") + b' }'
|
||||
equivalent = client.call("POST", message_path(chat), 201, actor=alice, raw=raw,
|
||||
headers={"Idempotency-Key": key, "Content-Type": "application/json"},
|
||||
schema="Message")
|
||||
check(equivalent["json"] == first["json"], "equivalent JSON replay changed Message")
|
||||
post(client, alice, chat, {"text": unique("changed")}, key, 409)
|
||||
check(len(occurrences(client, alice, chat, text)) == 1, "replay created duplicate")
|
||||
check(not occurrences(client, alice, chat, unique("changed")), "conflict wrote new message")
|
||||
case("idempotency_replay_and_conflict", replay_conflict)
|
||||
|
||||
def replay_across_replica():
|
||||
aliases = observe_instances(client, alice)
|
||||
key, text = unique("replica-key"), unique("replica")
|
||||
first = post(client, alice, chat, {"text": text}, key)
|
||||
first_alias = first["headers"].get("X-Instance-Id")
|
||||
check(first_alias in aliases, "initial response came from unknown instance")
|
||||
for _ in range(100):
|
||||
repeated = post(client, alice, chat, {"text": text}, key)
|
||||
check(repeated["json"] == first["json"], "cross-replica replay changed Message")
|
||||
if repeated["headers"].get("X-Instance-Id") != first_alias:
|
||||
check(len(occurrences(client, alice, chat, text)) == 1,
|
||||
"cross-replica replay created duplicate")
|
||||
return
|
||||
raise Failure("LB never routed replay to another instance")
|
||||
case("idempotency_replay_across_replica", replay_across_replica)
|
||||
|
||||
def independent_scope():
|
||||
key, text = unique("scope-key"), unique("scope")
|
||||
a = post(client, alice, chat, {"text": text + " A"}, key)["json"]
|
||||
b = post(client, bob, chat, {"text": text + " B"}, key)["json"]
|
||||
c = post(client, alice, other_chat, {"text": text + " C"}, key)["json"]
|
||||
check(len({a["id"], b["id"], c["id"]}) == 3, "key scope collided across user/chat")
|
||||
for actor, target, body, original in [(alice, chat, text + " A", a),
|
||||
(bob, chat, text + " B", b),
|
||||
(alice, other_chat, text + " C", c)]:
|
||||
check(post(client, actor, target, {"text": body}, key)["json"] == original,
|
||||
"scoped replay changed original")
|
||||
case("idempotency_user_chat_scope", independent_scope)
|
||||
|
||||
def concurrent():
|
||||
key, text = unique("concurrent-key"), unique("concurrent")
|
||||
workers = int(config.get("concurrency", 12))
|
||||
check(2 <= workers <= 64, "concurrency must be 2..64")
|
||||
gate = threading.Barrier(workers)
|
||||
def one(_):
|
||||
gate.wait(timeout=10)
|
||||
return post(client_for(config), alice, chat, {"text": text}, key)
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(one, range(workers)))
|
||||
check(all(r["status"] == 201 and r["json"] == responses[0]["json"] for r in responses),
|
||||
"concurrent replay returned different status/Message")
|
||||
check(len(occurrences(client, alice, chat, text)) == 1, "concurrent requests made duplicate")
|
||||
ids = {r["headers"].get("X-Instance-Id") for r in responses}
|
||||
evidence.record("concurrent_idempotency", attempts=workers, observed_instances=sorted(ids))
|
||||
check(len(ids) >= 2, "concurrent requests did not traverse two LB backends")
|
||||
case("idempotency_concurrent_cross_replica", concurrent)
|
||||
|
||||
def auth_rechecked():
|
||||
key, text = unique("auth-key"), unique("auth")
|
||||
post(client, alice, chat, {"text": text}, key)
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
post(client, alice, chat, {"text": text}, key, 401)
|
||||
post(client, eve, chat, {"text": text}, key, 404)
|
||||
check(len(occurrences(client, bob, chat, text)) == 1, "auth retry modified message")
|
||||
case("idempotency_session_and_foreign_access", auth_rechecked)
|
||||
|
||||
# The fixture owns one message in this chat. The isolated adapter temporarily
|
||||
# assigns it to the other member so the FK permits removing the original sender.
|
||||
def access_rechecked():
|
||||
if not all(config.get("hooks", {}).get(name) for name in ("revoke_access", "restore_access")):
|
||||
raise Pending("configure isolated hooks.revoke_access/restore_access for synthetic fixture")
|
||||
client2, owner, member, outsider, target, _ = bootstrap(config)
|
||||
key, text = unique("acl-key"), unique("acl")
|
||||
first = post(client2, owner, target, {"text": text}, key)["json"]
|
||||
evidence.record("access_hook_target", chat_id=target["id"], user_id=owner["id"],
|
||||
replacement_user_id=member["id"], message_id=first["id"])
|
||||
env = config.setdefault("hook_context", {})
|
||||
env.update({"TEST_CHAT_ID": target["id"], "TEST_USER_ID": owner["id"],
|
||||
"TEST_REPLACEMENT_USER_ID": member["id"], "TEST_MESSAGE_ID": first["id"],
|
||||
"TEST_IDEMPOTENCY_KEY": key})
|
||||
try:
|
||||
hook(config, "revoke_access", evidence)
|
||||
post(client2, owner, target, {"text": text}, key, 404)
|
||||
finally:
|
||||
hook(config, "restore_access", evidence)
|
||||
check(post(client2, owner, target, {"text": text}, key)["json"] == first,
|
||||
"replay after access restoration returned a different Message")
|
||||
check(len(occurrences(client2, member, target, text)) == 1,
|
||||
"access restoration left duplicate message")
|
||||
case("idempotency_access_rechecked_after_membership_change", access_rechecked)
|
||||
|
||||
def replay_after_restart():
|
||||
client3, owner, member, outsider, target, _ = bootstrap(config)
|
||||
key, text = unique("restart-key"), unique("restart")
|
||||
first = post(client3, owner, target, {"text": text}, key)["json"]
|
||||
hook(config, "restart", evidence, timeout=90)
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
client3.call("GET", "/health/ready", schema="Health")
|
||||
break
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "LB did not recover after restart")
|
||||
time.sleep(.2)
|
||||
check(post(client3, owner, target, {"text": text}, key)["json"] == first,
|
||||
"idempotency result changed after restart")
|
||||
check(len(occurrences(client3, member, target, text)) == 1,
|
||||
"restart retry created duplicate")
|
||||
case("idempotency_survives_restart", replay_after_restart)
|
||||
|
||||
def uncertain_replay():
|
||||
client4, owner, member, outsider, target, _ = bootstrap(config)
|
||||
key, text = unique("uncertain-key"), unique("uncertain")
|
||||
url = urlsplit(client4.base)
|
||||
check(url.scheme in ("http", "https") and url.hostname, "invalid LB URL")
|
||||
path = message_path(target)
|
||||
body = json.dumps({"text": text}, ensure_ascii=False).encode("utf-8")
|
||||
request = ("POST " + path + " HTTP/1.1\r\nHost: " + url.netloc +
|
||||
"\r\nConnection: close\r\nAuthorization: Bearer " + owner["token"] +
|
||||
"\r\nIdempotency-Key: " + key +
|
||||
"\r\nContent-Type: application/json\r\nContent-Length: " + str(len(body)) +
|
||||
"\r\n\r\n").encode("ascii") + body
|
||||
sock = socket.create_connection((url.hostname, url.port or (443 if url.scheme == "https" else 80)), 3)
|
||||
try:
|
||||
if url.scheme == "https":
|
||||
context = ssl.create_default_context(cafile=config.get("ca_file"))
|
||||
sock = context.wrap_socket(sock, server_hostname=url.hostname)
|
||||
sock.sendall(request)
|
||||
# Deliberately discard the response. The first request may or may not commit.
|
||||
finally:
|
||||
sock.close()
|
||||
result = post(client4, owner, target, {"text": text}, key)["json"]
|
||||
check(len(occurrences(client4, member, target, text)) == 1, "uncertain retry duplicated message")
|
||||
check(result["text"] == text, "uncertain retry returned wrong message")
|
||||
case("idempotency_after_disconnected_client", uncertain_replay)
|
||||
|
||||
def timed_out_replay():
|
||||
client5, owner, member, outsider, target, _ = bootstrap(config)
|
||||
key, text = unique("timeout-key"), unique("timeout")
|
||||
upstream = urlsplit(client5.base)
|
||||
forwarded = threading.Event()
|
||||
release = threading.Event()
|
||||
upstream_result = {}
|
||||
|
||||
class DelayedResponse(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def do_POST(self):
|
||||
connection = None
|
||||
try:
|
||||
length = int(self.headers["Content-Length"])
|
||||
body = self.rfile.read(length)
|
||||
connection_type = (http.client.HTTPSConnection if upstream.scheme == "https"
|
||||
else http.client.HTTPConnection)
|
||||
options = {"timeout": 5}
|
||||
if upstream.scheme == "https":
|
||||
options["context"] = ssl.create_default_context(cafile=config.get("ca_file"))
|
||||
connection = connection_type(upstream.hostname, upstream.port or
|
||||
(443 if upstream.scheme == "https" else 80), **options)
|
||||
headers = {k: v for k, v in self.headers.items()
|
||||
if k.lower() not in ("host", "connection", "content-length")}
|
||||
headers["Content-Length"] = str(len(body))
|
||||
connection.request("POST", self.path, body=body, headers=headers)
|
||||
response = connection.getresponse()
|
||||
payload = response.read()
|
||||
upstream_result["status"] = response.status
|
||||
upstream_result["body"] = payload
|
||||
except Exception as exc:
|
||||
upstream_result["error"] = type(exc).__name__
|
||||
finally:
|
||||
forwarded.set()
|
||||
release.wait(5)
|
||||
if connection:
|
||||
connection.close()
|
||||
try:
|
||||
self.send_response(upstream_result.get("status", 502))
|
||||
self.end_headers()
|
||||
self.wfile.write(upstream_result.get("body", b""))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
proxy = ThreadingHTTPServer(("127.0.0.1", 0), DelayedResponse)
|
||||
proxy.daemon_threads = True
|
||||
server_thread = threading.Thread(target=proxy.serve_forever, daemon=True)
|
||||
server_thread.start()
|
||||
try:
|
||||
short = Client("http://127.0.0.1:%d" % proxy.server_port, timeout=0.01)
|
||||
try:
|
||||
post(short, owner, target, {"text": text}, key)
|
||||
except Failure as exc:
|
||||
check("connection/TLS failure" in str(exc), "delayed request failed for a reason other than timeout")
|
||||
else:
|
||||
raise Failure("delayed response did not produce a client timeout")
|
||||
check(forwarded.wait(5), "test proxy did not forward the timed-out POST")
|
||||
check(upstream_result.get("status") == 201,
|
||||
"timed-out POST did not commit through public LB: " +
|
||||
str(upstream_result.get("error", upstream_result.get("status"))))
|
||||
finally:
|
||||
release.set()
|
||||
proxy.shutdown()
|
||||
proxy.server_close()
|
||||
server_thread.join(timeout=5)
|
||||
committed = occurrences(client5, member, target, text)
|
||||
check(len(committed) == 1, "timed-out first request was not committed before retry")
|
||||
result = post(client5, owner, target, {"text": text}, key)["json"]
|
||||
check(result == committed[0] and len(occurrences(client5, member, target, text)) == 1,
|
||||
"retry after timeout did not resolve to exactly one message")
|
||||
case("idempotency_after_client_timeout", timed_out_replay)
|
||||
failed = [name for name in executed if evidence.summary[name]["status"] == "FAIL"]
|
||||
pending = [name for name in executed if evidence.summary[name]["status"] == "PENDING_INFRA"]
|
||||
check(not failed, "idempotency cases failed: " + ", ".join(failed))
|
||||
if pending:
|
||||
raise Pending("idempotency cases awaiting infrastructure: " + ", ".join(pending))
|
||||
|
||||
|
||||
def observe_instances(client, actor, count=60):
|
||||
ids = set()
|
||||
for _ in range(count):
|
||||
response = client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
ids.add(response["headers"].get("X-Instance-Id"))
|
||||
check(len(ids) >= 2, "public LB exposed fewer than two X-Instance-Id values")
|
||||
return sorted(ids)
|
||||
|
||||
|
||||
def wait_instances(client, actor, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
try:
|
||||
return observe_instances(client, actor, count=24)
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.25)
|
||||
|
||||
|
||||
def load_window(config, evidence, client, actor, chat, seconds, label, expected_instance=None):
|
||||
start, successes, failures, reads, latencies, observed = time.monotonic(), 0, 0, 0, [], set()
|
||||
started_at_utc = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
||||
error_events = []
|
||||
first_good, first_read = None, None
|
||||
pending_key = uuid.uuid4().hex
|
||||
pending_text = "lab3-" + uuid.uuid4().hex
|
||||
attempted_texts, confirmed_texts = set(), set()
|
||||
while time.monotonic() - start < seconds:
|
||||
attempted_texts.add(pending_text)
|
||||
request_started_at_utc = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
||||
try:
|
||||
response = post(client, actor, chat, {"text": pending_text}, pending_key)
|
||||
successes += 1
|
||||
confirmed_texts.add(pending_text)
|
||||
latencies.append(response["elapsed"])
|
||||
observed.add(response["headers"].get("X-Instance-Id"))
|
||||
if first_good is None:
|
||||
first_good = time.monotonic() - start
|
||||
pending_key, pending_text = uuid.uuid4().hex, "lab3-" + uuid.uuid4().hex
|
||||
except Failure as exc:
|
||||
failures += 1
|
||||
error_events.append({"seconds": round(time.monotonic() - start, 3),
|
||||
"operation": "POST", "detail": str(exc)[:160],
|
||||
"request_started_at_utc": request_started_at_utc,
|
||||
"failed_at_utc": datetime.now(timezone.utc).isoformat(timespec="milliseconds")})
|
||||
request_started_at_utc = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
||||
try:
|
||||
response = client.call("GET", message_path(chat) + "?limit=1", actor=actor, schema="MessagePage")
|
||||
reads += 1
|
||||
if first_read is None:
|
||||
first_read = time.monotonic() - start
|
||||
observed.add(response["headers"].get("X-Instance-Id"))
|
||||
except Failure as exc:
|
||||
failures += 1
|
||||
error_events.append({"seconds": round(time.monotonic() - start, 3),
|
||||
"operation": "GET", "detail": str(exc)[:160],
|
||||
"request_started_at_utc": request_started_at_utc,
|
||||
"failed_at_utc": datetime.now(timezone.utc).isoformat(timespec="milliseconds")})
|
||||
elapsed = time.monotonic() - start
|
||||
summary = {"label": label, "duration_seconds": round(elapsed, 3),
|
||||
"started_at_utc": started_at_utc,
|
||||
"ended_at_utc": datetime.now(timezone.utc).isoformat(timespec="milliseconds"),
|
||||
"successful_write_rps": round(successes / elapsed, 3),
|
||||
"successful_writes": successes, "successful_reads": reads,
|
||||
"errors": failures, "first_success_seconds": first_good,
|
||||
"first_read_seconds": first_read,
|
||||
"observed_instances": sorted(observed), "latency_seconds": latencies,
|
||||
"error_events": error_events}
|
||||
evidence.record("load_window", **summary)
|
||||
check(successes > 0 and reads > 0, label + ": no successful reads/writes")
|
||||
if expected_instance:
|
||||
check(expected_instance not in observed, label + ": stopped/unready backend still served traffic")
|
||||
summary["_attempted_texts"] = attempted_texts
|
||||
summary["_confirmed_texts"] = confirmed_texts
|
||||
return summary
|
||||
|
||||
|
||||
def failover(config, evidence):
|
||||
client, alice, bob, eve, chat, _ = bootstrap(config)
|
||||
aliases = observe_instances(client, alice)
|
||||
evidence.record("lb_instances", aliases=aliases)
|
||||
for target in aliases:
|
||||
def one():
|
||||
before_docker = api_by_alias(config)
|
||||
check(target in before_docker and len(before_docker) >= 2 and
|
||||
all(item["State"]["Running"] for item in before_docker.values()),
|
||||
"target alias does not map to one of two running API containers")
|
||||
old = before_docker[target]
|
||||
stable_key = uuid.uuid4().hex
|
||||
stable_text = "lab3-before-" + uuid.uuid4().hex
|
||||
before = post(client, alice, chat, {"text": stable_text}, stable_key)["json"]
|
||||
stop_start = time.monotonic()
|
||||
hook(config, "stop_one", evidence, target=target, timeout=10)
|
||||
hook_elapsed = time.monotonic() - stop_start
|
||||
stopped = api_by_alias(config)
|
||||
check(target in stopped and stopped[target]["Id"] == old["Id"] and
|
||||
not stopped[target]["State"]["Running"] and
|
||||
any(item["State"]["Running"] for alias, item in stopped.items() if alias != target),
|
||||
"stop hook did not stop exactly the selected API container")
|
||||
try:
|
||||
result = load_window(config, evidence, client_for(config, timeout=1), alice,
|
||||
chat, float(config.get("failover_window_seconds", 15)),
|
||||
"stop_" + target, expected_instance=target)
|
||||
write_recovery = hook_elapsed + result["first_success_seconds"]
|
||||
read_recovery = hook_elapsed + result["first_read_seconds"]
|
||||
evidence.record("failover_recovery", target_instance=target,
|
||||
write_seconds=round(write_recovery, 3), read_seconds=round(read_recovery, 3))
|
||||
check(write_recovery <= 10 and read_recovery <= 10,
|
||||
"read/write did not recover within 10 seconds from stop start")
|
||||
check(before in history(client, bob, chat), "confirmed message lost after stop")
|
||||
check(post(client, alice, chat, {"text": stable_text}, stable_key)["json"] == before,
|
||||
"replay after replica stop returned different Message")
|
||||
actual_texts = [m["text"] for m in history(client, bob, chat)
|
||||
if m["text"] in result["_attempted_texts"]]
|
||||
check(len(actual_texts) == len(set(actual_texts)),
|
||||
"uncertain failover retry created duplicate")
|
||||
check(result["_confirmed_texts"].issubset(set(actual_texts)),
|
||||
"confirmed write disappeared during failover")
|
||||
finally:
|
||||
hook(config, "start_one", evidence, target=target, timeout=60)
|
||||
restarted = api_by_alias(config)
|
||||
check(target in restarted and restarted[target]["Id"] == old["Id"] and
|
||||
restarted[target]["State"]["Running"] and
|
||||
restarted[target]["State"]["StartedAt"] != old["State"]["StartedAt"] and
|
||||
volume_names(restarted[target]) == volume_names(old),
|
||||
"selected API container did not restart with same ID/volumes")
|
||||
evidence.record("failover_docker", target_instance=target,
|
||||
container_id=old["Id"],
|
||||
started_at_before=old["State"]["StartedAt"],
|
||||
started_at_after=restarted[target]["State"]["StartedAt"],
|
||||
volumes=volume_names(old))
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
observed = observe_instances(client, alice)
|
||||
if len(observed) >= 2:
|
||||
break
|
||||
except Failure:
|
||||
pass
|
||||
check(time.monotonic() < deadline, "second replica did not return through LB")
|
||||
time.sleep(.25)
|
||||
evidence.case("failover_" + target, one)
|
||||
failed = [alias for alias in aliases if evidence.summary["failover_" + alias]["status"] != "PASS"]
|
||||
check(not failed, "replica failover failed: " + ", ".join(failed))
|
||||
|
||||
|
||||
def grade4(config, evidence, only=None):
|
||||
def case(name, fn):
|
||||
if only is None or name in ("rolling_update_under_load", "rolling_update_zero_http_errors_quality"):
|
||||
evidence.case(name, fn)
|
||||
def health():
|
||||
client = public_ready(config)
|
||||
client.call("GET", "/health/live", schema="Health")
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
evidence.record("health", live=200, ready=200)
|
||||
case("health_live_ready", health)
|
||||
|
||||
def topology():
|
||||
argv = config.get("compose_config_argv", ["docker", "compose", "config", "--format", "json"])
|
||||
try:
|
||||
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=15, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
raise Pending("Docker Compose config unavailable") from None
|
||||
if proc.returncode:
|
||||
raise Pending("Docker Compose config unavailable; provide .env/secrets and compose_config_argv")
|
||||
try:
|
||||
services = json.loads(proc.stdout)["services"]
|
||||
except (ValueError, KeyError):
|
||||
raise Failure("Compose config did not return services JSON") from None
|
||||
apis = config.get("api_services") or [name for name in services if name == "api" or name.startswith("api-")]
|
||||
lbs = config.get("lb_services") or [name for name in services if name in ("lb", "proxy", "nginx", "haproxy", "traefik")]
|
||||
issues = []
|
||||
if not lbs or not all(name in services for name in lbs):
|
||||
issues.append("no configured LB service")
|
||||
if not apis or not all(name in services for name in apis):
|
||||
issues.append("no configured API service")
|
||||
runtime = {}
|
||||
project = None
|
||||
for name, service in services.items():
|
||||
deploy = service.get("deploy", {})
|
||||
limits = deploy.get("resources", {}).get("limits", {})
|
||||
if not ((limits.get("cpus") or service.get("cpus")) and
|
||||
(limits.get("memory") or service.get("mem_limit"))):
|
||||
issues.append(name + " lacks CPU/RAM limits")
|
||||
ids = compose_ids(config, name, all_containers=True)
|
||||
if not ids:
|
||||
issues.append(name + " has no Docker container")
|
||||
runtime[name] = []
|
||||
for identifier in ids:
|
||||
raw = inspect_container(identifier)
|
||||
labels = raw.get("Config", {}).get("Labels", {})
|
||||
observed_project = labels.get("com.docker.compose.project")
|
||||
if project is None:
|
||||
project = observed_project
|
||||
if not observed_project or observed_project != project or labels.get("com.docker.compose.service") != name:
|
||||
issues.append(name + " container has wrong Compose ownership")
|
||||
host = raw.get("HostConfig", {})
|
||||
cpu = host.get("NanoCpus", 0)
|
||||
memory = host.get("Memory", 0)
|
||||
if not (isinstance(cpu, int) and cpu > 0 and isinstance(memory, int) and memory > 0):
|
||||
issues.append(name + " lacks enforced Docker CPU/RAM limits")
|
||||
runtime[name].append({"id": raw["Id"], "running": raw["State"]["Running"],
|
||||
"exit_code": raw["State"].get("ExitCode"),
|
||||
"nano_cpus": cpu, "memory_bytes": memory,
|
||||
"healthcheck": bool(raw.get("Config", {}).get("Healthcheck")),
|
||||
"port_bindings": host.get("PortBindings") or {}})
|
||||
for name in apis:
|
||||
if name not in services:
|
||||
continue
|
||||
service = services[name]
|
||||
if service.get("ports"):
|
||||
issues.append(name + " publishes an API port around the LB")
|
||||
if service.get("container_name"):
|
||||
issues.append(name + " has a scaling-blocking container_name")
|
||||
if not service.get("healthcheck") and not all(x["healthcheck"] for x in runtime[name]):
|
||||
issues.append(name + " has no healthcheck")
|
||||
if not service.get("stop_grace_period"):
|
||||
issues.append(name + " has no stop_grace_period")
|
||||
replicas = sum(int(services[name].get("deploy", {}).get("replicas",
|
||||
services[name].get("scale", 1))) for name in apis if name in services)
|
||||
if replicas < 2:
|
||||
issues.append("fewer than two API replicas declared")
|
||||
if sum(x["running"] for name in apis for x in runtime.get(name, [])) < 2:
|
||||
issues.append("fewer than two running API containers")
|
||||
for name in apis:
|
||||
if any(x["port_bindings"] for x in runtime.get(name, [])):
|
||||
issues.append(name + " has a direct Docker host port binding")
|
||||
migrate = services.get("migrate")
|
||||
if not migrate:
|
||||
issues.append("migration service missing")
|
||||
evidence.record("compose_topology", api_services=apis, declared_replicas=replicas,
|
||||
lb_services=lbs, migration_service="migrate" if migrate else None,
|
||||
project=project, runtime=runtime, issues=issues)
|
||||
check(not issues, "; ".join(issues))
|
||||
case("compose_lb_limits_ports_migration_layout", topology)
|
||||
|
||||
def readiness_exclusion():
|
||||
client, alice, bob, eve, chat, _ = bootstrap(config)
|
||||
aliases = observe_instances(client, alice)
|
||||
target = aliases[0]
|
||||
unready_start = time.monotonic()
|
||||
hook(config, "make_unready", evidence, target=target)
|
||||
try:
|
||||
direct = probe(config, evidence, "probe_health", target)
|
||||
check(direct.get("live_status") == 200 and direct.get("ready_status") == 503,
|
||||
"unready replica must remain live and return ready=503")
|
||||
deadline = unready_start + 10
|
||||
while True:
|
||||
try:
|
||||
observed = [client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
["headers"]["X-Instance-Id"] for _ in range(12)]
|
||||
if target not in observed:
|
||||
break
|
||||
except Failure:
|
||||
pass
|
||||
check(time.monotonic() < deadline, "LB did not exclude unready replica within 10 seconds")
|
||||
time.sleep(.2)
|
||||
evidence.record("readiness_exclusion", target_instance=target,
|
||||
elapsed_seconds=round(time.monotonic() - unready_start, 3))
|
||||
result = load_window(config, evidence, client, alice, chat, 3, "unready", expected_instance=target)
|
||||
check(result["errors"] == 0, "LB still sent requests to unready backend")
|
||||
finally:
|
||||
hook(config, "restore_ready", evidence, target=target)
|
||||
wait_instances(client, alice, timeout=10)
|
||||
case("lb_excludes_unready_replica", readiness_exclusion)
|
||||
|
||||
def lb_timing():
|
||||
argv = config.get("hooks", {}).get("lb_timing_evidence")
|
||||
if not isinstance(argv, list) or not argv:
|
||||
raise Pending("configure hooks.lb_timing_evidence for LB health interval/timeout")
|
||||
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=10, check=False)
|
||||
check(proc.returncode == 0, "LB timing evidence hook failed")
|
||||
try:
|
||||
value = json.loads(proc.stdout)
|
||||
except ValueError:
|
||||
raise Failure("LB timing evidence hook must return JSON") from None
|
||||
interval = value.get("health_interval_seconds")
|
||||
timeout = value.get("health_timeout_seconds")
|
||||
detection = value.get("configured_max_detection_seconds")
|
||||
check(all(isinstance(x, (int, float)) and not isinstance(x, bool) and x > 0
|
||||
for x in (interval, timeout, detection)), "LB timing values must be positive numbers")
|
||||
check(detection <= 10, "configured LB detection exceeds 10 seconds")
|
||||
evidence.record("lb_timing", health_interval_seconds=interval,
|
||||
health_timeout_seconds=timeout,
|
||||
configured_max_detection_seconds=detection)
|
||||
case("lb_health_timing", lb_timing)
|
||||
|
||||
def sigterm():
|
||||
client, alice, bob, eve, chat, _ = bootstrap(config)
|
||||
target = wait_instances(client, alice)[0]
|
||||
hook(config, "sigterm_one", evidence, target=target, timeout=10)
|
||||
try:
|
||||
direct = probe(config, evidence, "probe_stopped", target)
|
||||
check(direct.get("accepting") is False, "terminated replica still accepts requests")
|
||||
load_window(config, evidence, client, alice, chat, 10, "sigterm", expected_instance=target)
|
||||
finally:
|
||||
hook(config, "start_one", evidence, target=target, timeout=60)
|
||||
case("sigterm_drains_and_stops_accepting", sigterm)
|
||||
|
||||
rolling_result = {}
|
||||
def rolling():
|
||||
client, alice, bob, eve, chat, _ = bootstrap(config)
|
||||
before = wait_instances(client, alice)
|
||||
old_containers = [inspect_container(identifier) for identifier in compose_ids(config, "api")]
|
||||
old_ids = {item["Id"] for item in old_containers}
|
||||
check(len(old_ids) == 2 and all(item["State"]["Running"] for item in old_containers),
|
||||
"rolling update requires two running API containers")
|
||||
argv = config.get("hooks", {}).get("rolling_update")
|
||||
if not isinstance(argv, list) or not argv:
|
||||
raise Pending("configure hooks.rolling_update for sequential replacement under load")
|
||||
telemetry = bool(config.get("rolling_telemetry"))
|
||||
captures = []
|
||||
since = str(int(time.time()))
|
||||
telemetry_dir = evidence.directory / "rolling-telemetry"
|
||||
if telemetry:
|
||||
telemetry_dir.mkdir(exist_ok=True)
|
||||
project = old_containers[0]["Config"]["Labels"]["com.docker.compose.project"]
|
||||
lb_ids = compose_ids(config, "lb")
|
||||
check(len(lb_ids) == 1, "rolling telemetry needs one LB container")
|
||||
def capture(name, command):
|
||||
output = (telemetry_dir / (name + ".log")).open("wb")
|
||||
errors = (telemetry_dir / (name + ".stderr.log")).open("wb")
|
||||
watcher = subprocess.Popen(command, cwd=ROOT, stdout=output, stderr=errors)
|
||||
captures.append((watcher, output, errors))
|
||||
capture("docker-events", ["docker", "events", "--filter", "type=container",
|
||||
"--filter", "label=com.docker.compose.project=" + project,
|
||||
"--format", "{{json .}}"])
|
||||
capture("haproxy", ["docker", "logs", "--follow", "--timestamps", "--since", since, lb_ids[0]])
|
||||
for identifier in sorted(old_ids):
|
||||
capture("api-old-" + identifier[:12],
|
||||
["docker", "logs", "--follow", "--timestamps", "--since", since, identifier])
|
||||
time.sleep(.2)
|
||||
rolling_env = dict(os.environ)
|
||||
if telemetry:
|
||||
rolling_env["HL_ROLLING_TRACE_ACTIVE"] = "1"
|
||||
process = subprocess.Popen(argv, cwd=ROOT, env=rolling_env, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, start_new_session=True)
|
||||
try:
|
||||
result = load_window(config, evidence, client_for(config, timeout=1), alice, chat,
|
||||
float(config.get("rolling_window_seconds", 20)), "rolling")
|
||||
output, errors = process.communicate(timeout=90)
|
||||
if telemetry:
|
||||
(telemetry_dir / "rolling-script.stdout.log").write_bytes(output)
|
||||
(telemetry_dir / "rolling-script.stderr.log").write_bytes(errors)
|
||||
check(process.returncode == 0, "rolling update hook failed")
|
||||
try:
|
||||
lifecycle = json.loads(output)
|
||||
except ValueError:
|
||||
raise Failure("rolling hook must return lifecycle JSON") from None
|
||||
check(lifecycle.get("replaced_processes", 0) >= 2 and
|
||||
lifecycle.get("min_ready_during_update", 0) >= 1,
|
||||
"rolling hook did not prove sequential replacement and a ready backend")
|
||||
after = observe_instances(client, alice)
|
||||
new_containers = [inspect_container(identifier) for identifier in compose_ids(config, "api")]
|
||||
new_ids = {item["Id"] for item in new_containers}
|
||||
check(len(new_ids) == 2 and not old_ids.intersection(new_ids) and
|
||||
all(item["State"]["Running"] for item in new_containers),
|
||||
"rolling update did not replace both real API containers")
|
||||
evidence.record("rolling_update", before=before, after=after,
|
||||
old_container_ids=sorted(old_ids), new_container_ids=sorted(new_ids),
|
||||
replaced_processes=lifecycle["replaced_processes"],
|
||||
min_ready_during_update=lifecycle["min_ready_during_update"],
|
||||
errors=result["errors"], successful_write_rps=result["successful_write_rps"])
|
||||
rolling_result.update(result)
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=5)
|
||||
if telemetry:
|
||||
for watcher, output_stream, error_stream in captures:
|
||||
if watcher.poll() is None:
|
||||
watcher.terminate()
|
||||
watcher.wait(timeout=5)
|
||||
output_stream.close()
|
||||
error_stream.close()
|
||||
try:
|
||||
for identifier in compose_ids(config, "api"):
|
||||
if identifier not in old_ids:
|
||||
proc = subprocess.run(["docker", "logs", "--timestamps", "--since", since,
|
||||
identifier], cwd=ROOT, capture_output=True, timeout=10)
|
||||
(telemetry_dir / ("api-new-" + identifier[:12] + ".log")).write_bytes(
|
||||
proc.stdout + proc.stderr)
|
||||
except (OSError, subprocess.SubprocessError, Pending):
|
||||
evidence.record("rolling_telemetry_incomplete", reason="new API logs unavailable")
|
||||
case("rolling_update_under_load", rolling)
|
||||
def rolling_quality():
|
||||
if not rolling_result:
|
||||
raise Pending("rolling update did not complete; inspect rolling_update_under_load")
|
||||
check(rolling_result["errors"] == 0, "rolling update had %d HTTP errors" % rolling_result["errors"])
|
||||
case("rolling_update_zero_http_errors_quality", rolling_quality)
|
||||
|
||||
def migration_once():
|
||||
# A one-time historical fact requires lifecycle evidence, not just a current
|
||||
# Compose snapshot. An adapter must count actual migration starts for this run.
|
||||
argv = config.get("hooks", {}).get("migration_evidence")
|
||||
if not isinstance(argv, list) or not argv:
|
||||
raise Pending("configure hooks.migration_evidence to count actual migration starts")
|
||||
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=20, check=False)
|
||||
check(proc.returncode == 0, "migration evidence hook failed")
|
||||
try:
|
||||
value = json.loads(proc.stdout)
|
||||
except ValueError:
|
||||
raise Failure("migration evidence hook must return JSON") from None
|
||||
check(value.get("migration_starts") == 1 and value.get("migration_exit_code") == 0,
|
||||
"migrations did not start exactly once and exit successfully")
|
||||
check(value.get("api_started_before_migration_complete") is False,
|
||||
"API started before migration completed")
|
||||
evidence.record("migration_once", migration_starts=1, migration_exit_code=0,
|
||||
api_started_before_migration_complete=False)
|
||||
case("migrations_started_once", migration_once)
|
||||
|
||||
|
||||
def public_checks(config, evidence):
|
||||
def run_make(target, action=None, label=None):
|
||||
public_ready(config)
|
||||
argv = ["make", target, "BASE_URL=" + config["base_url"]]
|
||||
if config.get("ca_file"):
|
||||
argv.append("CA_FILE=" + config["ca_file"])
|
||||
if action:
|
||||
script = config.get("hooks", {}).get(action)
|
||||
if not isinstance(script, list) or len(script) != 1:
|
||||
raise Pending("public %s requires hooks.%s with one executable script path" % (target, action))
|
||||
path = Path(script[0])
|
||||
if not path.is_absolute():
|
||||
path = ROOT / path
|
||||
if not path.is_file() or not os.access(path, os.X_OK):
|
||||
raise Pending("public %s action script is missing or not executable" % target)
|
||||
argv.append("ACTION_SCRIPT=" + str(path))
|
||||
started = time.monotonic()
|
||||
try:
|
||||
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=180, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise Failure("%s failed to launch or timed out (%s)" % (target, type(exc).__name__)) from None
|
||||
stem = label or target
|
||||
(evidence.directory / (stem + ".stdout.log")).write_bytes(proc.stdout)
|
||||
(evidence.directory / (stem + ".stderr.log")).write_bytes(proc.stderr)
|
||||
evidence.record("public_make", target=target, label=stem, exit_code=proc.returncode,
|
||||
elapsed_seconds=round(time.monotonic() - started, 3))
|
||||
check(proc.returncode == 0, target + " failed; inspect its saved stdout/stderr")
|
||||
evidence.case("public_make_test", lambda: run_make("test"))
|
||||
evidence.case("public_make_test_persistence", lambda: run_make("test-persistence", "restart"))
|
||||
def both_failovers():
|
||||
if not config.get("hooks", {}).get("recover_all"):
|
||||
raise Pending("configure hooks.recover_all before public failover")
|
||||
stopped_aliases = set()
|
||||
for attempt in range(1, 5):
|
||||
before = api_by_alias(config)
|
||||
check(len(before) == 2 and all(item["State"]["Running"] for item in before.values()),
|
||||
"public failover requires two running API containers")
|
||||
try:
|
||||
run_make("test-failover", "stop_one", label="test-failover-%d" % attempt)
|
||||
after = api_by_alias(config)
|
||||
stopped = [alias for alias, item in after.items() if not item["State"]["Running"]]
|
||||
check(len(stopped) == 1 and stopped[0] in before and
|
||||
after[stopped[0]]["Id"] == before[stopped[0]]["Id"],
|
||||
"public failover did not leave exactly its selected replica stopped")
|
||||
stopped_aliases.add(stopped[0])
|
||||
evidence.record("public_failover_target", attempt=attempt,
|
||||
target_instance=stopped[0], container_id=after[stopped[0]]["Id"])
|
||||
finally:
|
||||
hook(config, "recover_all", evidence, timeout=60)
|
||||
if len(stopped_aliases) == 2:
|
||||
break
|
||||
check(len(stopped_aliases) == 2,
|
||||
"public make test-failover did not exercise both API replicas in four attempts")
|
||||
evidence.case("public_make_test_failover_both_replicas", both_failovers)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", required=True, help="JSON config with PUBLIC LB address and optional hooks")
|
||||
parser.add_argument("--output", required=True, help="directory for raw, token-free results")
|
||||
parser.add_argument("--scenario", choices=["idempotency", "restart", "failover", "grade4", "rolling", "public", "all"], default="all")
|
||||
args = parser.parse_args()
|
||||
evidence = Evidence(args.output)
|
||||
try:
|
||||
config = json.loads(Path(args.config).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
evidence.case("configuration", lambda: (_ for _ in ()).throw(Failure(str(exc))))
|
||||
return evidence.finish()
|
||||
if args.scenario in ("idempotency", "restart", "all"):
|
||||
only = "idempotency_survives_restart" if args.scenario == "restart" else None
|
||||
evidence.case("idempotency_setup_and_suite", lambda: idempotency(config, evidence, only))
|
||||
if args.scenario in ("failover", "all"):
|
||||
evidence.case("public_lb_failover", lambda: failover(config, evidence))
|
||||
if args.scenario in ("grade4", "all"):
|
||||
grade4(config, evidence)
|
||||
if args.scenario == "rolling":
|
||||
grade4(config, evidence, only="rolling")
|
||||
if args.scenario in ("public", "all"):
|
||||
public_checks(config, evidence)
|
||||
return evidence.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,584 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Portable Compose acceptance runner and explicit persistence/outage hooks."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import shlex
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class CheckFailure(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class PersistenceOnlyComplete(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def command(args, *, env=None, timeout=90):
|
||||
result = subprocess.run(args, cwd=ROOT, env=env, capture_output=True,
|
||||
text=True, timeout=timeout)
|
||||
if result.returncode:
|
||||
raise CheckFailure("Command failed: " + " ".join(str(x) for x in args[:3]))
|
||||
return result.stdout
|
||||
|
||||
|
||||
def compose_base(env):
|
||||
project = env.get("COMPOSE_PROJECT_NAME", "")
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", project):
|
||||
raise CheckFailure("Set COMPOSE_PROJECT_NAME explicitly to the intended test project")
|
||||
files = env.get("COMPOSE_FILE", str(ROOT / "compose.yaml")).split(os.pathsep)
|
||||
base = ["docker", "compose", "--project-directory", str(ROOT), "-p", project]
|
||||
for file in files:
|
||||
if not file:
|
||||
raise CheckFailure("Empty COMPOSE_FILE entry")
|
||||
path = Path(file)
|
||||
if not path.is_absolute():
|
||||
path = ROOT / path
|
||||
base.extend(("-f", str(path.resolve())))
|
||||
return base
|
||||
|
||||
|
||||
def wait_ready(url, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url.rstrip("/") + "/health/ready", timeout=2) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except (OSError, urllib.error.URLError):
|
||||
pass
|
||||
time.sleep(0.25)
|
||||
raise CheckFailure("API did not become ready within the configured budget")
|
||||
|
||||
|
||||
def snapshot(base, env, services):
|
||||
result = {}
|
||||
for service in services:
|
||||
ids = command(base + ["ps", "-aq", service], env=env).split()
|
||||
if not ids or (service != "api" and len(ids) != 1):
|
||||
raise CheckFailure("Expected existing container(s) for " + service)
|
||||
containers = []
|
||||
for identifier in ids:
|
||||
raw = json.loads(command(["docker", "inspect", identifier], env=env))[0]
|
||||
labels = raw["Config"]["Labels"]
|
||||
if labels.get("com.docker.compose.project") != env["COMPOSE_PROJECT_NAME"] or \
|
||||
labels.get("com.docker.compose.service") != service:
|
||||
raise CheckFailure("Container belongs to another Compose project/service")
|
||||
containers.append({
|
||||
"id": raw["Id"], "started_at": raw["State"]["StartedAt"],
|
||||
"running": raw["State"]["Running"],
|
||||
"volumes": sorted(m["Name"] for m in raw["Mounts"] if m["Type"] == "volume"),
|
||||
})
|
||||
containers.sort(key=lambda item: item["id"])
|
||||
result[service] = containers if service == "api" else containers[0]
|
||||
return result
|
||||
|
||||
|
||||
def validate_transition(action, before, after):
|
||||
if not before or set(before) != set(after):
|
||||
raise CheckFailure("Missing lifecycle evidence")
|
||||
for service, old_group in before.items():
|
||||
new_group = after[service]
|
||||
old_items = old_group if isinstance(old_group, list) else [old_group]
|
||||
new_items = new_group if isinstance(new_group, list) else [new_group]
|
||||
old_by_id = {item["id"]: item for item in old_items}
|
||||
new_by_id = {item["id"]: item for item in new_items}
|
||||
if len(old_by_id) != len(old_items) or len(new_by_id) != len(new_items) or \
|
||||
set(old_by_id) != set(new_by_id):
|
||||
raise CheckFailure("Lifecycle action changed container set for " + service)
|
||||
for identifier, old in old_by_id.items():
|
||||
new = new_by_id[identifier]
|
||||
if old["volumes"] != new["volumes"]:
|
||||
raise CheckFailure("Lifecycle action changed volumes for " + service)
|
||||
if action in ("stop-db", "stop-cache"):
|
||||
if not old["running"] or new["running"]:
|
||||
raise CheckFailure("Service was not actually stopped: " + service)
|
||||
elif not new["running"] or old["started_at"] == new["started_at"]:
|
||||
raise CheckFailure("Service was not actually started/restarted: " + service)
|
||||
|
||||
|
||||
def record_lifecycle(path, action, project, before, after, source=None):
|
||||
validate_transition(action, before, after)
|
||||
if path:
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("a") as output:
|
||||
output.write(json.dumps({"action": action, "project": project,
|
||||
"source": source, "before": before, "after": after}) + "\n")
|
||||
|
||||
|
||||
def lifecycle(action, env=None):
|
||||
env = dict(os.environ if env is None else env)
|
||||
base = compose_base(env)
|
||||
config = json.loads(command(base + ["config", "--format", "json"], env=env))
|
||||
services = config["services"]
|
||||
stores = env.get("HL_STATE_SERVICES", "").split()
|
||||
if not stores:
|
||||
stores = [name for name in ("postgres", "redis", "valkey") if name in services]
|
||||
if action == "restart":
|
||||
targets = ["api"] + stores + (["lb"] if "lb" in services else [])
|
||||
elif "cache" in action:
|
||||
targets = [name for name in ("redis", "valkey") if name in services]
|
||||
if len(targets) != 1:
|
||||
raise CheckFailure("Expected exactly one configured Redis/Valkey service")
|
||||
else:
|
||||
targets = ["postgres"]
|
||||
if "postgres" not in stores or any(name not in services for name in targets):
|
||||
raise CheckFailure("Configured state stores do not match Compose services")
|
||||
before = snapshot(base, env, targets)
|
||||
verb = {"restart": "restart", "stop-db": "stop", "start-db": "start",
|
||||
"restart-cache": "restart", "stop-cache": "stop", "start-cache": "start"}[action]
|
||||
args = [verb] + (["--timeout", "20"] if verb in ("restart", "stop") else []) + targets
|
||||
command(base + args, env=env, timeout=65)
|
||||
if not action.startswith("stop-"):
|
||||
wait_ready(env.get("BASE_URL", "http://127.0.0.1:8080"), timeout=55)
|
||||
after = snapshot(base, env, targets)
|
||||
record_lifecycle(env.get("HL_LIFECYCLE_EVIDENCE"), action,
|
||||
env["COMPOSE_PROJECT_NAME"], before, after, source="stack.py")
|
||||
print("PASS: " + action + "; container state and volumes verified", flush=True)
|
||||
|
||||
|
||||
def go_results(output):
|
||||
events = []
|
||||
for line in output.splitlines():
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(event, dict):
|
||||
events.append(event)
|
||||
counts = Counter(x["Action"] for x in events if x.get("Test") and "/" not in x["Test"]
|
||||
and x.get("Action") in ("pass", "fail", "skip"))
|
||||
skipped = any(x.get("Test") and x.get("Action") == "skip" for x in events)
|
||||
if not counts["pass"] or counts["fail"] or skipped:
|
||||
raise CheckFailure("Go tests failed, were skipped, or did not run")
|
||||
return dict(counts)
|
||||
|
||||
|
||||
def free_ports():
|
||||
# Reserve both ports together so the two selections cannot collide.
|
||||
with socket.socket() as api, socket.socket() as postgres:
|
||||
api.bind(("127.0.0.1", 0))
|
||||
postgres.bind(("127.0.0.1", 0))
|
||||
return api.getsockname()[1], postgres.getsockname()[1]
|
||||
|
||||
|
||||
def verify(output, pull, measure=False, operation_budget_ms=None, persistence_only=False,
|
||||
lab3_only=False, lab3_scenario="all"):
|
||||
if not (persistence_only or lab3_only) and importlib.util.find_spec("openapi_spec_validator") is None:
|
||||
raise CheckFailure("Install test dependencies first: scripts/setup-tests.sh")
|
||||
output = output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
project = ("lab3-test-" if lab3_only else "lab2-test-") + secrets.token_hex(6)
|
||||
results = []
|
||||
summary = {"project": project, "status": "FAIL", "results": results,
|
||||
"scope": ("lab3-rolling-dual-diagnostic" if lab3_only and lab3_scenario == "rolling-dual" else
|
||||
"lab3-idempotency-only" if lab3_only and lab3_scenario == "idempotency" else
|
||||
"lab3-rolling-only" if lab3_only and lab3_scenario == "rolling" else
|
||||
"lab3-level4" if lab3_only else
|
||||
"persistence-only" if persistence_only else "full")}
|
||||
with tempfile.TemporaryDirectory(prefix=project + "-") as directory:
|
||||
tmp = Path(directory)
|
||||
api_port, pg_port = free_ports()
|
||||
direct_api_port = free_ports()[0]
|
||||
while direct_api_port in (api_port, pg_port):
|
||||
direct_api_port = free_ports()[0]
|
||||
password = secrets.token_hex(24)
|
||||
env = os.environ.copy()
|
||||
# Do not inherit an operator's application/database/Compose settings.
|
||||
for key in list(env):
|
||||
if key.startswith(("COMPOSE_", "DATABASE_", "AUTH_TEST_", "MIGRATE_TEST_", "LAB2_", "HL_")):
|
||||
del env[key]
|
||||
env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env.get("PATH", "")
|
||||
env.update(COMPOSE_PROJECT_NAME=project,
|
||||
COMPOSE_FILE=os.pathsep.join((str(ROOT / "compose.yaml"), str(tmp / "compose.test.yaml"))),
|
||||
BASE_URL=f"http://127.0.0.1:{api_port}",
|
||||
HL_LIFECYCLE_EVIDENCE=str(output / "lifecycle.jsonl"))
|
||||
env["LAB2_BASE_URL"] = env["BASE_URL"]
|
||||
# Old lab2 dependency/TTL tests need an API-generated response even
|
||||
# when the LB has excluded every unready backend. This port exists only
|
||||
# in the disposable test project, never in the production Compose file.
|
||||
env["AUTH_TEST_BASE_URL"] = f"http://127.0.0.1:{direct_api_port}"
|
||||
env["AUTH_TEST_STACK_RESTART_HOOK"] = str(ROOT / "scripts/restart.sh")
|
||||
env["AUTH_TEST_DIAGNOSTICS_DIR"] = str(output / "diagnostics")
|
||||
if operation_budget_ms is not None:
|
||||
env["AUTH_TEST_OPERATION_BUDGET_MS"] = str(operation_budget_ms)
|
||||
database = f"postgres://messenger:{password}@127.0.0.1:{pg_port}/messenger?sslmode=disable"
|
||||
env.update(AUTH_TEST_DATABASE_URL=database, MIGRATE_TEST_DATABASE_URL=database, LAB2_TEST_DATABASE_URL=database)
|
||||
for name, value in {
|
||||
"postgres_password": password,
|
||||
"database_url": f"postgres://messenger:{password}@postgres:5432/messenger?sslmode=disable",
|
||||
".env": (ROOT / ".env.example").read_text(),
|
||||
}.items():
|
||||
path = tmp / name
|
||||
path.write_text(value)
|
||||
path.chmod(0o600 if name == ".env" else 0o644)
|
||||
override = tmp / "compose.test.yaml"
|
||||
redis_port = None
|
||||
|
||||
def configure(ttl):
|
||||
# JSON strings are valid quoted YAML scalars, including paths with spaces.
|
||||
q = json.dumps
|
||||
api_scale = 2 if lab3_only else 1
|
||||
api_ports = (" ports: !override []" if lab3_only else
|
||||
f' ports: !override\n - "127.0.0.1:{direct_api_port}:8080"')
|
||||
segmented = lab3_only and lab3_scenario != "rolling"
|
||||
api_networks = " networks: [front, state]\n" if segmented else ""
|
||||
lb_networks = " networks: [front]\n" if segmented else ""
|
||||
state_networks = " networks: [state]\n" if segmented else ""
|
||||
network_definitions = "networks:\n front:\n state:\n" if segmented else ""
|
||||
override.write_text(f'''services:
|
||||
api:
|
||||
image: {project}-api:check
|
||||
scale: {api_scale}
|
||||
env_file: !override
|
||||
- {q(str(tmp / '.env'))}
|
||||
{api_ports}
|
||||
{api_networks} environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
SESSION_TTL_SECONDS: "{ttl}"
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
lb:
|
||||
{lb_networks} ports: !override
|
||||
- "127.0.0.1:{api_port}:8080"
|
||||
migrate:
|
||||
{state_networks} image: {project}-migrate:check
|
||||
postgres:
|
||||
{state_networks} ports: !override
|
||||
- "127.0.0.1:{pg_port}:5432"
|
||||
secrets:
|
||||
database_url:
|
||||
file: {q(str(tmp / 'database_url'))}
|
||||
postgres_password:
|
||||
file: {q(str(tmp / 'postgres_password'))}
|
||||
{network_definitions}
|
||||
''')
|
||||
if redis_port is not None:
|
||||
text = override.read_text().replace("secrets:\n database_url:", f''' redis:
|
||||
{state_networks} ports: !override
|
||||
- "127.0.0.1:{redis_port}:6379"
|
||||
secrets:
|
||||
database_url:''')
|
||||
text = text.replace(" APP_HOST: 0.0.0.0", " REDIS_ADDR: redis:6379\n SESSION_STORE: redis\n APP_HOST: 0.0.0.0")
|
||||
override.write_text(text)
|
||||
if measure:
|
||||
text = override.read_text().replace(' image: ' + project + '-api:check', ' cpus: 2.0\n mem_limit: 1g\n image: ' + project + '-api:check')
|
||||
text = text.replace(' postgres:\n ports:', ' postgres:\n cpus: 1.0\n mem_limit: 512m\n ports:')
|
||||
text = text.replace(' redis:\n ports:', ' redis:\n cpus: 0.5\n mem_limit: 256m\n ports:')
|
||||
override.write_text(text)
|
||||
|
||||
configure(3600)
|
||||
lab3_config = tmp / "lab3-restart.json"
|
||||
lab3_config.write_text(json.dumps({"base_url": env["BASE_URL"],
|
||||
"hooks": {"restart": [str(ROOT / "scripts/restart.sh")]}}))
|
||||
base = compose_base(env)
|
||||
services = command(base + ["config", "--services"], env=env).split()
|
||||
if "redis" in services:
|
||||
redis_port = free_ports()[0]
|
||||
while redis_port in (api_port, pg_port, direct_api_port):
|
||||
redis_port = free_ports()[0]
|
||||
configure(3600)
|
||||
env["AUTH_TEST_REDIS_ADDR"] = f"127.0.0.1:{redis_port}"
|
||||
restart = tmp / "restart-redis"
|
||||
restart.write_text("#!/bin/sh\nexec " + shlex.join([sys.executable, str(ROOT / "student-tests/stack.py"), "restart-cache"]) + "\n")
|
||||
restart.chmod(0o700)
|
||||
env["AUTH_TEST_REDIS_RESTART_HOOK"] = str(restart)
|
||||
summary["redis_fixture"] = "critical session store; explicit REDIS_ADDR=redis:6379 in test override"
|
||||
|
||||
if lab3_only:
|
||||
actions = [sys.executable, str(ROOT / "student-tests/lab3/docker_actions.py")]
|
||||
lab3_config.write_text(json.dumps({
|
||||
"base_url": env["BASE_URL"], "api_services": ["api"], "lb_services": ["lb"],
|
||||
"compose_base_argv": base, "compose_config_argv": base + ["config", "--format", "json"],
|
||||
"rolling_telemetry": lab3_scenario == "rolling-dual",
|
||||
"hooks": {
|
||||
"restart": [str(ROOT / "scripts/restart.sh")],
|
||||
"stop_one": [str(ROOT / "scripts/stop-one.sh")],
|
||||
"rolling_update": [str(ROOT / "scripts/rolling-update.sh")],
|
||||
**{name: actions + [name] for name in
|
||||
("start_one", "recover_all", "sigterm_one", "probe_stopped",
|
||||
"make_unready", "restore_ready", "probe_health",
|
||||
"lb_timing_evidence", "revoke_access", "restore_access")},
|
||||
},
|
||||
}))
|
||||
if lab3_scenario != "rolling":
|
||||
env["HL_STATE_NETWORK"] = project + "_state"
|
||||
if lab3_scenario in ("all", "rolling-dual"):
|
||||
# The readiness fault needs front+state networks. The working
|
||||
# rolling script runs on a one-network production stack and
|
||||
# asks Docker for all IPs concatenated. Resolve that one
|
||||
# inspect format to the actual front-network IP in this
|
||||
# test-only topology; every other Docker call is unchanged.
|
||||
real_docker = shutil.which("docker")
|
||||
if not real_docker:
|
||||
raise CheckFailure("Docker CLI unavailable for rolling IP adapter")
|
||||
shim = tmp / "docker"
|
||||
shim.write_text('''#!/bin/sh
|
||||
set -eu
|
||||
trace() {
|
||||
[ "${HL_ROLLING_TRACE_ACTIVE:-}" = 1 ] || return 0
|
||||
"$HL_TRACE_PYTHON" - "$HL_ROLLING_STEP_LOG" "$@" <<'PYTRACE'
|
||||
import datetime, json, sys
|
||||
record = {"time_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds"),
|
||||
"phase": sys.argv[2], "argv": sys.argv[3:]}
|
||||
with open(sys.argv[1], "a") as output:
|
||||
output.write(json.dumps(record) + "\\n")
|
||||
PYTRACE
|
||||
}
|
||||
trace begin "$@"
|
||||
if [ "$#" -eq 4 ] && [ "$1" = inspect ] && [ "$2" = --format ] &&
|
||||
[ "$3" = '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ]; then
|
||||
owner=$("$HL_REAL_DOCKER" inspect --format '{{index .Config.Labels "com.docker.compose.project"}}' "$4")
|
||||
[ "$owner" = "$COMPOSE_PROJECT_NAME" ] || exit 1
|
||||
format="{{(index .NetworkSettings.Networks \\"$HL_FRONT_NETWORK\\").IPAddress}}"
|
||||
if "$HL_REAL_DOCKER" inspect --format "$format" "$4"; then code=0; else code=$?; fi
|
||||
else
|
||||
if "$HL_REAL_DOCKER" "$@"; then code=0; else code=$?; fi
|
||||
fi
|
||||
trace end "$code" "$@"
|
||||
exit "$code"
|
||||
''')
|
||||
shim.chmod(0o700)
|
||||
env["HL_REAL_DOCKER"] = real_docker
|
||||
env["HL_FRONT_NETWORK"] = project + "_front"
|
||||
env["PATH"] = str(tmp) + os.pathsep + env["PATH"]
|
||||
summary["rolling_ip_adapter"] = "test-only Docker inspect selects the real front-network IP"
|
||||
if lab3_scenario == "rolling-dual":
|
||||
env["HL_TRACE_PYTHON"] = sys.executable
|
||||
env["HL_ROLLING_STEP_LOG"] = str(output / "lab3" / "rolling-docker-steps.jsonl")
|
||||
|
||||
def stage(name, args, timeout=180, parse_go=False, required=True, lifecycle_targets=None):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
before_lifecycle = snapshot(base, env, lifecycle_targets) if lifecycle_targets else None
|
||||
process = subprocess.run(args, cwd=ROOT, env=env, capture_output=True,
|
||||
text=True, timeout=timeout)
|
||||
text = process.stdout + process.stderr
|
||||
# Never put the generated fixture credential or DSN in artifacts.
|
||||
text = text.replace(database, "<test-database-url>").replace(password, "<test-password>")
|
||||
(output / (name + ".log")).write_text(text)
|
||||
if process.returncode:
|
||||
raise CheckFailure(name + " failed; see its sanitized test log")
|
||||
if lifecycle_targets:
|
||||
after_lifecycle = snapshot(base, env, lifecycle_targets)
|
||||
record_lifecycle(env.get("HL_LIFECYCLE_EVIDENCE"), "restart",
|
||||
project, before_lifecycle, after_lifecycle, source=name)
|
||||
detail = go_results(process.stdout) if parse_go else None
|
||||
results.append({"check": name, "status": "PASS", "seconds": round(time.monotonic() - started, 3),
|
||||
**({"tests": detail} if detail else {})})
|
||||
print("PASS: " + name, flush=True)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
def decode(value):
|
||||
return value.decode(errors="replace") if isinstance(value, bytes) else (value or "")
|
||||
partial = decode(error.stdout) + decode(error.stderr)
|
||||
partial = partial.replace(database, "<test-database-url>").replace(password, "<test-password>")
|
||||
(output / (name + ".log")).write_text(partial)
|
||||
results.append({"check": name, "status": "FAIL", "detail": "TimeoutExpired",
|
||||
"seconds": round(time.monotonic() - started, 3), "runner_budget_seconds": timeout})
|
||||
if required:
|
||||
raise CheckFailure(name + " timed out; see partial sanitized log") from None
|
||||
print("FAIL: " + name + "; partial log retained; continuing independent checks", flush=True)
|
||||
except (OSError, subprocess.SubprocessError, CheckFailure) as error:
|
||||
results.append({"check": name, "status": "FAIL", "detail": type(error).__name__})
|
||||
if required:
|
||||
raise CheckFailure(name + " failed; see test artifacts") from None
|
||||
print("FAIL: " + name + "; continuing independent checks", flush=True)
|
||||
|
||||
try:
|
||||
if not (persistence_only or lab3_only):
|
||||
stage("contracts", ["make", "check", "validate", "PYTHON=" + Path(sys.executable).name])
|
||||
stage("harness", [sys.executable, "-m", "unittest", "discover", "-s", "student-tests", "-p", "test_stack.py", "-v"])
|
||||
stage("lab2-harness", [sys.executable, "-m", "unittest", "discover", "-s", "student-tests/lab2", "-p", "test_harness.py", "-v"])
|
||||
if lab3_only:
|
||||
# Subscribe before the clean Compose project is created. Docker
|
||||
# Desktop may not retain historical events for a later query.
|
||||
events_path = output / "docker-start-events.jsonl"
|
||||
errors_path = output / "docker-events.stderr.log"
|
||||
with events_path.open("wb") as events_stream, errors_path.open("wb") as errors_stream:
|
||||
watcher = subprocess.Popen(
|
||||
["docker", "events", "--filter", "type=container", "--filter", "event=start",
|
||||
"--filter", "label=com.docker.compose.project=" + project,
|
||||
"--format", "{{json .}}"], cwd=ROOT, env=env,
|
||||
stdout=events_stream, stderr=errors_stream)
|
||||
time.sleep(.5)
|
||||
try:
|
||||
stage("compose-up", base + ["up", "-d", "--build", "--pull", pull,
|
||||
"--wait", "--wait-timeout", "90"], 300)
|
||||
finally:
|
||||
watcher.terminate()
|
||||
watcher.wait(timeout=5)
|
||||
events = []
|
||||
for line in events_path.read_text().splitlines():
|
||||
try:
|
||||
events.append(json.loads(line))
|
||||
except ValueError:
|
||||
pass
|
||||
migrate_starts = sum(
|
||||
(event.get("Actor") or {}).get("Attributes", {}).get("com.docker.compose.service") == "migrate"
|
||||
and event.get("Action") == "start" for event in events)
|
||||
migrate_ids = command(base + ["ps", "-aq", "migrate"], env=env).split()
|
||||
api_ids = command(base + ["ps", "-q", "api"], env=env).split()
|
||||
if len(migrate_ids) == 1 and len(api_ids) == 2:
|
||||
migrator = json.loads(command(["docker", "inspect", migrate_ids[0]], env=env))[0]
|
||||
apis = [json.loads(command(["docker", "inspect", identifier], env=env))[0]
|
||||
for identifier in api_ids]
|
||||
finished = migrator["State"]["FinishedAt"]
|
||||
migration = {
|
||||
"project": project, "migration_starts": migrate_starts,
|
||||
"migration_exit_code": migrator["State"]["ExitCode"],
|
||||
"migration_container_id": migrator["Id"],
|
||||
"migration_finished_at": finished,
|
||||
"api_containers": [{"id": item["Id"], "started_at": item["State"]["StartedAt"]}
|
||||
for item in apis],
|
||||
"api_started_before_migration_complete": any(
|
||||
item["State"]["StartedAt"] < finished for item in apis),
|
||||
"recorded_start_events": len(events),
|
||||
}
|
||||
evidence_path = output / "migration-evidence.json"
|
||||
evidence_path.write_text(json.dumps(migration, indent=2) + "\n")
|
||||
if events:
|
||||
config_value = json.loads(lab3_config.read_text())
|
||||
config_value["hooks"]["migration_evidence"] = actions + ["migration_evidence"]
|
||||
lab3_config.write_text(json.dumps(config_value))
|
||||
env["HL_MIGRATION_EVIDENCE"] = str(evidence_path)
|
||||
else:
|
||||
stage("compose-up", base + ["up", "-d", "--build", "--pull", pull,
|
||||
"--wait", "--wait-timeout", "90"], 300)
|
||||
wait_ready(env["BASE_URL"])
|
||||
if lab3_only:
|
||||
stage("lab3-" + lab3_scenario if lab3_scenario != "all" else "lab3-level4",
|
||||
[sys.executable, "student-tests/lab3/run.py",
|
||||
"--config", str(lab3_config),
|
||||
"--output", str(output / "lab3"),
|
||||
"--scenario", "rolling" if lab3_scenario == "rolling-dual" else lab3_scenario],
|
||||
timeout=420, required=False)
|
||||
summary["status"] = "FAIL" if any(x["status"] == "FAIL" for x in results) else "PASS"
|
||||
raise PersistenceOnlyComplete
|
||||
if persistence_only:
|
||||
stage("teacher-persistence", ["make", "test-persistence", "BASE_URL=" + env["BASE_URL"],
|
||||
"PYTHON=" + Path(sys.executable).name,
|
||||
"ACTION_SCRIPT=" + str(ROOT / "scripts/restart.sh")],
|
||||
required=False, lifecycle_targets=["api", "postgres", "redis", "lb"])
|
||||
stage("lab3-restart-idempotency", [sys.executable, "student-tests/lab3/run.py",
|
||||
"--config", str(lab3_config),
|
||||
"--output", str(output / "lab3-restart"),
|
||||
"--scenario", "restart"],
|
||||
required=False, lifecycle_targets=["api", "postgres", "redis", "lb"])
|
||||
summary["status"] = "FAIL" if any(x["status"] == "FAIL" for x in results) else "PASS"
|
||||
raise PersistenceOnlyComplete
|
||||
# Compile race-instrumented packages separately. Cold compilation is
|
||||
# not an application-operation latency test and must not consume
|
||||
# the execution budget of the actual integration tests.
|
||||
stage("go-race-build", ["go", "test", "-race", "-run", "^$", "./..."], timeout=300)
|
||||
stage("go-race", ["go", "test", "-race", "./...", "-count=1", "-json"], parse_go=True, timeout=600, required=False)
|
||||
stage("go-build", ["go", "build", "./..."], required=False)
|
||||
stage("go-vet", ["go", "vet", "./..."], required=False)
|
||||
stage("teacher-smoke", ["make", "test", "BASE_URL=" + env["BASE_URL"], "PYTHON=" + Path(sys.executable).name], required=False)
|
||||
auth = [sys.executable, "student-tests/auth_contract.py", "--base-url", env["AUTH_TEST_BASE_URL"], "--ttl", "3600"]
|
||||
if redis_port is not None:
|
||||
auth.extend(("--session-store", "redis"))
|
||||
stage("auth-normal", auth, required=False)
|
||||
stage("business", [sys.executable, "student-tests/lab2/run.py", "--suite", "business-boundaries", "--suite", "business-cursors", "--suite", "read-after-write", "--output", str(output / "business.json")], required=False)
|
||||
stage("sql-plan-10000", [sys.executable, "student-tests/lab2/run.py", "--suite", "sql-plan", "--output", str(output / "sql-plan.json")], timeout=180, required=False)
|
||||
if measure:
|
||||
resources = {}
|
||||
for role, cpus in (("api", 2.0), ("postgres", 1.0), ("redis", 0.5)):
|
||||
identifier = command(base + ["ps", "-q", role], env=env).strip()
|
||||
resources[role] = {"name": identifier, "cpus": cpus, "memory_limit_mib": {"api": 1024, "postgres": 512, "redis": 256}[role]}
|
||||
env["LAB2_RESOURCE_CONTAINERS"] = json.dumps(resources)
|
||||
stage("latency-matrix", [sys.executable, "student-tests/lab2/budgets.py", "--base-url", env["BASE_URL"], "--output", str(output / "latency")], timeout=300, required=False)
|
||||
stage("teacher-persistence", ["make", "test-persistence", "BASE_URL=" + env["BASE_URL"],
|
||||
"PYTHON=" + Path(sys.executable).name, "ACTION_SCRIPT=" + str(ROOT / "scripts/restart.sh")],
|
||||
required=False, lifecycle_targets=["api", "postgres", "redis", "lb"])
|
||||
stage("lab3-restart-idempotency", [sys.executable, "student-tests/lab3/run.py",
|
||||
"--config", str(lab3_config),
|
||||
"--output", str(output / "lab3-restart"),
|
||||
"--scenario", "restart"],
|
||||
required=False, lifecycle_targets=["api", "postgres", "redis", "lb"])
|
||||
stage("auth-persistence", auth + ["--suite", "persistence", "--restart-hook", str(ROOT / "scripts/restart.sh")],
|
||||
required=False, lifecycle_targets=["api", "postgres", "redis", "lb"])
|
||||
stage("postgres-outage", auth + ["--suite", "dependency", "--dependency", "postgres", "--timeout", "5",
|
||||
"--failure-hook", str(ROOT / "scripts/stop-postgres.sh"),
|
||||
"--recovery-hook", str(ROOT / "scripts/start-postgres.sh")], required=False)
|
||||
if redis_port is not None:
|
||||
stage("redis-outage", auth + ["--suite", "dependency", "--dependency", "redis", "--cache-policy", "critical", "--timeout", "5",
|
||||
"--failure-hook", str(ROOT / "scripts/stop-redis.sh"),
|
||||
"--recovery-hook", str(ROOT / "scripts/start-redis.sh")], required=False)
|
||||
configure(2)
|
||||
stage("short-ttl-api", base + ["up", "-d", "--no-build", "--no-deps", "api"])
|
||||
wait_ready(env["BASE_URL"])
|
||||
stage("auth-expiry", [sys.executable, "student-tests/auth_contract.py", "--base-url", env["AUTH_TEST_BASE_URL"], "--suite", "expiry", "--ttl", "2"], required=False)
|
||||
summary["status"] = "FAIL" if any(x["status"] == "FAIL" for x in results) else "PASS"
|
||||
except PersistenceOnlyComplete:
|
||||
pass
|
||||
except (OSError, subprocess.SubprocessError, CheckFailure) as error:
|
||||
summary["failure"] = str(error) if isinstance(error, CheckFailure) else type(error).__name__
|
||||
finally:
|
||||
# Only this newly generated project's own resources may be removed.
|
||||
try:
|
||||
stage("cleanup", base + ["down", "--volumes", "--remove-orphans", "--timeout", "20"], 90)
|
||||
containers = command(["docker", "ps", "-aq", "--filter", "label=com.docker.compose.project=" + project], env=env)
|
||||
volumes = command(["docker", "volume", "ls", "-q", "--filter", "label=com.docker.compose.project=" + project], env=env)
|
||||
if containers.strip() or volumes.strip():
|
||||
raise CheckFailure("Disposable project resources remain after cleanup")
|
||||
except (OSError, subprocess.SubprocessError, CheckFailure):
|
||||
summary["status"] = "FAIL"
|
||||
summary["cleanup_failed"] = True
|
||||
(output / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
print(summary["status"] + ": " + str(output / "summary.json"), flush=True)
|
||||
return 0 if summary["status"] == "PASS" else 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("verify", "restart", "stop-db", "start-db", "restart-cache", "stop-cache", "start-cache"))
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "student-tests/output" / time.strftime("%Y%m%d-%H%M%S"))
|
||||
parser.add_argument("--measure-budgets", action="store_true", help="bounded 1/5/10 HTTP matrix with explicit container limits")
|
||||
parser.add_argument("--persistence-only", action="store_true", help="same isolated Compose project, only public persistence and lab3 restart replay")
|
||||
parser.add_argument("--lab3-only", action="store_true", help="disposable two-replica lab3/LB level-4 run; saves evidence and cleans only its own project")
|
||||
parser.add_argument("--lab3-scenario", choices=("all", "rolling", "rolling-dual", "idempotency"), default="all",
|
||||
help="with --lab3-only: run one focused scenario in a fresh project, or the full suite")
|
||||
parser.add_argument("--operation-budget-ms", type=int, help="explicitly agreed operation budget; omitted keeps provisional 3000ms")
|
||||
parser.add_argument("--pull", choices=("missing", "never", "always"), default="missing")
|
||||
args = parser.parse_args()
|
||||
if args.persistence_only and args.lab3_only:
|
||||
parser.error("choose either --persistence-only or --lab3-only")
|
||||
if args.lab3_scenario != "all" and not args.lab3_only:
|
||||
parser.error("--lab3-scenario requires --lab3-only")
|
||||
if args.operation_budget_ms is not None and not 500 <= args.operation_budget_ms <= 10000:
|
||||
parser.error("operation budget must be 500..10000 ms")
|
||||
if args.action == "verify":
|
||||
# Normal CI cancellation must run the same finally cleanup as failures.
|
||||
def interrupted(_number, _frame):
|
||||
raise CheckFailure("Test run interrupted")
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
signal.signal(signal.SIGINT, interrupted)
|
||||
return verify(args.output, args.pull, args.measure_budgets, args.operation_budget_ms,
|
||||
args.persistence_only, args.lab3_only, args.lab3_scenario)
|
||||
lifecycle(args.action)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, ValueError, KeyError, subprocess.SubprocessError, CheckFailure) as error:
|
||||
print("FAIL: " + (str(error) if isinstance(error, CheckFailure) else type(error).__name__), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,117 @@
|
||||
import copy
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import json
|
||||
|
||||
import stack
|
||||
|
||||
|
||||
class StackTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.before = {"postgres": {"id": "owned", "started_at": "before",
|
||||
"running": True, "volumes": ["owned_data"]}}
|
||||
|
||||
def test_noop_restart_cannot_pass(self):
|
||||
with self.assertRaises(stack.CheckFailure):
|
||||
stack.validate_transition("restart", self.before, copy.deepcopy(self.before))
|
||||
|
||||
def test_changed_volume_cannot_pass_restart(self):
|
||||
after = copy.deepcopy(self.before)
|
||||
after["postgres"].update(started_at="after", volumes=["other_data"])
|
||||
with self.assertRaises(stack.CheckFailure):
|
||||
stack.validate_transition("restart", self.before, after)
|
||||
|
||||
def test_stopped_container_cannot_pass_restart(self):
|
||||
after = copy.deepcopy(self.before)
|
||||
after["postgres"].update(started_at="after", running=False)
|
||||
with self.assertRaises(stack.CheckFailure):
|
||||
stack.validate_transition("restart", self.before, after)
|
||||
|
||||
def test_actual_stop_and_start_preserve_the_same_volume(self):
|
||||
stopped = copy.deepcopy(self.before)
|
||||
stopped["postgres"]["running"] = False
|
||||
stack.validate_transition("stop-db", self.before, stopped)
|
||||
started = copy.deepcopy(self.before)
|
||||
started["postgres"]["started_at"] = "after"
|
||||
stack.validate_transition("start-db", stopped, started)
|
||||
|
||||
def test_cache_stop_and_restart_require_real_changes(self):
|
||||
before = {"redis": self.before["postgres"]}
|
||||
stopped = copy.deepcopy(before)
|
||||
stopped["redis"]["running"] = False
|
||||
stack.validate_transition("stop-cache", before, stopped)
|
||||
started = copy.deepcopy(before)
|
||||
started["redis"]["started_at"] = "after"
|
||||
stack.validate_transition("start-cache", stopped, started)
|
||||
stack.validate_transition("restart-cache", before, started)
|
||||
with self.assertRaises(stack.CheckFailure):
|
||||
stack.validate_transition("restart-cache", before, copy.deepcopy(before))
|
||||
|
||||
def test_two_api_replicas_must_both_restart_without_recreation(self):
|
||||
before = {"api": [dict(self.before["postgres"], id="api-1", volumes=[]),
|
||||
dict(self.before["postgres"], id="api-2", volumes=[])]}
|
||||
after = copy.deepcopy(before)
|
||||
for item in after["api"]:
|
||||
item["started_at"] = "after"
|
||||
stack.validate_transition("restart", before, after)
|
||||
partial = copy.deepcopy(after)
|
||||
partial["api"][1]["started_at"] = "before"
|
||||
with self.assertRaises(stack.CheckFailure):
|
||||
stack.validate_transition("restart", before, partial)
|
||||
replaced = copy.deepcopy(after)
|
||||
replaced["api"][1]["id"] = "new-api-2"
|
||||
with self.assertRaises(stack.CheckFailure):
|
||||
stack.validate_transition("restart", before, replaced)
|
||||
|
||||
def test_snapshot_collects_all_api_replicas_and_checks_project(self):
|
||||
def fake_command(argv, **_):
|
||||
if argv[-3:] == ["ps", "-aq", "api"]:
|
||||
return "api-2\napi-1\n"
|
||||
if argv[:2] == ["docker", "inspect"]:
|
||||
identifier = argv[2]
|
||||
return json.dumps([{"Id": identifier,
|
||||
"Config": {"Labels": {"com.docker.compose.project": "isolated",
|
||||
"com.docker.compose.service": "api"}},
|
||||
"State": {"StartedAt": "time-" + identifier, "Running": True},
|
||||
"Mounts": []}])
|
||||
self.fail("unexpected Docker command")
|
||||
with patch.object(stack, "command", side_effect=fake_command):
|
||||
result = stack.snapshot(["docker", "compose"], {"COMPOSE_PROJECT_NAME": "isolated"}, ["api"])
|
||||
self.assertEqual([item["id"] for item in result["api"]], ["api-1", "api-2"])
|
||||
|
||||
def test_lifecycle_evidence_records_actual_states_without_hook_stdout(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "lifecycle.jsonl"
|
||||
after = copy.deepcopy(self.before)
|
||||
after["postgres"]["started_at"] = "after"
|
||||
stack.record_lifecycle(path, "restart", "isolated", self.before, after,
|
||||
source="teacher-persistence")
|
||||
proof = json.loads(path.read_text())
|
||||
self.assertEqual(proof["source"], "teacher-persistence")
|
||||
self.assertEqual(proof["project"], "isolated")
|
||||
self.assertEqual(proof["after"]["postgres"]["started_at"], "after")
|
||||
|
||||
def test_skipped_or_empty_go_run_cannot_pass(self):
|
||||
for output in ("", '{"Action":"skip","Test":"TestStorage"}',
|
||||
'{"Action":"pass","Test":"TestStorage"}\n{"Action":"skip","Test":"TestStorage/subcase"}',
|
||||
'{"Action":"pass","Test":"TestOne"}\n{"Action":"skip","Test":"TestStorage"}'):
|
||||
with self.subTest(output=output), self.assertRaises(stack.CheckFailure):
|
||||
stack.go_results(output)
|
||||
|
||||
def test_project_must_be_explicit_before_any_docker_action(self):
|
||||
for project in ("", "bad project", "../other", "-option"):
|
||||
with self.subTest(project=project), self.assertRaises(stack.CheckFailure):
|
||||
stack.compose_base({"COMPOSE_PROJECT_NAME": project})
|
||||
|
||||
def test_compose_paths_with_spaces_remain_single_arguments(self):
|
||||
with tempfile.TemporaryDirectory(prefix="compose files ") as directory:
|
||||
path = str(Path(directory) / "override.yaml")
|
||||
args = stack.compose_base({"COMPOSE_PROJECT_NAME": "lab2-test-paths", "COMPOSE_FILE": path})
|
||||
self.assertEqual(args[-2:], ["-f", str(Path(path).resolve())])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Contract-based lab2 JSON edge cases; all data is synthetic.
|
||||
|
||||
Uses raw HTTP bodies for byte encoding and field-name checks. Expectations
|
||||
come from contracts/README.md and CreateUser/CreateChat/CreateMessage schemas.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, LAB, check, shape # noqa: E402
|
||||
|
||||
|
||||
def encoded(value):
|
||||
return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
def source_fingerprint():
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted([ROOT / name for name in ("go.mod", "go.sum", "Dockerfile", ".dockerignore")]
|
||||
+ list((ROOT / "cmd").rglob("*.go"))
|
||||
+ list((ROOT / "internal").rglob("*.go"))):
|
||||
digest.update(path.relative_to(ROOT).as_posix().encode() + b"\0")
|
||||
digest.update(path.read_bytes() + b"\0")
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def cases_for(client):
|
||||
owner = client.user("edge")
|
||||
chat = client.call("POST", "/api/v1/chats", 201, actor=owner,
|
||||
body={"title": "Validation audit", "member_ids": [owner["id"]]},
|
||||
schema="Chat")["json"]
|
||||
endpoints = (
|
||||
("users", "/api/v1/users", None, "User", ("username", "display_name", "password")),
|
||||
("chats", "/api/v1/chats", owner, "Chat", ("title", "member_ids")),
|
||||
("messages", "/api/v1/chats/" + chat["id"] + "/messages", owner, "Message", ("text",)),
|
||||
)
|
||||
|
||||
def body_for(endpoint):
|
||||
if endpoint == "users":
|
||||
return {"username": "edge_" + uuid.uuid4().hex[:16], "display_name": "Probe",
|
||||
"password": "Synthetic:validation-password"}
|
||||
if endpoint == "chats":
|
||||
return {"title": "Probe", "member_ids": [owner["id"]]}
|
||||
return {"text": "CASE_PROBE"}
|
||||
|
||||
cases = []
|
||||
|
||||
def add(endpoint, group, name, body=None, raw=None, expected=400, echo=None):
|
||||
label, path, actor, schema, _ = endpoint
|
||||
cases.append({"name": label + ": " + name, "group": group, "path": path,
|
||||
"actor": actor, "schema": schema, "raw": raw if raw is not None else encoded(body),
|
||||
"expected": expected, "echo": echo,
|
||||
"headers": {"Idempotency-Key": uuid.uuid4().hex} if label == "messages" and LAB >= 3 else {}})
|
||||
|
||||
invalid_bytes = (("ff", b"\xff"), ("continuation", b"\x80"), ("overlong", b"\xc0\xaf"),
|
||||
("truncated", b"\xe2\x82"), ("surrogate bytes", b"\xed\xa0\x80"),
|
||||
("above U+10FFFF", b"\xf4\x90\x80\x80"))
|
||||
for endpoint in endpoints:
|
||||
label, _, _, _, fields = endpoint
|
||||
for field in fields:
|
||||
aliases = [field.upper(), field[0].upper() + field[1:]]
|
||||
if "s" in field:
|
||||
aliases.append(field.replace("s", "ſ"))
|
||||
for alias in dict.fromkeys(aliases):
|
||||
for extra in (False, True):
|
||||
body = body_for(label)
|
||||
body[alias] = body[field] if extra else body.pop(field)
|
||||
add(endpoint, "key_case", field + " alias " + alias + (" extra" if extra else " only"), body)
|
||||
body = body_for(label)
|
||||
body.pop(field)
|
||||
add(endpoint, "shape", "missing " + field, body)
|
||||
wrong_values = (None, True, 1, {}, [], "not-an-array") if field == "member_ids" else (None, True, 1, {}, [])
|
||||
for wrong in wrong_values:
|
||||
body = body_for(label)
|
||||
body[field] = wrong
|
||||
add(endpoint, "shape", field + " type " + type(wrong).__name__, body)
|
||||
for root in (None, True, 1, "string", []):
|
||||
add(endpoint, "shape", "root " + type(root).__name__, root)
|
||||
body = body_for(label)
|
||||
body["extra"] = True
|
||||
add(endpoint, "shape", "unknown field", body)
|
||||
for suffix in (b"{}", b"null", b" garbage"):
|
||||
add(endpoint, "shape", "trailing " + suffix.decode(), raw=encoded(body_for(label)) + suffix)
|
||||
for raw in (b"", b'{"', b"{\"x\":NaN}", b'{"x":"\x00"}'):
|
||||
add(endpoint, "shape", "malformed " + raw.hex(), raw=raw)
|
||||
|
||||
value_field = {"users": "display_name", "chats": "title", "messages": "text"}[label]
|
||||
for name, bad in invalid_bytes:
|
||||
body = body_for(label)
|
||||
body[value_field] = "BYTE_PROBE"
|
||||
add(endpoint, "utf8", value_field + " invalid UTF-8 " + name,
|
||||
raw=encoded(body).replace(b"BYTE_PROBE", b"prefix" + bad + b"suffix"))
|
||||
for value in ("Привет 😀", "�", "e\u0301", "\U0010ffff"):
|
||||
body = body_for(label)
|
||||
body[value_field] = value
|
||||
add(endpoint, "utf8", value_field + " valid " + ascii(value), body, expected=201, echo=body)
|
||||
body = body_for(label)
|
||||
body[value_field] = "😀"
|
||||
add(endpoint, "utf8", "valid escaped surrogate pair",
|
||||
raw=json.dumps(body, ensure_ascii=True).encode(), expected=201, echo=body)
|
||||
body = body_for(label)
|
||||
raw = encoded(body).replace(('"' + value_field + '"').encode(),
|
||||
('"\\u%04x%s"' % (ord(value_field[0]), value_field[1:])).encode())
|
||||
add(endpoint, "key_case", "escaped canonical key", raw=raw, expected=201, echo=body)
|
||||
body = body_for(label)
|
||||
raw = encoded(body).replace(('"' + value_field + '"').encode(),
|
||||
('"\\u%04x%s"' % (ord(value_field[0].upper()), value_field[1:].upper())).encode())
|
||||
add(endpoint, "key_case", "escaped uppercase key", raw=raw)
|
||||
for value in ("", " \t\n ", "\u00a0\u2003", "😀" * (4001 if label == "messages" else 101)):
|
||||
body = body_for(label)
|
||||
body[value_field] = value
|
||||
add(endpoint, "boundaries", value_field + " invalid length/space " + str(len(value)), body)
|
||||
body = body_for(label)
|
||||
body[value_field] = "😀" * (4000 if label == "messages" else 100)
|
||||
add(endpoint, "boundaries", value_field + " exact Unicode maximum", body, expected=201, echo=body)
|
||||
|
||||
# The contract does not specify duplicate-key or lone-surrogate policy.
|
||||
# Keep these as observations, without asserting a required HTTP status.
|
||||
for escape in (b"\\ud800", b"\\udc00"):
|
||||
body = body_for(label)
|
||||
body[value_field] = "ESCAPE_PROBE"
|
||||
add(endpoint, "observations", "unpaired escape " + escape.decode(),
|
||||
raw=encoded(body).replace(b"ESCAPE_PROBE", escape), expected=None)
|
||||
raw = encoded(body_for(label))
|
||||
add(endpoint, "observations", "duplicate key then null",
|
||||
raw=raw[:-1] + b',"' + value_field.encode() + b'":null}', expected=None)
|
||||
|
||||
for value in ("ab", "Aaa", "a-a", "abc\n", "кириллица", "a" * 33):
|
||||
body = body_for("users")
|
||||
body["username"] = value
|
||||
add(endpoints[0], "boundaries", "invalid username " + ascii(value), body)
|
||||
for value in ([], [owner["id"], owner["id"]], [str(uuid.uuid4())],
|
||||
[owner["id"], str(uuid.uuid4())], [owner["id"], None], [owner["id"], "not-uuid"]):
|
||||
body = body_for("chats")
|
||||
body["member_ids"] = value
|
||||
add(endpoints[1], "boundaries", "invalid members " + repr(value), body)
|
||||
return cases
|
||||
|
||||
|
||||
def run(client, groups=None, verbose=True):
|
||||
results = []
|
||||
for case in cases_for(client):
|
||||
if case["group"] == "observations" and (groups is None or "observations" not in groups):
|
||||
continue
|
||||
if groups is not None and case["group"] not in groups:
|
||||
continue
|
||||
result = {key: case[key] for key in ("name", "group", "path", "expected")}
|
||||
# Request bodies may contain a registration password; do not put them
|
||||
# in evidence, even as hex. Tokens remain only in the teacher client.
|
||||
try:
|
||||
response = client.call("POST", case["path"], expected=list(range(200, 600)),
|
||||
actor=case["actor"], raw=case["raw"],
|
||||
headers={"Content-Type": "application/json", **case["headers"]})
|
||||
result["actual"] = response["status"]
|
||||
if case["expected"] is None:
|
||||
result["status"] = "OBSERVED"
|
||||
if response["status"] == 201:
|
||||
result["response"] = json.loads(response["bytes"])
|
||||
else:
|
||||
check(response["status"] == case["expected"],
|
||||
"expected %s, received %s" % (case["expected"], response["status"]))
|
||||
if response["status"] == 400:
|
||||
check(response["json"]["error"]["code"] == "invalid_request", "wrong error code")
|
||||
elif response["status"] == 201:
|
||||
payload = json.loads(response["bytes"])
|
||||
shape(payload, case["schema"])
|
||||
check(all(payload.get(k) == v for k, v in case["echo"].items()
|
||||
if k != "password"), "valid fields changed")
|
||||
check("password" not in payload and "password_hash" not in payload,
|
||||
"response exposed password material")
|
||||
result["status"] = "PASS"
|
||||
except (Failure, OSError, ValueError) as exc:
|
||||
result.update(status="FAIL", details=str(exc))
|
||||
results.append(result)
|
||||
if verbose:
|
||||
print(result["status"] + ": " + result["name"] +
|
||||
(": " + result["details"] if "details" in result else ""))
|
||||
return results
|
||||
|
||||
|
||||
def acceptance(client, group=None):
|
||||
results = run(client, {group} if group else None, verbose=False)
|
||||
check(bool(results), "validation group has no cases")
|
||||
failures = [x for x in results if x["status"] == "FAIL"]
|
||||
check(not failures, "; ".join(x["name"] + ": " + x["details"] for x in failures))
|
||||
return {"json_cases": len(results)}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--output")
|
||||
parser.add_argument("--include-observations", action="store_true")
|
||||
parser.add_argument("--tested-source-sha256", help="Fingerprint of the source used to build the tested server")
|
||||
args = parser.parse_args()
|
||||
if args.tested_source_sha256 and (len(args.tested_source_sha256) != 64 or
|
||||
any(c not in "0123456789abcdef" for c in args.tested_source_sha256)):
|
||||
parser.error("--tested-source-sha256 must be a lowercase SHA-256")
|
||||
groups = {"key_case", "utf8", "shape", "boundaries"}
|
||||
if args.include_observations:
|
||||
groups.add("observations")
|
||||
results = run(Client(args.base_url), groups)
|
||||
failures = sum(x["status"] == "FAIL" for x in results)
|
||||
observed = sum(x["status"] == "OBSERVED" for x in results)
|
||||
checked = len(results) - observed
|
||||
summary = {"status": "FAIL" if failures else "PASS", "passed": checked - failures,
|
||||
"failed": failures, "checked": checked, "observations": observed}
|
||||
print("SUMMARY:", json.dumps(summary))
|
||||
if args.output:
|
||||
report = {"date_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
"commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),
|
||||
"tested_source_sha256": args.tested_source_sha256,
|
||||
"working_tree_source_sha256": source_fingerprint(), "base_url": args.base_url,
|
||||
"scope": "HTTP JSON validation only; no Docker/runtime checks",
|
||||
"command": [sys.executable, *sys.argv], "summary": summary, "cases": results}
|
||||
target = Path(args.output)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user