forked from mtusi2026/mtusi2026lab2
ЛР 2: закрыть уровень 4
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
# Проверки авторизации после перехода на 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: настоящий запрос репозитория, первая и глубокая страницы |
|
||||
| Границы бизнес-запросов, пагинация, ACL, read-after-write | lab2/business.py; публичный smoke отдельно |
|
||||
|
||||
Проверки, требующие серверов, без явных тестовых адресов получают 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,184 @@
|
||||
# Собственные проверки лабораторной 1
|
||||
|
||||
Требования берутся из корневого README и `contracts/README.md`. Публичные assertions не ослабляются. Все пользователи, чаты и тексты синтетические.
|
||||
|
||||
## Уже запущенный API
|
||||
|
||||
```sh
|
||||
python3 student-tests/level4.py --base-url http://localhost:8080
|
||||
```
|
||||
|
||||
Одна команда запускает 17 сценариев: пять обязательных негативных/пагинационных сценариев уровня 4, отправку 100 сообщений от 10 клиентов и дополнительные условия базового контракта: Content-Type, поля JSON, формат 404, limit/cursor, привязку cursor, список чатов и Unicode-границы. HTTP-клиент и проверка схем переиспользованы из публичного `tests/client.py`; сами сценарии отдельные. Exit 0 означает успех всех сценариев, exit 1 — хотя бы один FAIL.
|
||||
|
||||
Дополнительная проверка после замечаний от 03.10.2026 включена в ту же команду: точный регистр имён полей всех трёх POST endpoint, неизвестные поля, повреждённые UTF-8 bytes, обязательные поля, `null`, неверные типы, второй JSON/мусор после тела и границы строк/участников. Валидные Unicode, символ `�`, корректная surrogate-пара и экранированное каноническое имя поля должны сохраняться. В актуальной версии на Go 1.27.1 используется `encoding/json/v2` с `json.RejectUnknownMembers(true)`: ошибки декодирования возвращают 400. Выполнено 162/162 обязательных проверок. Подробный результат можно получить отдельно:
|
||||
|
||||
```sh
|
||||
python3 student-tests/validation_edges.py --base-url http://localhost:8080 \
|
||||
--output evidence/validation-edges.json
|
||||
```
|
||||
|
||||
`--include-observations` дополнительно фиксирует дубликаты JSON-ключей и непарные `\uD800`/`\uDC00`. Контракт не задаёт для них отдельную политику; эти наблюдения не входят в PASS/FAIL обязательных проверок. Текущая реализация отклоняет все девять наблюдений с 400. Исторические 13/13 PASS не подтверждают новые сценарии. Проверка создаёт только синтетические данные и требует запущенный API.
|
||||
|
||||
## Изолированный контейнер и результаты
|
||||
|
||||
```sh
|
||||
python3 student-tests/container_level4.py --build \
|
||||
--image highload-lab1-audit:local --output evidence/level4.json
|
||||
```
|
||||
|
||||
Нужны Docker, make и Python 3.9+. Скрипт собирает образ из временной копии текущих отслеживаемых файлов, создаёт контейнер с 1 CPU / 128 MiB, публикует свободный порт только на 127.0.0.1, запускает `make check`, `make test` и собственные HTTP-тесты. Затем проверяет конфигурацию порта, UID, отсутствие Go в runtime, healthcheck, сброс памяти после рестарта, SIGTERM с завершением активного запроса и отказом новым запросам, логи без тестовых маркеров сообщений.
|
||||
|
||||
После завершения собственные контейнеры удаляются; другие контейнеры не изменяются. Образ остаётся для воспроизведения. `--build` можно опустить для проверки уже собранного образа. Полный JSON сохраняется по `--output`; рядом при сборке создаётся файл `*-build.txt`. В результатах записываются версия Docker, аппаратные сведения, лимиты, image ID, базовый HEAD и fingerprint исходников. Если рабочее дерево не закоммичено, это явно отмечается.
|
||||
|
||||
Сборка копии текущих отслеживаемых файлов не подтверждает содержимое опубликованного commit. Новые исходники и тесты нужно включить в сдаваемую версию проекта самостоятельно. Команда создаёт данные только внутри своего контейнера; после удаления они теряются.
|
||||
|
||||
## Оценка 5, трек 1: корректность после изменения
|
||||
|
||||
Нужны Docker с Linux cgroup v2, Go 1.27.1+ и Python 3.9+; поддерживаются macOS/Linux. Дополнительные библиотеки не требуются. `track1_load.go` — отдельный HTTP-клиент без импортов приложения; `track1.py` собирает его во временном каталоге, управляет контейнерами и сохраняет результаты. Исходники приложения, обязательный контракт и публичные тесты не изменяются.
|
||||
|
||||
```sh
|
||||
python3 student-tests/track1.py check --build \
|
||||
--image highload-lab1-track1:check --output evidence/track1-check.json
|
||||
```
|
||||
|
||||
Команда запускает `make check`, `make test`, собственные HTTP-проверки уровня 4 и следующие проверки истории:
|
||||
|
||||
- 203 исходных сообщения от 10 клиентов; полный обход с `limit=1,7,50,100`.
|
||||
- Порядок `(created_at, id)` с сохранением наносекунд; уникальность ID и полное совпадение сообщений с ответами POST.
|
||||
- Изменение `limit` с 3 на 79 при продолжении, последняя неполная страница и завершение cursor.
|
||||
- Пустая история, 404 для постороннего пользователя, 400 для cursor другого чата.
|
||||
- Ещё 100 записей от 10 клиентов одновременно с тремя обходами истории. После завершения — ровно 303 уникальных сообщения без потерь и изменения содержимого.
|
||||
|
||||
Проверка не требует snapshot между страницами. Во время конкурентного обхода проверяются порядок, отсутствие повторов и сохранность исходной истории; после остановки записи проверяются все подтверждённые сообщения. Скачок системных часов назад в сценарий не включён.
|
||||
|
||||
## Оценка 5, трек 1: матрица нагрузки
|
||||
|
||||
До изменения реализации:
|
||||
|
||||
```sh
|
||||
python3 student-tests/track1.py run --build \
|
||||
--image highload-lab1-track1:before --label before \
|
||||
--output evidence/track1-before.json
|
||||
```
|
||||
|
||||
После одного изменения реализации:
|
||||
|
||||
```sh
|
||||
python3 student-tests/track1.py run --build \
|
||||
--image highload-lab1-track1:after --label after \
|
||||
--output evidence/track1-after.json
|
||||
|
||||
python3 student-tests/track1.py compare \
|
||||
--before evidence/track1-before.json --after evidence/track1-after.json \
|
||||
--output evidence/track1-comparison.json
|
||||
```
|
||||
|
||||
Параметры по умолчанию: истории 100 / 1 000 / 10 000 сообщений, конкуренция 1 / 5 / 10, три повтора каждого сочетания, прогрев 5 с и измерение 30 с. Каждый профиль получает отдельный свежий контейнер с 1 CPU, 128 MiB RAM, без дополнительного swap. Размер синтетического ASCII-текста — 128 байт, страница — 50 элементов. GET чередует первую, среднюю и последнюю полную страницу; cursor получается от сервера и не конструируется клиентом. Подготовка данных и полные проверки истории не входят в измеряемую фазу.
|
||||
|
||||
Сохраняются JSON и CSV: успешные RPS, число/доля ошибок, p50/p95/p99 успешных запросов, CPU клиента, CPU контейнера, RSS процесса и память cgroup, временные ресурсные отсчёты, размеры истории, image ID, fingerprint исходников/генератора, параметры и результаты предварительных проверок. RSS читается из `/proc/1/status`; CPU — по разности `usage_usec` cgroup v2. Память cgroup включает cache и не подменяет RSS. Отсчёты ресурсов берутся каждые 0,5 с; пик означает максимум наблюдённых отсчётов, а не точный максимум.
|
||||
|
||||
Для короткого исходного эксперимента используются параметры `--duration 10 --warmup 2 --repeats 1`. Они также должны быть указаны при сравнительном запуске. Для окончательного исследования рекомендуется стандартный профиль с тремя повторами. Сравнение проверяет совпадение методики, ресурсов, стенда и версии генератора; выводит медиану и min/max по повторам. Один и тот же image ID до/после отклоняется как отсутствие подтверждённого изменения приложения.
|
||||
|
||||
Дополнительный сценарий `--workloads read,mixed` добавляет нагрузку с записью каждого двадцатого запроса. Он позволяет проверить задержки POST при чтении истории; история растёт во время прогрева и измерения, начальный и конечный размеры фиксируются. Это отдельный профиль, его нельзя сравнивать с чистым чтением как с одинаковой нагрузкой.
|
||||
|
||||
Выход 0 означает корректность сценариев и сбор измерений; он **не подтверждает оценку 5 или улучшение**. Ошибки HTTP/таймауты учитываются в метриках отдельно; нарушения содержимого/порядка, OOM, остановка процесса и ошибки сбора ресурсов делают запуск неуспешным. Подтверждённые сообщения проверяются после нагрузки. В mixed-профиле отдельно учитываются записи, которые могли сохраниться без полученного подтверждения; retry отсутствует.
|
||||
|
||||
Генератор работает в closed loop с HTTP/1.1 keep-alive: каждый клиент ожидает завершения своего запроса. Есть coordinated omission; задержки включают чтение JSON и клиентскую проверку данных. Клиент и Docker работают на одном компьютере, сбор ресурсов расходует часть CPU контейнера. Поэтому результаты характеризуют указанный стенд и профиль, а не абсолютный предел сервера. Для сохранения исходных результатов уже существующий output не перезаписывается; используйте новые имена файлов и разные теги before/after. Созданные контейнеры удаляются; образы остаются. Коммитов, staging и push сценарий не выполняет.
|
||||
|
||||
## Повторное сравнение на Go 1.27.1 от 03.10.2026
|
||||
|
||||
Обе версии используют Go 1.27.1, JSON v2 и один генератор. Для «до» сценарий `track1_baseline.py` создаёт временный локальный clone, копирует текущие файлы и заменяет **только** `../internal/repository/message.go` версией из commit `9de1152204e649c733d442255467dd81e1f16c59`. Подготовка записана в `baseline_preparation` итогового JSON. Рабочая копия проекта не изменяется; commit, staging и push не выполняются.
|
||||
|
||||
Команды выполненного короткого эксперимента:
|
||||
|
||||
```sh
|
||||
python3 student-tests/track1_baseline.py \
|
||||
--image highload-lab1-go127:before \
|
||||
--output evidence/track1-before-go127-2026-10-03.json
|
||||
|
||||
python3 student-tests/track1.py run --build \
|
||||
--image highload-lab1-go127:after --label after-go127 \
|
||||
--histories 100,1000,10000 --concurrency 1,5,10 \
|
||||
--duration 10 --warmup 2 --repeats 1 \
|
||||
--output evidence/track1-after-go127-2026-10-03.json
|
||||
|
||||
python3 student-tests/track1.py compare \
|
||||
--before evidence/track1-before-go127-2026-10-03.json \
|
||||
--after evidence/track1-after-go127-2026-10-03.json \
|
||||
--output evidence/track1-comparison-go127-2026-10-03.json
|
||||
```
|
||||
|
||||
Для повторения выбирайте новые output-файлы. Параметры `track1_baseline.py` фиксированы: истории 100/1000/10000, конкуренция 1/5/10, прогрев 2 с, измерение 10 с, один повтор; вариант «после» должен использовать те же значения. Более длительный профиль выполняется отдельно на обеих версиях по методике выше.
|
||||
|
||||
[До](../evidence/track1-before-go127-2026-10-03.json), [после](../evidence/track1-after-go127-2026-10-03.json), [сравнение](../evidence/track1-comparison-go127-2026-10-03.json). Результаты и ограничения приведены в [REPORT.md](../REPORT.md).
|
||||
|
||||
Термин `no retries` в выводе Go означает отсутствие повторов в цикле генератора. Стандартный `net/http.Transport` может безопасно восстановить запрос после некоторых ошибок ранее использованного соединения, в частности GET. Такие сетевые попытки отдельно не считаются: измеряются HTTP-вызовы клиента и их полное время.
|
||||
|
||||
## Историческое сравнение от 01.10.2026
|
||||
|
||||
[До](../evidence/track1-before-2026-10-01.json), [после](../evidence/track1-after-2026-10-01.json), [сравнение](../evidence/track1-comparison-2026-10-01.json), [контейнерная проверка](../evidence/level4-after-track1-2026-10-01.json) относятся к прежней версии Go и прежнему набору HTTP-проверок. Они сохранены для истории и не подтверждают исправление замечаний к JSON. Не сравнивайте эти измерения с Go 1.27.1 как эксперимент с одним изменением.
|
||||
|
||||
Для воспроизведения прежней исходной версии нужны её сохранённый образ `highload-lab1-track1:before-20261001` без `--build` либо отдельная копия commit `9de1152`. Текущая рабочая копия включает миграцию на Go 1.27.1 и отличается от обоих образов от 01.10.2026.
|
||||
|
||||
## Проверка в CI
|
||||
|
||||
### GitFlic
|
||||
|
||||
Конфигурация для платформы сдачи — [gitflic-ci.yaml](../gitflic-ci.yaml). Конвейер допускает push, событие merge request и ручной запуск из веб-интерфейса. Для автоматического MR-конвейера нужно также включить «Запуск конвейера слияния» в настройках проекта. [Справочник YAML](https://docs.gitflic.ru/latest/cicd/gitflic-ci-yaml/), [запуск конвейеров](https://docs.gitflic.ru/latest/cicd/pipeline/).
|
||||
|
||||
Задачи выполняются последовательно; ошибка любой задачи завершает конвейер с ошибкой:
|
||||
|
||||
1. `contracts`: отдельное временное Python-окружение, установка `requirements-dev.txt`, `make check validate`. Окружение удаляется; вывод сохраняется в `build/gitflic-ci/contracts.txt`.
|
||||
2. `application`: сборка уникального Docker-образа, `container_level4.py --build` и `track1.py check` для этого же образа. Проверяются публичный API, собственные сценарии уровня 4, 100 сообщений от 10 клиентов, конфигурация порта, UID/runtime, healthcheck, перезапуск, SIGTERM, логи и целостность истории при конкурентных записях. Полная нагрузочная матрица до/после остаётся отдельным экспериментом на указанном в отчёте стенде.
|
||||
|
||||
JSON, CSV и лог сборки находятся в `build/gitflic-ci/application-<UUID>/`. Новое имя для каждого запуска предотвращает конфликт тегов и перезапись результатов трека 1. Задачи сохраняют уже созданные артефакты и при ошибке (`when: always`); срок хранения — 30 дней. Тестовые контейнеры удаляют сценарии, а образ задачи удаляет shell trap с сохранением исходного exit code. `build/` уже исключён из Git; итоговые материалы для сдачи сохраняются отдельно в `evidence/`. Пароли приложения и доступ к реестру для этих задач не требуются.
|
||||
|
||||
#### Требования к runner
|
||||
|
||||
Обе задачи используют тег **`lab1-shell`**. Нужен отдельный runner типа **Shell**, которому доступны Python 3.9+ с `venv`/`pip`, Git, make, Go 1.27.1+ и локальный Docker Engine с Linux cgroup v2. На Linux узел runner и опубликованные порты Docker должны находиться в одной сетевой среде: тесты используют `127.0.0.1`. Обычный Docker executor с сокетом внешнего Docker-host для этой конфигурации не подходит. Runner выделяется этому проекту; общий Docker-host других проектов не используется согласно CONTRIBUTING.md.
|
||||
|
||||
Пользователь подтвердил 02.10.2026, что runner пока не подключён. На публичном `gitflic.ru` регистрация собственного runner выполняется на уровне **компании**; регистрация непосредственно в настройках личного проекта доступна только в self-hosted версиях. Требуется runner, доступный проекту в соответствующем контуре компании/учебного CI. Если у личного fork такого доступа нет, сначала согласуется с преподавателем размещение fork в компании или предоставление подходящего runner. Настройка компании и перенос проекта автоматически не выполняются. [Регистрация Shell runner](https://docs.gitflic.ru/latest/setup/runner/installshell/), [область регистрации агентов](https://docs.gitflic.ru/latest/cicd/agent/).
|
||||
|
||||
#### Подключение и первый запуск
|
||||
|
||||
1. Установить на отдельном Linux-узле совместимую версию GitFlic Runner по официальной инструкции; для Shell нужны также `helper.jar` и исполняемый `helper.sh`. Установить инструменты из списка выше. Проверить их доступность от пользователя, запускающего агент:
|
||||
|
||||
```sh
|
||||
sudo -u gitflic-runner python3 --version
|
||||
sudo -u gitflic-runner go version
|
||||
sudo -u gitflic-runner git --version
|
||||
sudo -u gitflic-runner make --version
|
||||
sudo -u gitflic-runner docker info --format '{{.CgroupVersion}}'
|
||||
```
|
||||
|
||||
Последняя команда должна вернуть `2`. Пользователь runner должен иметь доступ к Docker Engine на этом же узле.
|
||||
|
||||
2. В настройках компании открыть «Агенты CI/CD», получить Registration URL и token. Следующие команды выполнить **в Bash на узле runner**, из каталога с установленным `runner.jar`. Token вводится локально и не записывается в репозиторий:
|
||||
|
||||
```bash
|
||||
cd /opt/gitflic-runner
|
||||
read -r -p "Registration URL: " lab1_runner_url
|
||||
read -r -s -p "Registration token: " lab1_runner_token
|
||||
printf '\n'
|
||||
sudo -u gitflic-runner java -jar runner.jar register \
|
||||
--url "$lab1_runner_url" --registration-token "$lab1_runner_token" \
|
||||
--name lab1-shell --tags lab1-shell
|
||||
unset lab1_runner_token
|
||||
```
|
||||
|
||||
3. В созданном файле `config/application.properties` указать `runner.executor=shell`, рабочий каталог и каталог helper согласно инструкции установки. Запустить агент через установленный service или, для первого запуска:
|
||||
|
||||
```sh
|
||||
sudo -u gitflic-runner java -jar runner.jar start --config=config/application.properties
|
||||
```
|
||||
|
||||
В интерфейсе GitFlic проверить, что агент активен, имеет тег `lab1-shell`, доступен проекту и принимает задачи ветки `solution/BPI2304-remez`.
|
||||
|
||||
4. В настройках CI/CD проекта указать путь **`gitflic-ci.yaml`**. Для MR включить «Запуск конвейера слияния». Опубликовать конфигурацию и документы в своей ветке. [Настройки CI/CD](https://docs.gitflic.ru/latest/cicd/cicd-settings/).
|
||||
5. Открыть «CI/CD → Конвейеры → Создать конвейер», выбрать `solution/BPI2304-remez`. Ожидаемый результат: обе задачи успешны; `level4.json` и `track1.json` содержат `status: PASS`. Скачать артефакты и сохранить ссылку на фактический конвейер для отчёта. Последующие push запускают тот же конвейер автоматически.
|
||||
|
||||
Точные scripts обеих задач GitFlic CI локально прошли 02.10.2026: [сводка](../evidence/gitflic-ci-local-2026-10-02.json). YAML и синтаксис shell проверены; это не подтверждает регистрацию runner или удалённый запуск GitFlic.
|
||||
|
||||
### GitHub
|
||||
|
||||
При размещении проекта на GitHub сохраняется альтернативный `.github/workflows/application.yml`: сборка и контейнерные проверки с JSON/логом как artifact `lab1-application-checks`. Точная команда локально прошла 02.10.2026: [результат](../evidence/level4-ci.json), [лог](../evidence/level4-ci-build.txt). Этот workflow автоматически не выполняется на GitFlic.
|
||||
@@ -0,0 +1,177 @@
|
||||
# Запуск тестов лабораторной 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. Все Go-тесты с `-race` на настоящих PostgreSQL и Redis. SKIP считается ошибкой.
|
||||
Включены миграции до 3, откат 3 → 2 → 1 → 3, структура восстановленной
|
||||
sessions и сохранность четырёх бизнес-таблиц.
|
||||
4. Публичный `make test`, 16 HTTP auth-проверок, границы бизнес-запросов,
|
||||
пагинация и чтение после записи.
|
||||
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.
|
||||
Время 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,535 @@
|
||||
#!/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):
|
||||
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"]},
|
||||
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 != 2:
|
||||
p.error("this suite targets the lab2 contract")
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
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 := 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,443 @@
|
||||
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), chats, userService)
|
||||
return httptransport.NewRouter(middleware.NewMiddleware(auth), 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.
|
||||
acceptanceCtx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
|
||||
defer cancel()
|
||||
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) {
|
||||
cmd := exec.CommandContext(acceptanceCtx, "python3", tc.args...)
|
||||
cmd.Dir = root
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
// 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,121 @@
|
||||
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}
|
||||
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")
|
||||
}
|
||||
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)
|
||||
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)
|
||||
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), chatService, f.users)
|
||||
router := httptransport.NewRouter(
|
||||
middleware.NewMiddleware(f.auth), 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=600)
|
||||
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,293 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build and verify an isolated lab1 container; save sanitized evidence.
|
||||
|
||||
python3 student-tests/container_level4.py --build --output evidence/level4.json
|
||||
Requires Docker, make and Python 3.9+. Removes only its own test container.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
|
||||
def command(args, timeout=60, required=True):
|
||||
result = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if required and result.returncode:
|
||||
raise Failure("command failed: " + args[0] + " (exit %d)" % result.returncode)
|
||||
return result
|
||||
|
||||
|
||||
def docker(*args, required=True):
|
||||
result = command(["docker", *args], required=required)
|
||||
return (result.stdout + result.stderr if args[0] == "logs" else result.stdout).strip()
|
||||
|
||||
|
||||
def inspect(name):
|
||||
return json.loads(docker("inspect", name))[0]
|
||||
|
||||
|
||||
def wait_for(predicate, seconds, message):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.1)
|
||||
raise Failure(message)
|
||||
|
||||
|
||||
def source_fingerprint():
|
||||
paths = [ROOT / name for name in ("Dockerfile", ".dockerignore", "go.mod", "go.sum")]
|
||||
paths += list((ROOT / "cmd").rglob("*.go")) + list((ROOT / "internal").rglob("*.go"))
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted(paths):
|
||||
digest.update(str(path.relative_to(ROOT)).encode() + b"\0" + path.read_bytes() + b"\0")
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--image", default="highload-lab1-audit:local")
|
||||
parser.add_argument("--build", action="store_true")
|
||||
parser.add_argument("--output", default="evidence/level4.json")
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
evidence = {
|
||||
"checked_at_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
"git_head": command(["git", "rev-parse", "HEAD"]).stdout.strip(),
|
||||
"uncommitted_working_files": bool(command(["git", "status", "--porcelain"]).stdout),
|
||||
"source_sha256": source_fingerprint(),
|
||||
"host": {"system": platform.system(), "architecture": platform.machine()},
|
||||
"limits": {"cpu": 1, "memory_bytes": 128 * 1024 * 1024},
|
||||
"checks": [],
|
||||
}
|
||||
if platform.system() == "Darwin":
|
||||
hardware = command(["sysctl", "-n", "machdep.cpu.brand_string", "hw.memsize", "hw.ncpu"], required=False)
|
||||
if hardware.returncode == 0:
|
||||
cpu, memory, cores = hardware.stdout.splitlines()
|
||||
evidence["host"].update({"cpu": cpu, "memory_bytes": int(memory), "logical_cpus": int(cores)})
|
||||
name = "highload-lab1-check-" + uuid.uuid4().hex[:12]
|
||||
created = False
|
||||
markers = []
|
||||
|
||||
def record(label, scenario):
|
||||
try:
|
||||
details = scenario()
|
||||
status = "FAIL" if isinstance(details, dict) and details.get("exit_code", 0) else "PASS"
|
||||
evidence["checks"].append({"name": label, "status": status, "details": details})
|
||||
print(status + ":", label, flush=True)
|
||||
if status == "FAIL":
|
||||
print(details.get("output", ""), flush=True)
|
||||
except (Failure, OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
evidence["checks"].append({"name": label, "status": "FAIL", "details": str(exc)})
|
||||
print("FAIL: %s: %s" % (label, exc), flush=True)
|
||||
|
||||
try:
|
||||
info = json.loads(docker("info", "--format", "{{json .}}"))
|
||||
evidence["docker"] = {key: info.get(key) for key in
|
||||
("ServerVersion", "OperatingSystem", "Architecture", "NCPU", "MemTotal")}
|
||||
if args.build:
|
||||
started = time.monotonic()
|
||||
# Use current contents of tracked files; omit untracked IDE/runtime files.
|
||||
with tempfile.TemporaryDirectory(prefix="highload-clean-build-") as directory:
|
||||
tracked = command(["git", "ls-files", "-z"]).stdout.split("\0")
|
||||
for relative in filter(None, tracked):
|
||||
source = ROOT / relative
|
||||
if source.is_file():
|
||||
target = Path(directory) / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, target)
|
||||
build = command(["docker", "build", "--progress=plain", "-t", args.image, directory],
|
||||
timeout=300, required=False)
|
||||
build_log = output.with_name(output.stem + "-build.txt")
|
||||
build_log.write_text(build.stdout + build.stderr)
|
||||
evidence["build"] = {
|
||||
"command": "docker build --progress=plain -t %s <copy-of-current-tracked-files>" % args.image,
|
||||
"context": "current tracked working files, not a committed clone",
|
||||
"exit_code": build.returncode,
|
||||
"seconds": round(time.monotonic() - started, 3),
|
||||
"log": str(build_log.relative_to(ROOT)),
|
||||
}
|
||||
check(build.returncode == 0, "Docker build failed; see saved build log")
|
||||
image = json.loads(docker("image", "inspect", args.image))[0]
|
||||
evidence["image"] = {"tag": args.image, "id": image["Id"],
|
||||
"configured_user": image["Config"].get("User"),
|
||||
"healthcheck": image["Config"].get("Healthcheck")}
|
||||
docker("run", "-d", "--name", name, "--cpus=1", "--memory=128m",
|
||||
"-p", "127.0.0.1::8080", "-e", "APP_HOST=0.0.0.0", "-e", "APP_PORT=8080", args.image)
|
||||
created = True
|
||||
binding = inspect(name)["NetworkSettings"]["Ports"]["8080/tcp"][0]
|
||||
base = "http://127.0.0.1:" + binding["HostPort"]
|
||||
client = Client(base, timeout=2)
|
||||
|
||||
def ready():
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return True
|
||||
except Failure:
|
||||
return False
|
||||
|
||||
wait_for(ready, 15, "container did not become ready")
|
||||
|
||||
def external(invocation, display=None):
|
||||
result = command(invocation, required=False)
|
||||
return {"command": display or " ".join(invocation),
|
||||
"exit_code": result.returncode, "output": (result.stdout + result.stderr).strip()}
|
||||
|
||||
record("offline structure", lambda: external(["make", "check"]))
|
||||
record("public smoke", lambda: external(["make", "test", "BASE_URL=" + base]))
|
||||
record("own contract and 100-message tests", lambda: external(
|
||||
[sys.executable, "student-tests/level4.py", "--base-url", base],
|
||||
"python3 student-tests/level4.py --base-url " + base))
|
||||
|
||||
def configuration():
|
||||
other = name + "-port"
|
||||
docker("run", "-d", "--name", other, "--cpus=1", "--memory=128m",
|
||||
"-p", "127.0.0.1::8091", "-e", "APP_HOST=0.0.0.0", "-e", "APP_PORT=8091", args.image)
|
||||
try:
|
||||
port = inspect(other)["NetworkSettings"]["Ports"]["8091/tcp"][0]["HostPort"]
|
||||
alternate = Client("http://127.0.0.1:" + port, timeout=2)
|
||||
def alternate_ready():
|
||||
try:
|
||||
alternate.call("GET", "/health/ready", schema="Health")
|
||||
return True
|
||||
except Failure:
|
||||
return False
|
||||
wait_for(alternate_ready, 10, "APP_PORT=8091 did not change listening port")
|
||||
return {"APP_HOST": "0.0.0.0", "APP_PORT": "8091", "ready_status": 200,
|
||||
"note": "image healthcheck remains fixed to 8080; this tests HTTP configuration only"}
|
||||
finally:
|
||||
command(["docker", "rm", "--force", other], required=False)
|
||||
|
||||
record("configuration from environment", configuration)
|
||||
|
||||
def runtime():
|
||||
uid = int(docker("exec", name, "id", "-u"))
|
||||
check(uid != 0, "runtime user is root")
|
||||
compiler = command(["docker", "exec", name, "which", "go"], required=False)
|
||||
check(compiler.returncode == 1, "Go compiler present in runtime")
|
||||
return {"uid": uid, "go_compiler_present": False, "app_files": docker("exec", name, "ls", "/app")}
|
||||
|
||||
record("non-root and separate runtime", runtime)
|
||||
|
||||
def health():
|
||||
check(image["Config"].get("Healthcheck"), "image has no healthcheck")
|
||||
wait_for(lambda: inspect(name)["State"].get("Health", {}).get("Status") == "healthy",
|
||||
35, "Docker healthcheck did not become healthy")
|
||||
return {"status": "healthy"}
|
||||
|
||||
record("Docker healthcheck", health)
|
||||
|
||||
def lifecycle():
|
||||
nonlocal binding, base
|
||||
actor = client.user("lifecycle")
|
||||
chat = client.call("POST", "/api/v1/chats", 201, actor=actor,
|
||||
body={"title": "Lifecycle", "member_ids": [actor["id"]]}, schema="Chat")["json"]
|
||||
text = "private-test-marker-" + uuid.uuid4().hex
|
||||
markers.append(text)
|
||||
message = client.message(actor, chat, text)["json"]
|
||||
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages",
|
||||
actor=actor, schema="MessagePage")["json"]
|
||||
check(history["items"] == [message], "message not visible before restart")
|
||||
docker("restart", "--time", "10", name)
|
||||
binding = inspect(name)["NetworkSettings"]["Ports"]["8080/tcp"][0]
|
||||
base = "http://127.0.0.1:" + binding["HostPort"]
|
||||
client.base = base
|
||||
wait_for(ready, 15, "container not ready after restart")
|
||||
response = client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
return {"message_visible_before_restart": True, "old_user_after_restart": response["status"]}
|
||||
|
||||
record("in-memory lifecycle", lifecycle)
|
||||
|
||||
def shutdown():
|
||||
actor = client.user("shutdown")
|
||||
chat = client.call("POST", "/api/v1/chats", 201, actor=actor,
|
||||
body={"title": "Shutdown", "member_ids": [actor["id"]]}, schema="Chat")["json"]
|
||||
text = "drain-test-marker-" + uuid.uuid4().hex
|
||||
markers.append(text)
|
||||
body = json.dumps({"text": text}).encode()
|
||||
headers = ("POST /api/v1/chats/%s/messages HTTP/1.1\r\nHost: localhost\r\n"
|
||||
"X-User-Id: %s\r\nContent-Type: application/json\r\nContent-Length: %d\r\n"
|
||||
"Connection: close\r\n\r\n" % (chat["id"], actor["id"], len(body))).encode()
|
||||
baseline = docker("logs", name).count("shutdown signal received")
|
||||
with socket.create_connection(("127.0.0.1", int(binding["HostPort"])), timeout=3) as active:
|
||||
active.sendall(headers + body[:-1])
|
||||
time.sleep(0.2)
|
||||
started = time.monotonic()
|
||||
docker("kill", "--signal=TERM", name)
|
||||
wait_for(lambda: docker("logs", name).count("shutdown signal received") > baseline,
|
||||
3, "SIGTERM not observed in logs")
|
||||
check(inspect(name)["State"]["Running"], "process exited before draining active request")
|
||||
rejected = 0
|
||||
for _ in range(5):
|
||||
request = urllib.request.Request(base + "/health/live", headers={"Connection": "close"})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=0.5):
|
||||
pass
|
||||
except (urllib.error.URLError, OSError):
|
||||
rejected += 1
|
||||
check(rejected == 5, "new requests were accepted after SIGTERM")
|
||||
active.sendall(body[-1:])
|
||||
response = b""
|
||||
while True:
|
||||
chunk = active.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
response += chunk
|
||||
check(response.split(b"\r\n", 1)[0].startswith(b"HTTP/1.1 201"),
|
||||
"active valid request did not finish with 201")
|
||||
wait_for(lambda: not inspect(name)["State"]["Running"], 9, "process did not stop")
|
||||
elapsed = time.monotonic() - started
|
||||
state = inspect(name)["State"]
|
||||
check(elapsed <= 10 and state["ExitCode"] == 0, "SIGTERM exceeded 10 seconds or exited abnormally")
|
||||
return {"seconds": round(elapsed, 3), "exit_code": state["ExitCode"],
|
||||
"new_requests_rejected": rejected, "active_request_status": 201}
|
||||
|
||||
record("SIGTERM, new requests and active request drain", shutdown)
|
||||
|
||||
def logging():
|
||||
result = command(["docker", "logs", name])
|
||||
logs = result.stdout + result.stderr
|
||||
check(all(marker not in logs for marker in markers), "message body found in logs")
|
||||
lines = logs.splitlines()
|
||||
request_lines = [line for line in lines if "http request" in line]
|
||||
check(request_lines, "no useful request logs")
|
||||
check(all("method=" in line and "status=" in line and "duration=" in line
|
||||
and "request_id=" in line and 'request_id=""' not in line for line in request_lines),
|
||||
"request logs lack useful fields or request IDs")
|
||||
check("server started" in logs and "shutdown signal received" in logs, "missing lifecycle logs")
|
||||
return {"request_lines": len(request_lines), "message_markers_present": False,
|
||||
"fields": ["method", "path", "status", "duration", "request_id"]}
|
||||
|
||||
record("useful logs without message contents", logging)
|
||||
except (Failure, OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
evidence["checks"].append({"name": "setup", "status": "FAIL", "details": str(exc)})
|
||||
print("FAIL: setup:", exc, flush=True)
|
||||
finally:
|
||||
if created:
|
||||
command(["docker", "rm", "--force", name], required=False)
|
||||
evidence["status"] = "PASS" if evidence["checks"] and all(
|
||||
item["status"] == "PASS" for item in evidence["checks"]) else "FAIL"
|
||||
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
|
||||
print("SUMMARY: %s; evidence: %s" % (evidence["status"], args.output), flush=True)
|
||||
return 0 if evidence["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,203 @@
|
||||
# Заготовки проверок lab2 на оценку 5
|
||||
|
||||
Ниже — тесты и тестовые адаптеры. Код приложения, обязательный контракт,
|
||||
публичные tests/ и основной Compose не меняются. Переносимый runner и активный
|
||||
workflow Gitea описаны в [RUNNING.md](../RUNNING.md).
|
||||
Основание: [полный чек-лист](../../LAB2_CHECKLIST.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-стенд не поднимает.
|
||||
|
||||
`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 track1 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,91 @@
|
||||
"""Additional lab2 API cases, using the unchanged teacher client."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import check, timestamp
|
||||
|
||||
|
||||
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})
|
||||
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"]})
|
||||
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"})
|
||||
|
||||
|
||||
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"})
|
||||
check(history(c, actor, first, limit=2) == ordered, "complete keyset traversal differs")
|
||||
|
||||
|
||||
def read_after_write(c, client_factory, concurrency=4):
|
||||
actor = c.user("concurrent")
|
||||
chat = room(c, actor)
|
||||
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()
|
||||
confirmed = local.message(actor, chat, "Read-after-write " + str(index))["json"]
|
||||
page = local.call("GET", path, actor=actor, 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(min(32, concurrency * 4))))
|
||||
check({m["id"] for m in history(c, actor, chat)} == {m["id"] for m in messages},
|
||||
"concurrent writes lost or duplicated confirmations")
|
||||
@@ -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,448 @@
|
||||
#!/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"))
|
||||
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 malformed JSON",
|
||||
"business-cursors": "Cursor binding, changing limit, empty/complete pages and ACL",
|
||||
"read-after-write": "Concurrent confirmations 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,474 @@
|
||||
// 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"
|
||||
|
||||
"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
|
||||
}
|
||||
|
||||
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) {
|
||||
repo := postgres.NewMessageRepository(sqlc.New(f.pool))
|
||||
f.record.mu.Lock()
|
||||
f.record.active = true
|
||||
f.record.mu.Unlock()
|
||||
started := time.Now()
|
||||
items, err := repo.GetMessagesByChatID(ctx, f.chats[0], 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 = errors.New("fixture history returned an unexpected page length")
|
||||
}
|
||||
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) {
|
||||
if _, err := f.read(ctx, 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")
|
||||
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" {
|
||||
os.Exit(2)
|
||||
}
|
||||
signals, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
ctx, cancel := context.WithTimeout(signals, 3*time.Minute)
|
||||
defer cancel()
|
||||
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,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,275 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 1 level-4 acceptance checks against a running HTTP server.
|
||||
|
||||
Run: python3 student-tests/level4.py --base-url http://localhost:8080
|
||||
Creates only synthetic users, chats and messages.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, Failure, check, timestamp # noqa: E402
|
||||
from validation_edges import acceptance # noqa: E402
|
||||
|
||||
|
||||
def chat_for(client, members):
|
||||
return client.call(
|
||||
"POST", "/api/v1/chats", 201, actor=members[0],
|
||||
body={"title": "Проверка уровня 4", "member_ids": [x["id"] for x in members]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
|
||||
|
||||
def malformed_json(client):
|
||||
response = client.call(
|
||||
"POST", "/api/v1/users", 400,
|
||||
raw=b'{"username":', headers={"Content-Type": "application/json"},
|
||||
)
|
||||
check(response["json"]["error"]["code"] == "invalid_request", "wrong error for malformed JSON")
|
||||
|
||||
|
||||
def foreign_chat(client):
|
||||
owner, outsider = client.user("owner"), client.user("outsider")
|
||||
chat = chat_for(client, [owner])
|
||||
path = "/api/v1/chats/" + chat["id"]
|
||||
for method, suffix, body in (
|
||||
("GET", "", None),
|
||||
("GET", "/messages", None),
|
||||
("POST", "/messages", {"text": "synthetic"}),
|
||||
):
|
||||
result = client.call(method, path + suffix, 404, actor=outsider, body=body)
|
||||
check(result["json"]["error"]["code"] == "not_found", "foreign chat revealed")
|
||||
|
||||
|
||||
def empty_message(client):
|
||||
owner = client.user("empty")
|
||||
chat = chat_for(client, [owner])
|
||||
for value in ("", " \t\n "):
|
||||
result = client.call(
|
||||
"POST", "/api/v1/chats/" + chat["id"] + "/messages", 400,
|
||||
actor=owner, body={"text": value},
|
||||
)
|
||||
check(result["json"]["error"]["code"] == "invalid_request", "empty text accepted")
|
||||
|
||||
|
||||
def duplicate_username(client):
|
||||
owner = client.user("duplicate")
|
||||
result = client.call("POST", "/api/v1/users", 409, body=owner["registration"])
|
||||
check(result["json"]["error"]["code"] == "conflict", "duplicate username not rejected")
|
||||
|
||||
|
||||
def media_type(client):
|
||||
owner = client.user("media")
|
||||
chat = chat_for(client, [owner])
|
||||
requests = (
|
||||
("/api/v1/users", {"username": "media_probe", "display_name": "Probe"}, None),
|
||||
("/api/v1/chats", {"title": "Probe", "member_ids": [owner["id"]]}, owner),
|
||||
("/api/v1/chats/" + chat["id"] + "/messages", {"text": "synthetic"}, owner),
|
||||
)
|
||||
for path, body, actor in requests:
|
||||
response = client.call("POST", path, 415, actor=actor,
|
||||
raw=json.dumps(body).encode(), headers={"Content-Type": "text/plain"})
|
||||
check(response["json"]["error"]["code"] == "unsupported_media_type", "wrong 415 error code")
|
||||
|
||||
|
||||
def request_validation(client):
|
||||
owner = client.user("validation")
|
||||
chat = chat_for(client, [owner])
|
||||
cases = (
|
||||
("/api/v1/users", {"username": 123, "display_name": "Probe"}, None),
|
||||
("/api/v1/users", {"username": "validation_probe", "display_name": "Probe", "extra": True}, None),
|
||||
("/api/v1/chats", {"title": "Probe", "member_ids": [owner["id"], owner["id"]]}, owner),
|
||||
("/api/v1/chats", {"title": "Probe", "member_ids": []}, owner),
|
||||
("/api/v1/chats/" + chat["id"] + "/messages", {"text": 123}, owner),
|
||||
("/api/v1/chats/" + chat["id"] + "/messages", {"text": "synthetic", "sender_id": owner["id"]}, owner),
|
||||
)
|
||||
for path, body, actor in cases:
|
||||
response = client.call("POST", path, 400, actor=actor, body=body)
|
||||
check(response["json"]["error"]["code"] == "invalid_request", "wrong validation error code")
|
||||
|
||||
|
||||
def unknown_api_route(client):
|
||||
owner = client.user("route")
|
||||
response = client.call("GET", "/api/v1/does-not-exist", 404, actor=owner)
|
||||
check(response["json"]["error"]["code"] == "not_found", "wrong unknown-route error code")
|
||||
|
||||
|
||||
def pagination_parameters(client):
|
||||
owner = client.user("params")
|
||||
chat = chat_for(client, [owner])
|
||||
failures = []
|
||||
for path in ("/api/v1/chats", "/api/v1/chats/" + chat["id"] + "/messages"):
|
||||
for value in ("0", "101", "invalid", ""):
|
||||
try:
|
||||
response = client.call("GET", path + "?limit=" + value, 400, actor=owner)
|
||||
check(response["json"]["error"]["code"] == "invalid_request", "wrong limit error code")
|
||||
except Failure as exc:
|
||||
failures.append("limit=%r: %s" % (value, exc))
|
||||
client.call("GET", path + "?cursor=invalid", 400, actor=owner)
|
||||
check(not failures, "; ".join(failures))
|
||||
|
||||
|
||||
def cursor_binding(client):
|
||||
owner = client.user("cursor")
|
||||
first, second = chat_for(client, [owner]), chat_for(client, [owner])
|
||||
written = [client.message(owner, first, "cursor item %d" % i)["json"] for i in range(5)]
|
||||
path = "/api/v1/chats/" + first["id"] + "/messages"
|
||||
page = client.call("GET", path + "?limit=1", actor=owner, schema="MessagePage")["json"]
|
||||
cursor = quote(page["next_cursor"], safe="")
|
||||
client.call("GET", "/api/v1/chats/" + second["id"] + "/messages?cursor=" + cursor, 400, actor=owner)
|
||||
rest = client.call("GET", path + "?limit=100&cursor=" + cursor, actor=owner, schema="MessagePage")["json"]
|
||||
check(page["items"] + rest["items"] == written, "changing limit lost or duplicated messages")
|
||||
check(rest["next_cursor"] is None, "final cursor must be null")
|
||||
|
||||
|
||||
def chat_pagination(client):
|
||||
owner, outsider = client.user("chatpages"), client.user("chatother")
|
||||
expected = [chat_for(client, [owner]) for _ in range(7)]
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
path = "/api/v1/chats?limit=2"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", path, actor=owner, schema="ChatPage")["json"]
|
||||
seen.extend(page["items"])
|
||||
check(len(seen) <= 7, "chat pagination repeated items")
|
||||
next_cursor = page["next_cursor"]
|
||||
check(next_cursor is None or next_cursor != cursor, "chat cursor did not advance")
|
||||
if next_cursor is None:
|
||||
break
|
||||
client.call("GET", "/api/v1/chats?cursor=" + quote(next_cursor, safe=""), 400, actor=outsider)
|
||||
cursor = next_cursor
|
||||
check(seen == sorted(expected, key=lambda item: (timestamp(item["created_at"]), item["id"])),
|
||||
"chat pagination lost, repeated or reordered items")
|
||||
|
||||
|
||||
def unicode_boundaries(client):
|
||||
registration = {"username": "unicode_" + uuid.uuid4().hex[:12], "display_name": "😀" * 100}
|
||||
user = client.call("POST", "/api/v1/users", 201, body=registration, schema="User")["json"]
|
||||
check(user["display_name"] == registration["display_name"], "Unicode display name changed")
|
||||
client.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "unicode_" + uuid.uuid4().hex[:12], "display_name": "😀" * 101})
|
||||
actor = {"id": user["id"]}
|
||||
chat = client.call("POST", "/api/v1/chats", 201, actor=actor,
|
||||
body={"title": "😀" * 100, "member_ids": [user["id"]]}, schema="Chat")["json"]
|
||||
message = client.message(actor, chat, "😀" * 4000)["json"]
|
||||
check(message["text"] == "😀" * 4000, "Unicode text changed")
|
||||
client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400,
|
||||
actor=actor, body={"text": "😀" * 4001})
|
||||
|
||||
|
||||
def multiple_pages(client):
|
||||
owner = client.user("pages")
|
||||
chat = chat_for(client, [owner])
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
written = [client.message(owner, chat, "page item %d" % i)["json"] for i in range(7)]
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = path + "?limit=2"
|
||||
if cursor is not None:
|
||||
url += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", url, actor=owner, schema="MessagePage")["json"]
|
||||
check(0 < len(page["items"]) <= 2, "invalid page size")
|
||||
seen.extend(page["items"])
|
||||
next_cursor = page["next_cursor"]
|
||||
check(next_cursor is None or next_cursor != cursor, "cursor did not advance")
|
||||
check(len(seen) <= len(written), "pagination loop or duplicate")
|
||||
if next_cursor is None:
|
||||
break
|
||||
cursor = next_cursor
|
||||
ids = [item["id"] for item in seen]
|
||||
check(len(ids) == 7 and len(set(ids)) == 7, "pagination omitted or repeated messages")
|
||||
check(set(ids) == {item["id"] for item in written}, "pagination returned different messages")
|
||||
check(seen == sorted(seen, key=lambda item: (timestamp(item["created_at"]), item["id"])),
|
||||
"history is not ordered by (created_at, id)")
|
||||
|
||||
|
||||
def concurrent_messages(client):
|
||||
members = [client.user("race%d" % i) for i in range(10)]
|
||||
chat = chat_for(client, members)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def sender(index):
|
||||
local = Client(client.base)
|
||||
barrier.wait(timeout=10)
|
||||
return [local.message(members[index], chat, "race %d %d" % (index, j))["json"]
|
||||
for j in range(10)]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
groups = list(pool.map(sender, range(10)))
|
||||
written = [item for group in groups for item in group]
|
||||
check(len(written) == 100 and len({item["id"] for item in written}) == 100,
|
||||
"100 writes were not acknowledged with unique IDs")
|
||||
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = path + "?limit=37"
|
||||
if cursor is not None:
|
||||
url += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", url, actor=members[0], schema="MessagePage")["json"]
|
||||
seen.extend(page["items"])
|
||||
check(len(seen) <= 100, "history returned more than 100 messages")
|
||||
next_cursor = page["next_cursor"]
|
||||
check(next_cursor is None or next_cursor != cursor, "cursor did not advance")
|
||||
if next_cursor is None:
|
||||
break
|
||||
cursor = next_cursor
|
||||
|
||||
ids = [item["id"] for item in seen]
|
||||
check(len(ids) == 100 and len(set(ids)) == 100, "history does not contain 100 unique messages")
|
||||
check(set(ids) == {item["id"] for item in written}, "acknowledged messages missing from history")
|
||||
check({item["id"]: item for item in seen} == {item["id"]: item for item in written},
|
||||
"stored messages differ from acknowledged messages")
|
||||
check({item["sender_id"] for item in seen} == {member["id"] for member in members},
|
||||
"not all 10 clients contributed")
|
||||
print("RESULT: 10 clients x 10 writes; 100 acknowledged; 100 unique IDs in complete history")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
failures = []
|
||||
scenarios = (
|
||||
("malformed JSON", malformed_json),
|
||||
("foreign chat", foreign_chat),
|
||||
("empty message", empty_message),
|
||||
("duplicate username", duplicate_username),
|
||||
("multiple pages", multiple_pages),
|
||||
("100 concurrent messages", concurrent_messages),
|
||||
("unsupported media type", media_type),
|
||||
("request validation", request_validation),
|
||||
("unknown API route", unknown_api_route),
|
||||
("pagination parameters", pagination_parameters),
|
||||
("cursor binding and changed limit", cursor_binding),
|
||||
("chat pagination", chat_pagination),
|
||||
("Unicode code-point boundaries", unicode_boundaries),
|
||||
("exact JSON field names", lambda c: acceptance(c, "key_case")),
|
||||
("strict UTF-8 and valid Unicode", lambda c: acceptance(c, "utf8")),
|
||||
("JSON required fields/types/document", lambda c: acceptance(c, "shape")),
|
||||
("additional contract boundaries", lambda c: acceptance(c, "boundaries")),
|
||||
)
|
||||
for name, scenario in scenarios:
|
||||
try:
|
||||
scenario(client)
|
||||
print("PASS:", name)
|
||||
except (Failure, OSError, ValueError) as exc:
|
||||
failures.append(name)
|
||||
print("FAIL: %s: %s" % (name, exc))
|
||||
print("SUMMARY: %d/%d passed" % (len(scenarios) - len(failures), len(scenarios)))
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,358 @@
|
||||
#!/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 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
|
||||
|
||||
|
||||
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 len(ids) != 1:
|
||||
raise CheckFailure("Expected one existing container for " + service)
|
||||
raw = json.loads(command(["docker", "inspect", ids[0]], env=env))[0]
|
||||
if raw["Config"]["Labels"].get("com.docker.compose.project") != env["COMPOSE_PROJECT_NAME"]:
|
||||
raise CheckFailure("Container belongs to another Compose project")
|
||||
result[service] = {
|
||||
"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"),
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def validate_transition(action, before, after):
|
||||
if not before or set(before) != set(after):
|
||||
raise CheckFailure("Missing lifecycle evidence")
|
||||
for service, old in before.items():
|
||||
new = after[service]
|
||||
if old["id"] != new["id"] or old["volumes"] != new["volumes"]:
|
||||
raise CheckFailure("Lifecycle action recreated a container or changed volumes")
|
||||
if action in ("stop-db", "stop-cache"):
|
||||
if not old["running"] or new["running"]:
|
||||
raise CheckFailure("Database was not actually stopped")
|
||||
else:
|
||||
if not new["running"] or old["started_at"] == new["started_at"]:
|
||||
raise CheckFailure("Service was not actually started/restarted: " + service)
|
||||
|
||||
|
||||
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
|
||||
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)
|
||||
validate_transition(action, before, after)
|
||||
evidence = env.get("HL_LIFECYCLE_EVIDENCE")
|
||||
if evidence:
|
||||
path = Path(evidence)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("a") as output:
|
||||
output.write(json.dumps({"action": action, "project": env["COMPOSE_PROJECT_NAME"],
|
||||
"before": before, "after": after}) + "\n")
|
||||
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):
|
||||
if 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 = "lab2-test-" + secrets.token_hex(6)
|
||||
results = []
|
||||
summary = {"project": project, "status": "FAIL", "results": results}
|
||||
with tempfile.TemporaryDirectory(prefix=project + "-") as directory:
|
||||
tmp = Path(directory)
|
||||
api_port, pg_port = free_ports()
|
||||
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"]
|
||||
env["AUTH_TEST_BASE_URL"] = env["BASE_URL"]
|
||||
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
|
||||
override.write_text(f'''services:
|
||||
api:
|
||||
image: {project}-api:check
|
||||
env_file: !override
|
||||
- {q(str(tmp / '.env'))}
|
||||
ports: !override
|
||||
- "127.0.0.1:{api_port}:8080"
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
SESSION_TTL_SECONDS: "{ttl}"
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
migrate:
|
||||
image: {project}-migrate:check
|
||||
postgres:
|
||||
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'))}
|
||||
''')
|
||||
if redis_port is not None:
|
||||
text = override.read_text().replace("secrets:\n database_url:", f''' redis:
|
||||
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)
|
||||
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):
|
||||
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"
|
||||
|
||||
def stage(name, args, timeout=180, parse_go=False, required=True):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
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")
|
||||
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 (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:
|
||||
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"])
|
||||
stage("compose-up", base + ["up", "-d", "--build", "--pull", pull, "--wait", "--wait-timeout", "90"], 300)
|
||||
wait_ready(env["BASE_URL"])
|
||||
stage("go-race", ["go", "test", "-race", "./...", "-count=1", "-json"], parse_go=True, timeout=300, 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["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)
|
||||
stage("auth-persistence", auth + ["--suite", "persistence", "--restart-hook", str(ROOT / "scripts/restart.sh")], required=False)
|
||||
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["BASE_URL"], "--suite", "expiry", "--ttl", "2"], required=False)
|
||||
summary["status"] = "FAIL" if any(x["status"] == "FAIL" for x in results) else "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("--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.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)
|
||||
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,71 @@
|
||||
import copy
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
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_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,465 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 1, track 1: isolated matrix, integrity checks and paired comparison.
|
||||
|
||||
Requires Python 3.9+, Docker, Go 1.27.1+. Standard libraries only; macOS/Linux.
|
||||
Does not edit the application or perform Git mutations.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GENERATOR = ROOT / "student-tests/track1_load.go"
|
||||
|
||||
|
||||
def command(args, timeout=60, required=True, **kwargs):
|
||||
result = subprocess.run(args, cwd=ROOT, capture_output=True, text=True,
|
||||
timeout=timeout, **kwargs)
|
||||
if required and result.returncode:
|
||||
raise RuntimeError("command failed: %s (exit %d)" % (args[0], result.returncode))
|
||||
return result
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return command(["docker", *args]).stdout.strip()
|
||||
|
||||
|
||||
def inspect(name):
|
||||
return json.loads(docker("inspect", name))[0]
|
||||
|
||||
|
||||
def digest(paths):
|
||||
h = hashlib.sha256()
|
||||
for path in sorted(paths):
|
||||
h.update(str(path.relative_to(ROOT)).encode() + b"\0" + path.read_bytes() + b"\0")
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def save(path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(path.suffix + ".tmp")
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def numbers(value):
|
||||
result = [int(x) for x in value.split(",")]
|
||||
if len(set(result)) != len(result) or any(x <= 0 for x in result):
|
||||
raise argparse.ArgumentTypeError("expected distinct positive integers")
|
||||
return result
|
||||
|
||||
|
||||
def compile_generator(directory):
|
||||
target = Path(directory) / "track1-load"
|
||||
environment = dict(os.environ, GOCACHE=str(Path(directory) / "go-cache"))
|
||||
result = command(["go", "build", "-o", str(target), str(GENERATOR)],
|
||||
timeout=180, required=False, env=environment)
|
||||
if result.returncode:
|
||||
raise RuntimeError("generator compilation failed: " + result.stderr.strip())
|
||||
return target
|
||||
|
||||
|
||||
def build_image(args, output):
|
||||
if not args.build:
|
||||
return {"performed": False, "source_image_mapping": "unverified: existing image"}
|
||||
with tempfile.TemporaryDirectory(prefix="highload-track1-context-") as directory:
|
||||
for relative in filter(None, command(["git", "ls-files", "-z"]).stdout.split("\0")):
|
||||
source = ROOT / relative
|
||||
if source.is_file():
|
||||
target = Path(directory) / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, target)
|
||||
result = command(["docker", "build", "--progress=plain", "-t", args.image, directory],
|
||||
timeout=300, required=False)
|
||||
log = output.with_name(output.stem + "-build.txt")
|
||||
log.write_text(result.stdout + result.stderr)
|
||||
if result.returncode:
|
||||
raise RuntimeError("application Docker build failed; see " + str(log))
|
||||
return {"performed": True, "exit_code": result.returncode, "log": str(log.relative_to(ROOT))
|
||||
if log.is_relative_to(ROOT) else str(log),
|
||||
"context": "current tracked working files; not a committed clone"}
|
||||
|
||||
|
||||
def start_container(image, args):
|
||||
name = "highload-track1-" + uuid.uuid4().hex[:12]
|
||||
try:
|
||||
docker("run", "-d", "--name", name, "--cpus=" + str(args.cpus),
|
||||
"--memory=" + str(args.memory_mib) + "m",
|
||||
"--memory-swap=" + str(args.memory_mib) + "m",
|
||||
"--log-opt", "max-size=10m", "--log-opt", "max-file=1",
|
||||
"-p", "127.0.0.1::8080", "-e", "APP_HOST=0.0.0.0",
|
||||
"-e", "APP_PORT=8080", image)
|
||||
port = inspect(name)["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"]
|
||||
base = "http://127.0.0.1:" + port
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/health/ready", timeout=1) as response:
|
||||
if response.status == 200:
|
||||
return name, base
|
||||
except (urllib.error.URLError, OSError):
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("API did not become ready")
|
||||
except BaseException:
|
||||
command(["docker", "rm", "--force", name], required=False)
|
||||
raise
|
||||
|
||||
|
||||
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 = command(["docker", "exec", self.name, "awk",
|
||||
'FNR == 1 {print "FILE " FILENAME} {print}', *self.files],
|
||||
timeout=4, required=False)
|
||||
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."}
|
||||
|
||||
|
||||
def invoke(binary, name, base, args, history=203, concurrency=10, workload="read", mode="load"):
|
||||
invocation = [str(binary), "-base-url", base, "-mode", mode,
|
||||
"-history", str(history), "-concurrency", str(concurrency),
|
||||
"-duration", str(args.duration), "-warmup", str(args.warmup),
|
||||
"-timeout", str(args.timeout), "-page-size", str(args.page_size),
|
||||
"-payload-bytes", str(args.payload_bytes), "-workload", workload]
|
||||
child = subprocess.Popen(invocation, cwd=ROOT, text=True, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
sampler, measurement_start, metrics, resources = None, None, None, None
|
||||
failure = None
|
||||
# Generators should not hang in setup or verification; no shell process is spawned.
|
||||
timer = threading.Timer(max(120, history * args.timeout / 10 + args.duration + args.warmup + 30), child.kill)
|
||||
timer.start()
|
||||
try:
|
||||
for line in child.stdout:
|
||||
event = json.loads(line)
|
||||
kind = event["event"]
|
||||
if kind == "measurement_start":
|
||||
measurement_start = time.monotonic()
|
||||
sampler = Sampler(name, args.sample_interval)
|
||||
sampler.thread.start()
|
||||
elif kind == "measurement_complete":
|
||||
resources = sampler.finish(measurement_start, time.monotonic(), args.cpus)
|
||||
elif kind == "result":
|
||||
metrics = event["data"]
|
||||
elif kind == "failure":
|
||||
failure = event["data"]["reason"]
|
||||
code = child.wait(timeout=10)
|
||||
if code or metrics is None:
|
||||
raise RuntimeError(failure or "generator failed (exit %d)" % code)
|
||||
if mode == "load" and resources is None:
|
||||
raise RuntimeError("generator omitted resource measurement phase")
|
||||
return {"generator": metrics, "resources": resources, "exit_code": code}
|
||||
finally:
|
||||
timer.cancel()
|
||||
if child.poll() is None:
|
||||
child.kill()
|
||||
child.wait()
|
||||
if sampler:
|
||||
sampler.stop_event.set()
|
||||
sampler.thread.join(timeout=5)
|
||||
child.stdout.close()
|
||||
child.stderr.close()
|
||||
|
||||
|
||||
def preflight(binary, image, args):
|
||||
name, base = start_container(image, args)
|
||||
try:
|
||||
results = []
|
||||
for invocation in (["make", "check"], ["make", "test", "BASE_URL=" + base],
|
||||
[sys.executable, "student-tests/level4.py", "--base-url", base]):
|
||||
result = command(invocation, required=False)
|
||||
results.append({"command": " ".join(invocation), "exit_code": result.returncode,
|
||||
"output": (result.stdout + result.stderr).strip()})
|
||||
if result.returncode:
|
||||
raise RuntimeError("preflight failed: " + invocation[0])
|
||||
return {"status": "PASS", "contract_checks": results,
|
||||
"track1_correctness": invoke(binary, name, base, args, mode="check")}
|
||||
finally:
|
||||
command(["docker", "rm", "--force", name], required=False)
|
||||
|
||||
|
||||
def write_csv(output, cases):
|
||||
path = output.with_suffix(".csv")
|
||||
fields = ["workload", "history", "concurrency", "repeat", "status", "read_rps",
|
||||
"read_p50_ms", "read_p95_ms", "read_p99_ms", "write_rps", "write_p95_ms",
|
||||
"errors", "rss_peak_mib", "cpu_percent_of_limit", "client_cpu_cores"]
|
||||
with path.open("w", newline="") as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=fields)
|
||||
writer.writeheader()
|
||||
for case in cases:
|
||||
row = {k: case.get(k) for k in fields[:5]}
|
||||
if case.get("result"):
|
||||
result = case["result"]
|
||||
metrics = result["generator"]["metrics"]
|
||||
read, write, resources = metrics["read"], metrics["write"], result["resources"]
|
||||
row.update(read_rps=read["successful_rps"], write_rps=write["successful_rps"],
|
||||
write_p95_ms=write["successful_latency_ms"]["p95"],
|
||||
errors=read["failed_requests"] + write["failed_requests"],
|
||||
rss_peak_mib=resources["rss_peak_observed_bytes"] / 1048576,
|
||||
cpu_percent_of_limit=resources["mean_cpu_percent_of_limit"],
|
||||
client_cpu_cores=metrics["client_cpu_cores"])
|
||||
for p in ("p50", "p95", "p99"):
|
||||
row["read_" + p + "_ms"] = read["successful_latency_ms"][p]
|
||||
writer.writerow(row)
|
||||
|
||||
|
||||
def run_experiment(args):
|
||||
output = (ROOT / args.output).resolve()
|
||||
if output.exists():
|
||||
raise RuntimeError("output already exists; choose a new path to preserve earlier measurements")
|
||||
if args.command == "run" and (len(args.histories) < 3 or len(args.concurrency) < 3):
|
||||
raise RuntimeError("track 1 requires at least three history sizes and three concurrency levels")
|
||||
if any(h < 2 * args.page_size for h in args.histories) or args.duration < max(2, args.sample_interval * 4):
|
||||
raise RuntimeError("history must fit two full pages; duration must allow at least four samples")
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
paths = [ROOT / p for p in ("Dockerfile", ".dockerignore", "go.mod", "go.sum")]
|
||||
paths += list((ROOT / "cmd").rglob("*.go")) + list((ROOT / "internal").rglob("*.go"))
|
||||
environment = {"system": platform.system(), "architecture": platform.machine(), "logical_cpus": os.cpu_count()}
|
||||
if platform.system() == "Darwin":
|
||||
hardware = command(["sysctl", "-n", "machdep.cpu.brand_string", "hw.memsize"]).stdout.splitlines()
|
||||
environment.update(cpu=hardware[0], memory_bytes=int(hardware[1]))
|
||||
info = json.loads(docker("info", "--format", "{{json .}}"))
|
||||
if str(info.get("CgroupVersion")) != "2":
|
||||
raise RuntimeError("resource collector currently requires Linux cgroup v2")
|
||||
report = {"schema": 1, "status": "RUNNING", "label": args.label,
|
||||
"started_at_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
"invocation": ["python3", "student-tests/track1.py", *sys.argv[1:]],
|
||||
"git_head": command(["git", "rev-parse", "HEAD"]).stdout.strip(),
|
||||
"uncommitted_working_files": bool(command(["git", "status", "--porcelain"]).stdout),
|
||||
"working_source_sha256": digest(paths),
|
||||
"generator_sha256": digest([GENERATOR, Path(__file__).resolve()]),
|
||||
"host": environment,
|
||||
"docker": {k: info.get(k) for k in ("ServerVersion", "Architecture", "NCPU", "MemTotal", "CgroupVersion")},
|
||||
"limits": {"cpus": args.cpus, "memory_bytes": args.memory_mib * 1048576,
|
||||
"memory_swap_bytes": args.memory_mib * 1048576},
|
||||
"method": {"histories": args.histories, "concurrency": args.concurrency,
|
||||
"workloads": args.workloads, "duration_seconds": args.duration,
|
||||
"warmup_seconds": args.warmup, "repeats": args.repeats,
|
||||
"page_size": args.page_size, "payload_bytes": args.payload_bytes,
|
||||
"timeout_seconds": args.timeout, "sample_interval_seconds": args.sample_interval,
|
||||
"seed_clients": 10, "read_pages": "first, middle, last full page; round robin",
|
||||
"fresh_container_per_case": True, "order": "repeat, history, concurrency, workload"},
|
||||
"cases": [], "limitations": ["PASS validates the experiment and data integrity, not grade 5 or improvement.",
|
||||
"Closed-loop generator has coordinated omission; successes and errors are separate.",
|
||||
"Generator and API share one host; Docker sampling consumes a small part of container CPU.",
|
||||
"RSS is process residency, not heap size. Sampled peaks can miss short spikes."]}
|
||||
save(output, report)
|
||||
try:
|
||||
print("BUILD: application image and standalone generator", flush=True)
|
||||
report["build"] = build_image(args, output)
|
||||
image = json.loads(docker("image", "inspect", args.image))[0]
|
||||
report["image"] = {"tag": args.image, "id": image["Id"]}
|
||||
with tempfile.TemporaryDirectory(prefix="highload-track1-generator-") as directory:
|
||||
binary = compile_generator(directory)
|
||||
report["go_version"] = command(["go", "version"]).stdout.strip()
|
||||
print("PREFLIGHT: public API, level 4 HTTP checks, track 1 integrity", flush=True)
|
||||
report["preflight"] = preflight(binary, image["Id"], args)
|
||||
save(output, report)
|
||||
if args.command == "run":
|
||||
profiles = list(itertools.product(range(1, args.repeats + 1), args.histories,
|
||||
args.concurrency, args.workloads))
|
||||
for index, (repeat, history, concurrency, workload) in enumerate(profiles, 1):
|
||||
case = {"repeat": repeat, "history": history, "concurrency": concurrency,
|
||||
"workload": workload, "status": "RUNNING"}
|
||||
report["cases"].append(case)
|
||||
print("CASE %d/%d: %s, N=%d, C=%d, repeat=%d" %
|
||||
(index, len(profiles), workload, history, concurrency, repeat), flush=True)
|
||||
name = None
|
||||
try:
|
||||
name, base = start_container(image["Id"], args)
|
||||
case["result"] = invoke(binary, name, base, args, history, concurrency, workload)
|
||||
state = inspect(name)["State"]
|
||||
case["container_state"] = {k: state[k] for k in ("Running", "OOMKilled", "ExitCode")}
|
||||
if not state["Running"] or state["OOMKilled"] or case["result"]["resources"]["oom_kill_count"]:
|
||||
raise RuntimeError("container stopped or OOM occurred")
|
||||
case["status"] = "PASS"
|
||||
metrics = case["result"]["generator"]["metrics"]["read"]
|
||||
print(" PASS: %.1f read RPS, p95=%s ms, p99=%s ms, RSS=%.1f MiB, errors=%d" %
|
||||
(metrics["successful_rps"], metrics["successful_latency_ms"]["p95"],
|
||||
metrics["successful_latency_ms"]["p99"],
|
||||
case["result"]["resources"]["rss_peak_observed_bytes"] / 1048576,
|
||||
metrics["failed_requests"]), flush=True)
|
||||
except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
case.update(status="FAIL", reason=str(exc))
|
||||
if name:
|
||||
state = inspect(name)["State"]
|
||||
case["container_state"] = {k: state[k] for k in ("Running", "OOMKilled", "ExitCode")}
|
||||
print(" FAIL: " + str(exc), flush=True)
|
||||
finally:
|
||||
if name:
|
||||
command(["docker", "rm", "--force", name], required=False)
|
||||
save(output, report)
|
||||
write_csv(output, report["cases"])
|
||||
report["status"] = "PASS" if all(c["status"] == "PASS" for c in report["cases"]) else "FAIL"
|
||||
except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
report.update(status="FAIL", reason=str(exc))
|
||||
print("FAIL: " + str(exc), flush=True)
|
||||
finally:
|
||||
report["finished_at_utc"] = dt.datetime.now(dt.timezone.utc).isoformat()
|
||||
save(output, report)
|
||||
write_csv(output, report["cases"])
|
||||
print("SUMMARY: %s; %s" % (report["status"], args.output), flush=True)
|
||||
return 0 if report["status"] == "PASS" else 1
|
||||
|
||||
|
||||
def compare(args):
|
||||
before, after = [json.loads((ROOT / p).read_text()) for p in (args.before, args.after)]
|
||||
for report in (before, after):
|
||||
if report["status"] != "PASS" or not report["cases"]:
|
||||
raise RuntimeError("comparison requires two complete PASS matrices")
|
||||
for field in ("schema", "method", "limits", "host", "docker", "generator_sha256", "go_version"):
|
||||
if before[field] != after[field]:
|
||||
raise RuntimeError("incomparable experiments: different " + field)
|
||||
if before["image"]["id"] == after["image"]["id"]:
|
||||
raise RuntimeError("before and after use the same image; no application change demonstrated")
|
||||
def group(report):
|
||||
groups = {}
|
||||
for case in report["cases"]:
|
||||
key = (case["workload"], case["history"], case["concurrency"])
|
||||
groups.setdefault(key, []).append(case)
|
||||
return groups
|
||||
a, b = group(before), group(after)
|
||||
if set(a) != set(b):
|
||||
raise RuntimeError("different matrix profiles")
|
||||
rows = []
|
||||
print("workload N C | read RPS before -> after | p95 ms before -> after | RSS MiB before -> after")
|
||||
for key in sorted(a):
|
||||
def aggregate(cases):
|
||||
values = {"read_rps": [], "read_p95_ms": [], "read_p99_ms": [], "rss_peak_mib": [], "errors": []}
|
||||
for case in cases:
|
||||
result = case["result"]
|
||||
read, write = (result["generator"]["metrics"][op] for op in ("read", "write"))
|
||||
values["read_rps"].append(read["successful_rps"])
|
||||
values["read_p95_ms"].append(read["successful_latency_ms"]["p95"])
|
||||
values["read_p99_ms"].append(read["successful_latency_ms"]["p99"])
|
||||
values["rss_peak_mib"].append(result["resources"]["rss_peak_observed_bytes"] / 1048576)
|
||||
values["errors"].append(read["failed_requests"] + write["failed_requests"])
|
||||
if any(v is None for series in values.values() for v in series):
|
||||
raise RuntimeError("a profile has no successful reads")
|
||||
return {name: {"median": statistics.median(series), "min": min(series), "max": max(series)}
|
||||
for name, series in values.items()}
|
||||
first, second = aggregate(a[key]), aggregate(b[key])
|
||||
row = {"workload": key[0], "history": key[1], "concurrency": key[2], "before": first, "after": second}
|
||||
row["read_rps_ratio"] = second["read_rps"]["median"] / first["read_rps"]["median"]
|
||||
rows.append(row)
|
||||
print("%s %d %d | %.1f -> %.1f | %.3f -> %.3f | %.1f -> %.1f" %
|
||||
(*key, first["read_rps"]["median"], second["read_rps"]["median"],
|
||||
first["read_p95_ms"]["median"], second["read_p95_ms"]["median"],
|
||||
first["rss_peak_mib"]["median"], second["rss_peak_mib"]["median"]))
|
||||
output = (ROOT / args.output).resolve()
|
||||
if output.exists():
|
||||
raise RuntimeError("comparison output already exists; choose a new path")
|
||||
save(output, {"schema": 1, "before": args.before, "after": args.after,
|
||||
"before_image": before["image"], "after_image": after["image"], "rows": rows,
|
||||
"note": "Medians and min/max across repetitions; latency percentiles cover successful requests. A ratio is not proof of causality or a universal passing RPS."})
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
for name in ("run", "check"):
|
||||
p = sub.add_parser(name)
|
||||
p.add_argument("--build", action="store_true")
|
||||
p.add_argument("--image", required=True)
|
||||
p.add_argument("--label", default="before")
|
||||
p.add_argument("--output", required=True)
|
||||
p.add_argument("--histories", type=numbers, default=[100, 1000, 10000])
|
||||
p.add_argument("--concurrency", type=numbers, default=[1, 5, 10])
|
||||
p.add_argument("--workloads", default="read", type=lambda s: s.split(","), choices=None)
|
||||
p.add_argument("--duration", type=float, default=30)
|
||||
p.add_argument("--warmup", type=float, default=5)
|
||||
p.add_argument("--repeats", type=int, default=3)
|
||||
p.add_argument("--cpus", type=float, default=1)
|
||||
p.add_argument("--memory-mib", type=int, default=128)
|
||||
p.add_argument("--page-size", type=int, default=50)
|
||||
p.add_argument("--payload-bytes", type=int, default=128)
|
||||
p.add_argument("--timeout", type=float, default=5)
|
||||
p.add_argument("--sample-interval", type=float, default=0.5)
|
||||
p = sub.add_parser("compare")
|
||||
p.add_argument("--before", required=True)
|
||||
p.add_argument("--after", required=True)
|
||||
p.add_argument("--output", required=True)
|
||||
args = parser.parse_args()
|
||||
if args.command != "compare":
|
||||
if args.repeats < 1 or args.cpus <= 0 or args.memory_mib < 32 or args.warmup < 0 or args.timeout <= 0 or args.sample_interval < 0.1 or not 1 <= args.page_size <= 100 or not 32 <= args.payload_bytes <= 4000 or any(c > 256 for c in args.concurrency) or not args.workloads or set(args.workloads) - {"read", "mixed"} or len(args.workloads) != len(set(args.workloads)):
|
||||
parser.error("invalid limits, durations or workload parameters")
|
||||
try:
|
||||
return compare(args) if args.command == "compare" else run_experiment(args)
|
||||
except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
print("FAIL: " + str(exc), flush=True)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeat the sorting baseline with the current Go/JSON code and test harness.
|
||||
|
||||
Creates a temporary local clone, overlays the current tracked files and the
|
||||
validation tests, and replaces only the message repository with the saved
|
||||
pre-optimization version. The original checkout is not modified.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
REPOSITORY = "internal/database/repository/message.go"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--ref", default="9de1152204e649c733d442255467dd81e1f16c59")
|
||||
parser.add_argument("--image", required=True)
|
||||
parser.add_argument("--output", required=True)
|
||||
args = parser.parse_args()
|
||||
output = Path(args.output)
|
||||
if output.is_absolute() or output.parent != Path("evidence") or output.suffix != ".json":
|
||||
parser.error("--output must be evidence/<name>.json")
|
||||
if (ROOT / output).exists():
|
||||
parser.error("output already exists; choose a new filename")
|
||||
baseline = subprocess.check_output(["git", "show", args.ref + ":" + REPOSITORY], cwd=ROOT)
|
||||
paths = subprocess.check_output(["git", "ls-files", "-z"], cwd=ROOT).decode().split("\0")
|
||||
# Include the new HTTP tests before the author commits them.
|
||||
paths.append("student-tests/validation_edges.py")
|
||||
with tempfile.TemporaryDirectory(prefix="highload-track1-baseline-") as directory:
|
||||
checkout = Path(directory) / "source"
|
||||
subprocess.run(["git", "clone", "--quiet", "--local", "--no-hardlinks", str(ROOT), str(checkout)], check=True)
|
||||
for relative in filter(None, paths):
|
||||
source = ROOT / relative
|
||||
if source.is_file():
|
||||
target = checkout / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, target)
|
||||
(checkout / REPOSITORY).write_bytes(baseline)
|
||||
invocation = [sys.executable, "student-tests/track1.py", "run", "--build",
|
||||
"--image", args.image, "--label", "before-go127",
|
||||
"--histories", "100,1000,10000", "--concurrency", "1,5,10",
|
||||
"--duration", "10", "--warmup", "2", "--repeats", "1", "--output", str(output)]
|
||||
result = subprocess.run(invocation, cwd=checkout)
|
||||
for generated in (checkout / "evidence").glob(output.stem + "*"):
|
||||
if generated.is_file():
|
||||
shutil.copy2(generated, ROOT / "evidence" / generated.name)
|
||||
if (ROOT / output).exists():
|
||||
data = json.loads((ROOT / output).read_text())
|
||||
data["baseline_preparation"] = {
|
||||
"command": [sys.executable, *sys.argv], "repository_ref": args.ref,
|
||||
"replaced_file": REPOSITORY,
|
||||
"method": "Current working files, Go 1.27.1 and JSON v2; only the message repository restored from ref in a temporary clone",
|
||||
"source_file_sha256": hashlib.sha256(baseline).hexdigest(),
|
||||
}
|
||||
(ROOT / output).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
|
||||
return result.returncode
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,643 @@
|
||||
// Standalone black-box lab-1 generator. No application packages are imported.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json/v2"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
type page struct {
|
||||
Items []message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
type requestError struct {
|
||||
Kind string
|
||||
Status int
|
||||
}
|
||||
|
||||
func (e *requestError) Error() string { return fmt.Sprintf("%s (HTTP %d)", e.Kind, e.Status) }
|
||||
|
||||
type api struct {
|
||||
base string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// Entire response is consumed; transport reuses connections. No retries or redirects.
|
||||
func (a *api) call(method, path, actor string, body any, want int, out any) error {
|
||||
var input io.Reader
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
input = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequest(method, a.base+path, input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if actor != "" {
|
||||
req.Header.Set("X-User-Id", actor)
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
resp, err := a.client.Do(req)
|
||||
if err != nil {
|
||||
return &requestError{Kind: "transport_or_timeout"}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024+1))
|
||||
if err != nil {
|
||||
return &requestError{Kind: "transport_or_timeout"}
|
||||
}
|
||||
if len(b) > 2*1024*1024 {
|
||||
return &requestError{Kind: "protocol", Status: resp.StatusCode}
|
||||
}
|
||||
media, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if resp.Header.Get("X-Request-Id") == "" || err != nil || media != "application/json" {
|
||||
return &requestError{Kind: "protocol", Status: resp.StatusCode}
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
var e struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(b, &e) != nil || e.Error.Code == "" || e.Error.Message == "" || e.Error.RequestID != resp.Header.Get("X-Request-Id") {
|
||||
return &requestError{Kind: "protocol", Status: resp.StatusCode}
|
||||
}
|
||||
}
|
||||
if resp.StatusCode != want {
|
||||
return &requestError{Kind: "http_status", Status: resp.StatusCode}
|
||||
}
|
||||
if out != nil {
|
||||
if json.Unmarshal(b, out, json.RejectUnknownMembers(true)) != nil {
|
||||
return &requestError{Kind: "protocol", Status: resp.StatusCode}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func stamp(m message) (time.Time, error) {
|
||||
if !strings.HasSuffix(m.CreatedAt, "Z") {
|
||||
return time.Time{}, fmt.Errorf("non-UTC timestamp")
|
||||
}
|
||||
return time.Parse(time.RFC3339Nano, m.CreatedAt)
|
||||
}
|
||||
func less(a, b message) bool {
|
||||
x, _ := stamp(a)
|
||||
y, _ := stamp(b)
|
||||
return x.Before(y) || (x.Equal(y) && a.ID < b.ID)
|
||||
}
|
||||
func valid(m message, chat string) error {
|
||||
_, err := stamp(m)
|
||||
if err != nil || len(m.ID) != 36 || m.ChatID != chat || len(m.SenderID) != 36 || m.Text == "" {
|
||||
return fmt.Errorf("invalid Message")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func newUser(a *api, label string) (string, error) {
|
||||
b := make([]byte, 6)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var user struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
err := a.call("POST", "/api/v1/users", "", map[string]any{"username": "t1_" + label + "_" + hex.EncodeToString(b), "display_name": "Synthetic track 1"}, 201, &user)
|
||||
if err == nil && len(user.ID) != 36 {
|
||||
err = fmt.Errorf("invalid User ID")
|
||||
}
|
||||
return user.ID, err
|
||||
}
|
||||
func newChat(a *api, users []string) (string, error) {
|
||||
var chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
err := a.call("POST", "/api/v1/chats", users[0], map[string]any{"title": "Synthetic track 1", "member_ids": users}, 201, &chat)
|
||||
if err == nil && len(chat.ID) != 36 {
|
||||
err = fmt.Errorf("invalid Chat ID")
|
||||
}
|
||||
return chat.ID, err
|
||||
}
|
||||
func post(a *api, actor, chat, text string) (message, error) {
|
||||
var m message
|
||||
err := a.call("POST", "/api/v1/chats/"+chat+"/messages", actor, map[string]string{"text": text}, 201, &m)
|
||||
if err == nil {
|
||||
err = valid(m, chat)
|
||||
}
|
||||
if err == nil && (m.Text != text || m.SenderID != actor) {
|
||||
err = fmt.Errorf("POST changed text or sender")
|
||||
}
|
||||
return m, err
|
||||
}
|
||||
func read(a *api, actor, path string, limit int) (page, error) {
|
||||
var p page
|
||||
err := a.call("GET", path, actor, nil, 200, &p)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
if p.Items == nil || len(p.Items) > limit || (p.NextCursor != nil && (*p.NextCursor == "" || len(p.Items) != limit)) {
|
||||
return p, fmt.Errorf("invalid page or cursor")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
func pathFor(chat string, limit int, cursor string) string {
|
||||
p := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chat, limit)
|
||||
if cursor != "" {
|
||||
p += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Uses the opaque server cursor, exact nanosecond timestamps and full Message equality.
|
||||
func walk(a *api, actor, chat string, limit, bound int) ([]message, map[int]string, error) {
|
||||
all := make([]message, 0)
|
||||
seen := map[string]bool{}
|
||||
cursors := map[int]string{0: ""}
|
||||
cursor := ""
|
||||
for {
|
||||
p, err := read(a, actor, pathFor(chat, limit, cursor), limit)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, m := range p.Items {
|
||||
if err := valid(m, chat); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if seen[m.ID] || (len(all) > 0 && !less(all[len(all)-1], m)) {
|
||||
return nil, nil, fmt.Errorf("duplicate or unordered history")
|
||||
}
|
||||
seen[m.ID] = true
|
||||
all = append(all, m)
|
||||
if len(all) > bound {
|
||||
return nil, nil, fmt.Errorf("history exceeded safety bound")
|
||||
}
|
||||
}
|
||||
if p.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
if *p.NextCursor == cursor {
|
||||
return nil, nil, fmt.Errorf("cursor did not advance")
|
||||
}
|
||||
cursor = *p.NextCursor
|
||||
cursors[len(all)] = cursor
|
||||
}
|
||||
return all, cursors, nil
|
||||
}
|
||||
func sameHistory(all []message, expected map[string]message, allowExtras bool) (int, error) {
|
||||
for _, m := range all {
|
||||
old, ok := expected[m.ID]
|
||||
if ok && old != m {
|
||||
return 0, fmt.Errorf("acknowledged Message changed")
|
||||
}
|
||||
if !ok && !allowExtras {
|
||||
return 0, fmt.Errorf("unexpected Message")
|
||||
}
|
||||
}
|
||||
if len(all) < len(expected) {
|
||||
return 0, fmt.Errorf("acknowledged messages missing")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, m := range all {
|
||||
seen[m.ID] = true
|
||||
}
|
||||
for id := range expected {
|
||||
if !seen[id] {
|
||||
return 0, fmt.Errorf("acknowledged messages missing")
|
||||
}
|
||||
}
|
||||
return len(all) - len(expected), nil
|
||||
}
|
||||
func payload(index int64, size int) string {
|
||||
prefix := fmt.Sprintf("synthetic-%012d-", index)
|
||||
return prefix + strings.Repeat("x", size-len(prefix))
|
||||
}
|
||||
func seed(a *api, users []string, chat string, count, size int) (map[string]message, error) {
|
||||
var next atomic.Int64
|
||||
var mu sync.Mutex
|
||||
expected := map[string]message{}
|
||||
errs := make(chan error, len(users))
|
||||
var wg sync.WaitGroup
|
||||
for _, actor := range users {
|
||||
wg.Add(1)
|
||||
go func(actor string) {
|
||||
defer wg.Done()
|
||||
for {
|
||||
i := int(next.Add(1)) - 1
|
||||
if i >= count {
|
||||
return
|
||||
}
|
||||
m, err := post(a, actor, chat, payload(int64(i), size))
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
if _, exists := expected[m.ID]; exists {
|
||||
mu.Unlock()
|
||||
errs <- fmt.Errorf("duplicate POST ID")
|
||||
return
|
||||
}
|
||||
expected[m.ID] = m
|
||||
mu.Unlock()
|
||||
}
|
||||
}(actor)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
return nil, err
|
||||
}
|
||||
return expected, nil
|
||||
}
|
||||
func event(name string, data any) {
|
||||
if json.MarshalWrite(os.Stdout, map[string]any{"event": name, "data": data}) == nil {
|
||||
fmt.Fprintln(os.Stdout)
|
||||
}
|
||||
}
|
||||
func cpuSeconds() float64 {
|
||||
var usage syscall.Rusage
|
||||
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) != nil {
|
||||
return -1
|
||||
}
|
||||
return float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1e6
|
||||
}
|
||||
|
||||
type operationStats struct {
|
||||
Successes int `json:"successful_requests"`
|
||||
Errors map[string]int `json:"errors"`
|
||||
Latencies []float64 `json:"-"`
|
||||
}
|
||||
type stats struct {
|
||||
Read operationStats
|
||||
Write operationStats
|
||||
}
|
||||
|
||||
func newStats() stats {
|
||||
return stats{Read: operationStats{Errors: map[string]int{}}, Write: operationStats{Errors: map[string]int{}}}
|
||||
}
|
||||
func summary(s operationStats, elapsed float64) map[string]any {
|
||||
sort.Float64s(s.Latencies)
|
||||
var p50, p95, p99 any
|
||||
percentile := func(p float64) float64 { return s.Latencies[int(math.Ceil(p*float64(len(s.Latencies))))-1] }
|
||||
if len(s.Latencies) > 0 {
|
||||
p50 = percentile(.5)
|
||||
p95 = percentile(.95)
|
||||
p99 = percentile(.99)
|
||||
}
|
||||
errors := 0
|
||||
for _, n := range s.Errors {
|
||||
errors += n
|
||||
}
|
||||
ratio := 0.0
|
||||
if errors+s.Successes > 0 {
|
||||
ratio = float64(errors) / float64(errors+s.Successes)
|
||||
}
|
||||
return map[string]any{"successful_requests": s.Successes, "failed_requests": errors, "error_ratio": ratio, "errors": s.Errors, "successful_rps": float64(s.Successes) / elapsed, "successful_latency_ms": map[string]any{"p50": p50, "p95": p95, "p99": p99}}
|
||||
}
|
||||
func classify(err error) string {
|
||||
var e *requestError
|
||||
if errors.As(err, &e) {
|
||||
return fmt.Sprintf("%s:%d", e.Kind, e.Status)
|
||||
}
|
||||
return "protocol_or_integrity"
|
||||
}
|
||||
|
||||
// Closed loop: one outstanding request per goroutine. Request deadlines include body reads.
|
||||
func phase(a *api, users []string, chat string, paths []string, pages [][]message, concurrency, limit, size int, duration time.Duration, mixed bool, expected map[string]message, next *atomic.Int64) map[string]any {
|
||||
start := make(chan struct{})
|
||||
ready := sync.WaitGroup{}
|
||||
done := sync.WaitGroup{}
|
||||
ready.Add(concurrency)
|
||||
done.Add(concurrency)
|
||||
results := make([]stats, concurrency)
|
||||
var mu sync.Mutex
|
||||
var deadline time.Time
|
||||
for worker := 0; worker < concurrency; worker++ {
|
||||
go func(worker int) {
|
||||
defer done.Done()
|
||||
s := newStats()
|
||||
ready.Done()
|
||||
<-start
|
||||
iteration := 0
|
||||
for time.Now().Before(deadline) {
|
||||
write := mixed && (iteration+worker)%20 == 0
|
||||
bucket := &s.Read
|
||||
if write {
|
||||
bucket = &s.Write
|
||||
}
|
||||
began := time.Now()
|
||||
var err error
|
||||
if write {
|
||||
m, e := post(a, users[worker%len(users)], chat, payload(next.Add(1), size))
|
||||
err = e
|
||||
if err == nil {
|
||||
mu.Lock()
|
||||
if _, exists := expected[m.ID]; exists {
|
||||
err = fmt.Errorf("duplicate POST ID")
|
||||
} else {
|
||||
expected[m.ID] = m
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
if !write {
|
||||
idx := (iteration + worker) % len(paths)
|
||||
var p page
|
||||
p, err = read(a, users[worker%len(users)], paths[idx], limit)
|
||||
if err == nil {
|
||||
if len(p.Items) != len(pages[idx]) {
|
||||
err = fmt.Errorf("fixed page changed")
|
||||
} else {
|
||||
for i, m := range p.Items {
|
||||
if m != pages[idx][i] {
|
||||
err = fmt.Errorf("fixed page changed")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
elapsed := float64(time.Since(began).Nanoseconds()) / 1e6
|
||||
if err == nil {
|
||||
bucket.Successes++
|
||||
bucket.Latencies = append(bucket.Latencies, elapsed)
|
||||
} else {
|
||||
bucket.Errors[classify(err)]++
|
||||
}
|
||||
iteration++
|
||||
}
|
||||
results[worker] = s
|
||||
}(worker)
|
||||
}
|
||||
ready.Wait()
|
||||
began := time.Now()
|
||||
cpu := cpuSeconds()
|
||||
deadline = began.Add(duration)
|
||||
close(start)
|
||||
done.Wait()
|
||||
elapsed := time.Since(began).Seconds()
|
||||
cpu = cpuSeconds() - cpu
|
||||
combined := newStats()
|
||||
for _, s := range results {
|
||||
for _, pair := range [][2]*operationStats{{&combined.Read, &s.Read}, {&combined.Write, &s.Write}} {
|
||||
pair[0].Successes += pair[1].Successes
|
||||
pair[0].Latencies = append(pair[0].Latencies, pair[1].Latencies...)
|
||||
for k, n := range pair[1].Errors {
|
||||
pair[0].Errors[k] += n
|
||||
}
|
||||
}
|
||||
}
|
||||
return map[string]any{"requested_seconds": duration.Seconds(), "elapsed_seconds": elapsed, "client_cpu_seconds": cpu, "client_cpu_cores": cpu / elapsed, "read": summary(combined.Read, elapsed), "write": summary(combined.Write, elapsed)}
|
||||
}
|
||||
|
||||
func correctness(a *api, users []string, chat string, expected map[string]message, size int) (map[string]any, error) {
|
||||
// Limits vary and the final page is partial; all seed acknowledgements must survive.
|
||||
var initial []message
|
||||
for _, limit := range []int{1, 7, 50, 100} {
|
||||
all, _, err := walk(a, users[0], chat, limit, len(expected))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = sameHistory(all, expected, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
initial = all
|
||||
}
|
||||
first, err := read(a, users[0], pathFor(chat, 3, ""), 3)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if first.NextCursor == nil {
|
||||
return nil, fmt.Errorf("missing cursor")
|
||||
}
|
||||
second, err := read(a, users[0], pathFor(chat, 79, *first.NextCursor), 79)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i, m := range append(first.Items, second.Items...) {
|
||||
if m != initial[i] {
|
||||
return nil, fmt.Errorf("changing limit lost or reordered messages")
|
||||
}
|
||||
}
|
||||
other, err := newChat(a, users)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = a.call("GET", pathFor(other, 50, *first.NextCursor), users[0], nil, 400, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outsider, err := newUser(a, "outsider")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = a.call("GET", pathFor(chat, 50, ""), outsider, nil, 404, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
empty, err := read(a, users[0], pathFor(other, 50, ""), 50)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(empty.Items) != 0 || empty.NextCursor != nil {
|
||||
return nil, fmt.Errorf("invalid empty history")
|
||||
}
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 13)
|
||||
var mu sync.Mutex
|
||||
seedCount := len(expected)
|
||||
for w, actor := range users {
|
||||
wg.Add(1)
|
||||
go func(w int, actor string) {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
for i := 0; i < 10; i++ {
|
||||
m, e := post(a, actor, chat, payload(int64(seedCount+w*10+i), size))
|
||||
if e != nil {
|
||||
errs <- e
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
if _, exists := expected[m.ID]; exists {
|
||||
mu.Unlock()
|
||||
errs <- fmt.Errorf("duplicate POST ID")
|
||||
return
|
||||
}
|
||||
expected[m.ID] = m
|
||||
mu.Unlock()
|
||||
}
|
||||
}(w, actor)
|
||||
}
|
||||
for _, limit := range []int{2, 17, 53} {
|
||||
wg.Add(1)
|
||||
go func(limit int) {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
all, _, e := walk(a, users[0], chat, limit, seedCount+100)
|
||||
if e == nil {
|
||||
_, e = sameHistory(all, mapFrom(initial), true)
|
||||
}
|
||||
if e != nil {
|
||||
errs <- e
|
||||
}
|
||||
}(limit)
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for e := range errs {
|
||||
return nil, e
|
||||
}
|
||||
all, _, err := walk(a, users[0], chat, 37, len(expected))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = sameHistory(all, expected, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"status": "PASS", "seed_messages": seedCount, "concurrent_writes": 100, "writers": 10, "concurrent_history_walkers": 3, "final_unique_messages": len(all), "limits_checked": []int{1, 7, 50, 100}, "changed_limit": true, "foreign_chat": true, "cursor_binding": true, "empty_history": true, "ordering": "created_at nanoseconds, then id; full Message equality"}, nil
|
||||
}
|
||||
func mapFrom(all []message) map[string]message {
|
||||
m := map[string]message{}
|
||||
for _, item := range all {
|
||||
m[item.ID] = item
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func execute() error {
|
||||
base := flag.String("base-url", "http://127.0.0.1:8080", "isolated lab1 API")
|
||||
mode := flag.String("mode", "load", "load or check")
|
||||
history := flag.Int("history", 1000, "initial message count")
|
||||
concurrency := flag.Int("concurrency", 5, "concurrent clients")
|
||||
limit := flag.Int("page-size", 50, "history page size")
|
||||
seconds := flag.Float64("duration", 30, "measurement seconds")
|
||||
warmup := flag.Float64("warmup", 5, "warmup seconds")
|
||||
timeout := flag.Float64("timeout", 5, "HTTP timeout seconds")
|
||||
size := flag.Int("payload-bytes", 128, "ASCII text bytes")
|
||||
workload := flag.String("workload", "read", "read or mixed (every 20th request writes)")
|
||||
flag.Parse()
|
||||
if (*mode != "load" && *mode != "check") || (*workload != "read" && *workload != "mixed") || *limit < 1 || *limit > 100 || *history < 2**limit || *concurrency < 1 || *concurrency > 256 || *seconds < 1 || *warmup < 0 || *timeout <= 0 || *size < 32 || *size > 4000 {
|
||||
return fmt.Errorf("invalid arguments")
|
||||
}
|
||||
transport := &http.Transport{MaxIdleConns: 512, MaxIdleConnsPerHost: 512, MaxConnsPerHost: 512, IdleConnTimeout: 90 * time.Second, DisableCompression: true}
|
||||
defer transport.CloseIdleConnections()
|
||||
a := &api{base: strings.TrimRight(*base, "/"), client: &http.Client{Transport: transport, Timeout: time.Duration(*timeout * float64(time.Second)), CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
|
||||
if err := a.call("GET", "/health/ready", "", nil, 200, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
users := make([]string, 10)
|
||||
for i := range users {
|
||||
u, err := newUser(a, fmt.Sprint(i))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
users[i] = u
|
||||
}
|
||||
chat, err := newChat(a, users)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
event("seed_start", map[string]any{"messages": *history})
|
||||
expected, err := seed(a, users, chat, *history, *size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *mode == "check" {
|
||||
result, err := correctness(a, users, chat, expected, *size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
event("result", result)
|
||||
return nil
|
||||
}
|
||||
all, cursors, err := walk(a, users[0], chat, *limit, *history)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = sameHistory(all, expected, false); err != nil {
|
||||
return err
|
||||
}
|
||||
positions := []int{0, (*history / 2 / *limit) * *limit, ((*history - *limit) / *limit) * *limit}
|
||||
paths := make([]string, 3)
|
||||
pages := make([][]message, 3)
|
||||
for i, pos := range positions {
|
||||
paths[i] = pathFor(chat, *limit, cursors[pos])
|
||||
pages[i] = append([]message(nil), all[pos:pos+*limit]...)
|
||||
}
|
||||
event("fixture_ready", map[string]any{"messages": len(all), "page_positions": positions})
|
||||
var next atomic.Int64
|
||||
next.Store(int64(*history))
|
||||
mixed := *workload == "mixed"
|
||||
event("warmup_start", nil)
|
||||
if *warmup > 0 {
|
||||
phase(a, users, chat, paths, pages, *concurrency, *limit, *size, time.Duration(*warmup*float64(time.Second)), mixed, expected, &next)
|
||||
}
|
||||
measurementInitial := len(expected)
|
||||
event("measurement_start", map[string]any{"history_messages": measurementInitial})
|
||||
metrics := phase(a, users, chat, paths, pages, *concurrency, *limit, *size, time.Duration(*seconds*float64(time.Second)), mixed, expected, &next)
|
||||
event("measurement_complete", nil)
|
||||
all, _, err = walk(a, users[0], chat, 100, int(next.Load())+*concurrency+*history)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
extra, err := sameHistory(all, expected, mixed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
protocolFailures := 0
|
||||
for _, op := range []string{"read", "write"} {
|
||||
for key, n := range metrics[op].(map[string]any)["errors"].(map[string]int) {
|
||||
if strings.HasPrefix(key, "protocol") {
|
||||
protocolFailures += n
|
||||
}
|
||||
}
|
||||
}
|
||||
if protocolFailures > 0 {
|
||||
return fmt.Errorf("load observed %d protocol/integrity failures", protocolFailures)
|
||||
}
|
||||
event("result", map[string]any{"status": "PASS", "generator": "Go " + runtime.Version() + "; HTTP/1.1 keep-alive, closed loop, no retries", "generator_logical_cpus": runtime.NumCPU(), "workload": *workload, "initial_messages": *history, "measurement_initial_messages": measurementInitial, "final_messages": len(all), "concurrency": *concurrency, "page_size": *limit, "page_positions": positions, "payload_bytes": *size, "metrics": metrics, "integrity": map[string]any{"acknowledged_messages": len(expected), "missing_acknowledged_messages": 0, "unacknowledged_messages": extra, "unique_messages": len(all), "full_message_equality": true}, "limitations": []string{"Success latency only; errors separate. Closed loop has coordinated omission.", "Client includes JSON decoding, equality checks and OS scheduling; this is not a proof of maximum capacity.", "RSS/CPU are collected externally. Mixed workload grows history during warmup and measurement.", "Fixed read pages assume no backwards wall-clock jump during the experiment. No snapshots are required of the API."}})
|
||||
return nil
|
||||
}
|
||||
func main() {
|
||||
if err := execute(); err != nil {
|
||||
event("failure", map[string]string{"reason": err.Error()})
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Contract-based lab1 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, 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")),
|
||||
("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"}
|
||||
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})
|
||||
|
||||
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")}
|
||||
if case["group"] in ("utf8", "observations"):
|
||||
result["request_hex"] = case["raw"].hex()
|
||||
try:
|
||||
response = client.call("POST", case["path"], expected=list(range(200, 600)),
|
||||
actor=case["actor"], raw=case["raw"],
|
||||
headers={"Content-Type": "application/json"})
|
||||
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()), "valid fields changed")
|
||||
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):
|
||||
results = run(client, {group}, 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))
|
||||
|
||||
|
||||
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