10 Commits
Author SHA1 Message Date
kudesn1k bb5981f522 Обновить доказательства на коде после ревью, сверить с ними отчёт и выделить исправления базы в шаблоне PR 2026-10-21 15:15:37 +03:00
kudesn1k 7aa86d36ba Учесть замечания ревью: читать timestamptz в UTC, встроить списки колонок, не требовать каноническую PHC-строку, уточнить замеры отказов 2026-10-21 15:08:17 +03:00
kudesn1k 956b84f2d7 Заполнить отчёт и доказательства лабораторной 2 2026-10-06 16:05:24 +03:00
kudesn1k 949622ed93 Не показывать клиенту контекст обёртки ошибок 2026-10-06 15:58:55 +03:00
kudesn1k ba535c6ee6 Проверять готовность PostgreSQL по TCP и ограничить память Valkey 2026-10-06 15:54:26 +03:00
kudesn1k bea31f3f02 Ограничить дозвон и поиск имени зависимостей одной секундой 2026-10-06 15:54:26 +03:00
kudesn1k f9850a36c4 Упростить ошибки сессий, логировать миграции и тестировать с рабочим клиентом Valkey 2026-10-06 15:46:01 +03:00
kudesn1k 405fb07608 Логировать причину ответов 5xx при отказе зависимостей 2026-10-06 15:43:23 +03:00
kudesn1k 3001507ecb Отвечать 400 и 401 вместо 500 на NUL и невалидный UTF-8 во входных данных 2026-10-06 15:41:36 +03:00
kudesn1k 8f9252a5c1 Сделать (chat_id, id) ключом сообщений и добавить сценарий EXPLAIN истории 2026-10-06 15:25:26 +03:00
39 changed files with 680 additions and 107 deletions
+14 -14
View File
@@ -1,18 +1,18 @@
## Лабораторная 2
Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO
Автор / группа: Бакулин, БПИ2301
Целевая оценка (3/4/5): 4
Трек 5, если заявлен: не заявлен
Что реализовано и что перенесено: TODO
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO
Что реализовано и что перенесено: перенесён минимум lab1 (формат ошибок, keyset-пагинация, UUIDv7, graceful shutdown). Пользователи, чаты, участники и сообщения хранятся в PostgreSQL 18 (pgx, миграции goose при старте, атомарное создание чата). Регистрация с паролем (Argon2id), вход через Basic, непрозрачный Bearer-токен, сессии в Valkey с AOF `appendfsync always` и абсолютным сроком, logout. Недоступность PostgreSQL или Valkey даёт 503 с причиной в логе. Стенд в compose с secrets, хук перезапуска, EXPLAIN истории. Исправления базы lab1: `WithUser` перенесён из `auth` в `httpx` (иначе цикл импортов `auth ↔ user`), `server.Run` не зависит от сборки приложения, `member_ids` всегда в порядке id; in-memory хранилища удалены. Подробности — в REPORT.md.
Команды запуска из чистого clone: `make secrets && make up`, затем `make test`, `make test-persistence ACTION_SCRIPT=scripts/restart.sh`, `make unit` (нужен Docker), `make explain`; удаление данных — `make destroy`.
Результаты проверок и ссылка на REPORT.md: REPORT.md, раздел «Доказательства критериев»; файлы в `evidence/`.
Ограничения / известные ошибки: один host без репликации; потеря Valkey разлогинивает всех; без TLS (lab7); описание семантики пагинации при конкурентных вставках — в REPORT.md.
Источники и использование ИИ: перечислены в REPORT.md. ИИ-ассистент использовался как парный программист: генерация кода, тестов и черновиков документации по моим архитектурным решениям с последующим ревью каждого модуля и переработкой по замечаниям; выбор стека, структура проекта, модель данных, обработка ошибок, логирование и границы модулей определены мной; все проверки воспроизведены мной вручную.
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [ ] Контракт и публичные тесты не ослаблены.
- [ ] make check и make test выполнены; приложен реальный вывод.
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные тесты не ослаблены.
- [x] make check и make test выполнены; приложен реальный вывод.
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
+130 -15
View File
@@ -1,37 +1,152 @@
# Отчёт — лабораторная 2
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор, группа: Бакулин, БПИ2301
- Целевая оценка; выбранный трек 5, если нужен: 4. Уровни 3 и 4 выполнены полностью, трек 5 не заявлен.
- Commit/PR: ветка `solution/bpi2301-bakulin`; ссылка на PR — после публикации.
- Использованные источники, библиотеки и помощь ИИ: документация PostgreSQL 18 (транзакции, EXPLAIN, `uuidv7`, типы даты/времени), PostgreSQL wiki «Don't Do This», документация Valkey (persistence, ACL/requirepass, eviction), RFC 7617 (Basic), RFC 6750 и RFC 7235 (Bearer, `WWW-Authenticate`), RFC 9106 и OWASP Password Storage Cheat Sheet (Argon2id), документация Docker Compose (secrets, healthcheck, `depends_on`). Библиотеки: `github.com/gin-gonic/gin` v1.12.0, `github.com/google/uuid` v1.6.0, `github.com/jackc/pgx/v5` v5.11.0 (драйвер и пул), `github.com/pressly/goose/v3` v3.27.0 (миграции), `github.com/redis/go-redis/v9` v9.23.0 (клиент Valkey), `golang.org/x/crypto/argon2`, в тестах `github.com/testcontainers/testcontainers-go` v0.39.0. ИИ-ассистент использовался как парный программист: генерация кода, тестов и черновиков документации по моим архитектурным решениям с последующим ревью каждого модуля и переработкой по замечаниям; выбор стека, структура проекта, модель данных, обработка ошибок, логирование и границы модулей определены мной; все проверки воспроизведены мной вручную.
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Версии, на которых выполнялись проверки: Go 1.27.1 (`go.mod`), Docker Desktop 28.5.1 с Compose v2 (нужен 2.24+ из-за `env_file … required: false`), Python 3.13 для публичных проверок (нужен 3.9+), GNU Make. Образы закреплены digest'ами: `postgres:18.6-alpine3.24`, `valkey/valkey:9.1.2-alpine3.24` в `compose.yaml`, `golang:1.27.1-alpine3.23` и `alpine:3.23` в `Dockerfile`.
```sh
make secrets # ./secrets: пароли PostgreSQL и Valkey и URL для API; существующие файлы не перезаписываются
make up # docker compose up -d --build --wait: postgres и valkey healthy → api применяет миграции → healthy
make check PYTHON=python
make validate PYTHON=python # полная проверка OpenAPI; нужен pip install -r requirements-dev.txt
make test PYTHON=python
make test-persistence ACTION_SCRIPT=scripts/restart.sh PYTHON=python # на Windows: ACTION_SCRIPT=scripts/restart.cmd
make unit # собственные тесты; нужен запущенный Docker: тесты поднимают свои PostgreSQL и Valkey
make explain > evidence/explain-history.txt
make concurrency # 10 клиентов × 10 сообщений, отчёт в evidence/concurrency.json
```
`.env` не обязателен: все настройки имеют значения по умолчанию, а пути к секретам задаёт `compose.yaml`. Если порт 8080 занят — `PUBLISH=127.0.0.1:18080 make up` и `BASE_URL=http://localhost:18080` для проверок. Короткий TTL для проверки истечения: `SESSION_TTL_SECONDS=2 make up` (Compose пересоздаст только api; вернуть — `make up`).
Секреты. `scripts/init-secrets.sh` создаёт в `./secrets` (каталог в `.gitignore` и `.dockerignore`) четыре файла: пароль PostgreSQL, DSN для API, `requirepass` для Valkey и URL Valkey для API. Compose монтирует их как secrets в `/run/secrets/*`; API читает их через `DATABASE_URL_FILE` и `SESSION_STORE_URL_FILE`, PostgreSQL — через `POSTGRES_PASSWORD_FILE`, Valkey — через `include` в `infra/valkey/valkey.conf`. Значения секретов не попадают ни в env контейнера (`docker inspect`), ни в образ, ни в логи. Скрипт не перезаписывает существующие файлы: PostgreSQL применяет пароль только при инициализации volume, новый пароль при живом volume заблокировал бы API.
Bootstrap и миграции. Схема — `migrations/00001_init.sql`, вшита в бинарник через `embed`. API при старте до открытия порта применяет миграции goose под session advisory lock (несколько реплик в lab3 сериализуются на нём), в логе `schema ready applied_migrations=[1]`, повторный старт — `applied_migrations=[]`. Отдельного шага оператора нет.
Остановка и удаление данных. `docker compose stop` — graceful остановка всех трёх процессов (API дорабатывает запросы, PostgreSQL пишет checkpoint, Valkey дописывает AOF); `make down` — удалить контейнеры с сохранением volumes; `make destroy` (`docker compose down -v`) — **намеренное удаление всех учебных данных**: пользователей, чатов, сообщений и сессий. Для полного сброса затем удалить `./secrets`.
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
```
клиент ──HTTP──> api (Go, gin) ──pgx pool (≤10)──> postgres [volume pgdata] users, chats, chat_members, messages
└─go-redis (≤10)──> valkey [volume valkeydata] session:<sha256(token)> → user_id
```
Источник истины: PostgreSQL — для пользователей, чатов, участников и сообщений; Valkey — единственное хранилище сессий и, значит, их источник истины (кэша в работе нет). Обе зависимости критичны для синхронного пути: без Valkey нельзя аутентифицировать ни один запрос, без PostgreSQL — прочитать или записать данные. `/health/ready` проверяет обе (общий бюджет 1 с) и флаг shutdown; `/health/live` — только процесс.
Модель данных (`migrations/00001_init.sql`). В схеме только модель данных — `NOT NULL`, PK, FK, `UNIQUE`; правила валидации (форматы, длины) живут в приложении и в БД не дублируются. Время — `timestamptz` (момент времени, в UTC по построению), `created_at` пишет приложение из UUIDv7 id, поэтому порядок `(created_at, id)` совпадает с порядком id.
| Таблица | Ключи и индексы | Зачем |
| --- | --- | --- |
| users | PK id, `users_username_key UNIQUE (username)` | уникальность username держит constraint, поэтому гонка регистраций безопасна |
| chats | PK id | |
| chat_members | PK (chat_id, user_id), индекс (user_id, chat_id), FK на chats и users | членство и состав чата; список чатов пользователя keyset-ом по второму индексу |
| messages | PK (chat_id, id), FK на chats и users | ключ и есть индекс истории: `WHERE chat_id=$1 AND id>$2 ORDER BY id LIMIT $3` |
Ключ сообщений — `(chat_id, id)`, отдельного индекса по id нет. Сообщение по одному id API не ищет, а такой индекс стоил бы записи и, как показал EXPLAIN на 102 000 сообщений, уводил планировщик в обход всех сообщений по порядку id с фильтром по чату (15 303 отброшенные строки и 1092 буфера на первой странице). Цена: уникальность id гарантирована внутри чата; id генерирует сервер (UUIDv7, 74 случайных бита), коллизия практически исключена. Время диапазоном тоже не требует отдельного индекса: UUIDv7 содержит время, интервал `[t1, t2)` превращается в диапазон id по тому же ключу.
Транзакционные границы. Регистрация — один `INSERT`, `23505` по `users_username_key` даёт 409. Создание чата — одна транзакция: `INSERT chats` и `INSERT chat_members … unnest($2::uuid[])`; существование участников проверяется до транзакции одним batch-запросом (400 на неизвестного), FK остаётся страховкой. Отправка сообщения — проверка членства и один `INSERT`. Чтения — одиночные `SELECT` на `READ COMMITTED`. Ограничение (contracts/README:20): id выдаётся до `INSERT`, поэтому коммиты конкурентных отправок могут лечь не в порядке id; читатель, чей cursor уже прошёл больший id, не увидит «опоздавшее» сообщение при продолжении обхода, при чтении с начала оно стоит на своём месте, повторов нет.
Аутентификация (`internal/auth`). `POST /api/v1/auth/sessions` принимает только `Authorization: Basic` (`Request.BasicAuth` делит строку по первому двоеточию, так что двоеточие в пароле допустимо). Неизвестный пользователь, неверный пароль, username с NUL или не-UTF-8 дают одинаковый 401 с `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`; для неизвестного username всё равно выполняется KDF на фиктивном хеше, чтобы время ответа не выдавало существование пользователя. Успех — `201 {token, token_type: "Bearer", expires_at, user}`. Токен — 32 случайных байта в base64url (256 бит), непрозрачный. В Valkey хранится ключ `session:<sha256(token)>` со значением user_id и абсолютным сроком (`SET … PXAT/EXAT`): утечка AOF не даёт рабочих токенов, а рестарт не продлевает сессию. Все остальные endpoint'ы требуют `Authorization: Bearer <token>` (схема без учёта регистра); отсутствие, Basic, неизвестный, истёкший или отозванный токен — 401 с `WWW-Authenticate: Bearer realm="messenger"`. `X-User-Id` не читается вообще. `DELETE /api/v1/auth/sessions/current` удаляет ключ и отвечает 204, повтор — 401. Срок жизни задаёт `SESSION_TTL_SECONDS` и фиксируется при входе; скользящего продления нет, иначе `expires_at` в ответе был бы ложью. Пароли — Argon2id (`m=19 MiB, t=2, p=1`, соль 16 байт) в PHC-строке; параметры читаются из строки, поэтому их можно поднять без инвалидации старых хешей.
Valkey (`infra/valkey/valkey.conf`): `appendonly yes`, `appendfsync always` — запись сессии подтверждается после fsync, как COMMIT в PostgreSQL; пишут только вход и выход, чтение сессии fsync не трогает. `save ""` — RDB не нужен рядом с AOF. `maxmemory 256mb` с `noeviction` — сессии никогда не вытесняются: при заполнении новые входы получают 503, а не молча разлогинивают пользователей. Пароль Valkey задан: иначе любой процесс в docker-сети мог бы записать `session:<sha256(своего токена)>` и подделать сессию.
Отказы и таймауты. Пул PostgreSQL ограничен 10 соединениями, `statement_timeout=5s`, `idle_in_transaction_session_timeout=10s`, подключение и поиск имени хоста — 1 с. Клиент Valkey: пул 10, дозвон 1 с одной попыткой, чтение и запись 1 с, повторы команд выключены. Каждый запрос к `/api` ограничен дедлайном 5 с (меньше `WriteTimeout` сервера 10 с, чтобы 503 успел записаться). Недоступность зависимости (отказ соединения, таймаут, классы ошибок PostgreSQL 08/53/57) превращается в `503 unavailable`; клиенту уходит только безопасное сообщение (`database unavailable`, `session store unavailable`), причина пишется в лог строкой `request failed` с `request_id` и `cause`. Аноним при недоступном Valkey не пропускается: ответ 503, а не 401 и не 200. Регистрация от Valkey не зависит и продолжает работать.
Код и что изменилось относительно lab1:
```
cmd/server конфигурация, пул PostgreSQL, миграции, клиент Valkey, listener, сигналы
migrations/ SQL-миграции goose, вшиты в бинарник
internal/app composition root (Deps: пул, клиент Valkey, TTL, таймаут запроса)
internal/server http.Server и graceful shutdown; принимает http.Handler и флаг readiness
internal/auth session.go, repository.go, service.go, handler.go, middleware.go; store/valkey.go
internal/user + пароль и Authenticate; store/postgres.go (inmem удалён)
internal/chat участники в каноническом порядке по id; store/postgres.go (inmem удалён)
internal/health live/ready с проверками зависимостей
internal/platform/ config (+ *_FILE, SESSION_TTL_SECONDS), postgres (пул, Migrate, Classify),
valkey (клиент), password (Argon2id), httpx (+ WithUser, Timeout), apperr, ident, pagination
internal/testenv PostgreSQL и Valkey в testcontainers для тестов; в бинарник не входит
tools/concurrency чёрный ящик гонок, теперь с паролем и Bearer
```
Перенесено из lab1 без изменений: формат ошибок и `X-Request-Id`, keyset-пагинация и cursor, UUIDv7 и вывод `created_at` из id, access log по уровням, graceful shutdown. Изменено по объявленному переходу 1 → 2: регистрация требует `password`, `X-User-Id` заменён Bearer-сессией, Basic только на входе. Исправления базы: `WithUser` переехал из `auth` в `httpx` (иначе цикл импортов `auth ↔ user`), `server.Run` больше не зависит от сборки приложения, `member_ids` всегда в порядке id (контракт считает их множеством). Удалены in-memory хранилища и сценарий `student-tests/lifecycle.sh` (он проверял потерю данных после рестарта — в lab2 нужно обратное, это проверяет `make test-persistence`).
Тесты. Сервисы, хранилища и HTTP тестируются против настоящих PostgreSQL и Valkey (testcontainers-go, один контейнер на пакет, `TRUNCATE` всех таблиц и `FLUSHDB` перед каждым тестом); чистая логика (валидация, cursor, конфигурация, Argon2id) — обычными юнит-тестами. testcontainers закреплён на v0.39.0: с v0.40 он запрашивает публикацию порта с `HostPort "0"`, которую Docker Desktop 28.5.1 на Windows не выполняет; goose — на v3.27.0 из-за совместимости транзитивной зависимости с этой версией.
Соответствие `.env.example` реальной конфигурации:
| Переменная | `.env.example` | Реализация | По умолчанию |
| --- | --- | --- | --- |
| APP_HOST, APP_PORT, APP_ENV | да | как в lab1 | 0.0.0.0, 8080, lab |
| SESSION_TTL_SECONDS | да | срок сессии, целое > 0 | 3600 |
| DATABASE_URL_FILE | да | файл с DSN PostgreSQL, обязателен | `/run/secrets/database_url` в compose |
| SESSION_STORE | да (`postgres`) | не читается: сессии всегда в Valkey | — |
| CACHE_URL_FILE | да | не используется: кэша нет; имя оставлено для кэша, если он появится | — |
| SESSION_STORE_URL_FILE | нет | файл с URL Valkey, обязателен | `/run/secrets/session_store_url` в compose |
| APP_LOG_LEVEL, APP_SHUTDOWN_TIMEOUT, APP_MAX_BODY_BYTES | нет | как в lab1 | info, 8s, 65536 |
Ошибка в любой переменной или нечитаемый файл секрета останавливают процесс на старте с кодом 2; сообщение называет переменную, но не значение.
Роли стенда:
| Роль | Сервис | Версия | Health/readiness | Volume | Сеть/порт | Credentials |
| --- | --- | --- | --- | --- | --- | --- |
| api | api (`mtusi-messenger-lab2`) | сборка из исходников | `/health/ready` (PG + Valkey) | — | `127.0.0.1:8080` | secrets `database_url`, `session_store_url` |
| postgres | postgres | 18.6-alpine3.24 @digest | `pg_isready -h 127.0.0.1` | `pgdata:/var/lib/postgresql` | только внутренняя сеть | secret `postgres_password` |
| redis_or_valkey | valkey | 9.1.2-alpine3.24 @digest | `valkey-cli ping` с паролем | `valkeydata:/data` (AOF) | только внутренняя сеть | secret `valkey_auth` |
CI. `.github/workflows/app.yml`: unit-тесты с race detector (на runner нужен Docker для testcontainers), затем `make secrets`, `docker compose up --build --wait`, smoke, persistence с `scripts/restart.sh`, concurrency, логи и `down -v` (стенд CI одноразовый). Skeleton-job `contracts.yml` не менялся.
## Доказательства критериев
Все файлы сняты на одном стенде, поднятом с пустых volumes (дата, commit и параметры хоста в заголовке каждого файла).
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Публичный smoke | `make check`, `make validate`, `make test` | все PASS | evidence/smoke.txt |
| Минимум lab1 с переходом на Bearer | `make test` (сценарий lab2), `TestProtectedRoutesAcceptOnlyBearer` и остальные HTTP-тесты `internal/app` | PASS | evidence/smoke.txt, evidence/tests.txt |
| Данные и действующие сессии переживают рестарт API и хранилищ без удаления volumes | `make test-persistence ACTION_SCRIPT=scripts/restart.cmd` (`restart.sh`: `docker compose stop` + `up -d --wait`) | PASS тем же токеном; `StartedAt` всех трёх контейнеров изменился | evidence/persistence.txt |
| PostgreSQL: пользователи, чаты, участники, сообщения; PK/FK, UNIQUE username; миграции с нуля | `make destroy && make up`, `\dt`, `\di` | `schema ready applied_migrations=[1]`, 4 таблицы и индексы | evidence/bootstrap.txt |
| Повторный запуск миграций без дублирования | рестарт api; `TestMigrateIsRepeatable` | `applied_migrations=[]` | evidence/bootstrap.txt, evidence/tests.txt |
| Атомарное создание чата и его rollback | `TestCreateRollsBackWhenMemberInsertFails` | после ошибки FK нет ни строки чата, ни участников | evidence/tests.txt |
| Basic только на входе, Bearer на остальных, `X-User-Id` не даёт доступ | `TestProtectedRoutesAcceptOnlyBearer`, `TestLoginFailuresAreUniformBasicChallenges` | 401 с нужным `WWW-Authenticate`; `X-User-Id` игнорируется | evidence/tests.txt |
| Срок жизни и отзыв сессии | `TestSessionExpiresAfterTTL`, `TestLogoutRevokesOnlyTheCurrentToken`; стенд с `SESSION_TTL_SECONDS=2` | через 3 с 401 Bearer; logout 204, повтор 401 | evidence/expiry.txt, evidence/tests.txt |
| Пароли через password KDF | `TestRegisterStoresUserWithPasswordHash` | в БД `$argon2id$v=19$m=19456,t=2,p=1$…` | evidence/tests.txt |
| Secrets/volumes не в Git | `git ls-files secrets .env` | пусто; `secrets/` в `.gitignore` и `.dockerignore` | — |
| Valkey реально используется для сессий с TTL и persistence | `CONFIG GET`; остановка/запуск Valkey с тем же токеном | `appendonly yes`, `appendfsync always`, `noeviction`; после рестарта Valkey токен работает | evidence/bootstrap.txt, evidence/dependency-failures.txt |
| Параметризованные запросы, ограниченный пул и таймауты | код `store/postgres.go` (только `$n`), `TestPoolAppliesLimitsAndTimeouts`, `TestTimeoutBoundsTheRequestContext` | `MaxConns=10`, `statement_timeout=5s`, connect 1 с, дедлайн запроса | evidence/tests.txt |
| Гонка регистрации одного username | `TestConcurrentRegistrationOfOneUsernameHasOneWinner` | 10 параллельных попыток: ровно 1 успех, 9 × 409, одна строка | evidence/tests.txt |
| Индекс истории обоснован EXPLAIN на ≥10 000 сообщений, без полного scan на страницу | `make explain` (102 000 сообщений, 12 000 в целевом чате, транзакция с ROLLBACK) | `Index Scan using messages_pkey`, `Index Cond (chat_id = … AND id > …)`, 51 строка; 51 буфер на первой странице и 6 на глубокой, 0.05–0.1 мс; OFFSET той же страницы — сортировка 10 052 строк, 495 буферов, 6.5 мс | evidence/explain-history.txt |
| Автопроверки expiry, logout, неверного пароля, недоступности Redis/БД | `TestSessionExpiresAfterTTL`, `TestLogoutRevokesOnlyTheCurrentToken`, `TestLoginFailuresAreUniformBasicChallenges`, `TestValkeyOutageAnswers503`, `TestPostgresOutageAnswers503`, `TestHungPostgresAnswers503WithinTheRequestTimeout` | все PASS; при отказе — 503, никогда 200 или 401 | evidence/tests.txt, evidence/dependency-failures.txt |
| Гонки отправки сообщений | `make concurrency` | 100/100 созданы, перечислены и уникальны, порядок по id | evidence/concurrency.json |
| Выбранный трек 5 | не заявлен | — | — |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Стенд: Windows 11 Pro, Docker Desktop 28.5.1 (4 CPU, 3.8 GiB RAM для Linux-VM), без лимитов CPU/RAM на контейнеры, loopback-сеть. Нагрузочные измерения не проводились (трек 5 не заявлен); ниже проверки отказов уровня 4.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
| Полный рестарт: `docker compose stop` и `up -d --wait` (хук persistence) | те же данные и тот же токен | PASS, все три процесса перезапущены | весь тест с хуком ~15 с; потерь нет |
| `docker compose stop valkey` | 503 на защищённые запросы и вход, ready 503, регистрация работает | 503 за 1.0 с (дозвон ограничен 1 с; без ограничения поиск имени остановленного контейнера в DNS Docker не укладывается в дедлайн запроса 5 с), `POST /users` 201, в логе `cause: dial tcp: lookup valkey: i/o timeout` | после `start` тот же токен 200: сессии восстановлены из AOF |
| `docker compose stop postgres` | 503 на операции с данными, ready 503 | первый запрос — 503 за 0.02 с (PostgreSQL при остановке закрыл соединения пула, в логе `57P01`), следующие — за 1.0 с (новое соединение ждёт поиск имени, ограниченный 1 с, в логе `hostname resolving error … i/o timeout`) | после `start` 200 без перезапуска API: пул переподключается |
| PostgreSQL на паузе (`docker pause`, тест) | запрос не висит дольше дедлайна | 503 при дедлайне 300 мс, ready 503 | — |
| `SESSION_TTL_SECONDS=2` | сессия истекает | 200 сразу, 401 Bearer через 3 с | — |
| Ввод, который PostgreSQL не может хранить: NUL в `display_name`/`title`/`text`, NUL или не-UTF-8 в Basic username | 400 / 401, не 500 | 400 и 401 (проверка в приложении) | — |
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Один Docker-host и по одному экземпляру PostgreSQL и Valkey: отказ host или диска теряет сервис; репликации и бэкапов нет. `appendfsync always` защищает подтверждённые сессии от падения процесса Valkey, но не от потери volume.
- Потеря или `FLUSHALL` Valkey разлогинивает всех: сессии существуют только там. Данные пользователей при этом не теряются, нужен повторный вход.
- Valkey — вторая критичная зависимость: при его отказе защищённый API отвечает 503, хотя PostgreSQL жив. Это осознанная цена хранения сессий вне БД.
- Argon2id тратит 19 MiB на вход или регистрацию; ограничения частоты входа нет (429 в контракте факультативен), всплеск входов нагружает CPU и память API.
- Семантика пагинации при конкурентных вставках описана выше: сообщение, закоммиченное позже сообщения с большим id, может быть пропущено продолжением уже идущего обхода.
- Уникальность id сообщения гарантирована в пределах чата; поиск сообщения по одному id потребует отдельного индекса.
- HTTP без TLS допустим только на локальном стенде (Basic передаёт пароль в открытом виде); TLS — в lab7. API ходит в PostgreSQL пользователем `messenger`, которого создаёт образ (он суперпользователь); отдельная роль без DDL и прав суперпользователя — задача lab7.
- `scripts/restart.cmd` нужен только на Windows: `tests/resilience.py` запускает хук без shell, а Windows не исполняет `.sh` напрямую.
- Дальше: трек 5 по согласованности кэша истории (отдельный экземпляр Valkey под кэш, имя переменной `CACHE_URL_FILE` зарезервировано) либо подготовка к lab3 (реплики API используют общие сессии в Valkey уже сейчас).
+3 -1
View File
@@ -42,9 +42,11 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config) error {
return err
}
defer pool.Close()
if err := postgres.Migrate(ctx, pool); err != nil {
applied, err := postgres.Migrate(ctx, pool)
if err != nil {
return err
}
log.Info("schema ready", "applied_migrations", applied)
sessions, err := valkey.NewClient(ctx, cfg.SessionStoreURL)
if err != nil {
return err
+3 -1
View File
@@ -41,7 +41,9 @@ services:
volumes:
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD", "pg_isready", "-U", "messenger", "-d", "messenger"]
# Over TCP: during first initialisation the image runs a temporary
# server on the Unix socket only, which must not count as ready.
test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "messenger", "-d", "messenger"]
interval: 5s
timeout: 3s
retries: 10
+63
View File
@@ -0,0 +1,63 @@
# Bootstrap from empty volumes: make destroy && make secrets up
# date: 2026-10-21T12:09:10Z, commit: 7aa86d3 (branch solution/bpi2301-bakulin)
# host: Windows 11, Docker Desktop 28.5.1 (4 CPU, 4111327232 bytes RAM), Go go1.27.1, Python 3.13.1
$ make up
Network mtusi2026lab2_default Created
Volume mtusi2026lab2_pgdata Created
Volume mtusi2026lab2_valkeydata Created
Container mtusi2026lab2-valkey-1 Created
Container mtusi2026lab2-postgres-1 Created
Container mtusi-messenger-lab2 Created
Container mtusi2026lab2-valkey-1 Started
Container mtusi2026lab2-postgres-1 Started
Container mtusi2026lab2-valkey-1 Healthy
Container mtusi2026lab2-postgres-1 Healthy
Container mtusi-messenger-lab2 Started
Container mtusi2026lab2-postgres-1 Healthy
Container mtusi2026lab2-valkey-1 Healthy
Container mtusi-messenger-lab2 Healthy
$ docker compose ps
SERVICE IMAGE STATUS PORTS
api mtusi-messenger:lab2 Up 6 seconds (healthy) 127.0.0.1:8080->8080/tcp
postgres postgres:18.6-alpine3.24@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873 Up 12 seconds (healthy) 5432/tcp
valkey valkey/valkey:9.1.2-alpine3.24@sha256:48332870af354a799964c0012ae1194a0bf2bf894eb508f945810596dc2d8d11 Up 12 seconds (healthy) 6379/tcp
$ docker compose logs api | grep -E "schema ready|starting"
{"time":"2026-10-21T12:10:07.644733332Z","level":"INFO","msg":"schema ready","applied_migrations":[1]}
{"time":"2026-10-21T12:10:07.674799548Z","level":"INFO","msg":"starting","env":"lab","addr":"0.0.0.0:8080","shutdown_timeout":"8s","session_ttl":"1h0m0s"}
$ psql \dt and \di (schema created by the migration)
List of tables
Schema | Name | Type | Owner
--------+------------------+-------+-----------
public | chat_members | table | messenger
public | chats | table | messenger
public | goose_db_version | table | messenger
public | messages | table | messenger
public | users | table | messenger
(5 rows)
List of indexes
Schema | Name | Type | Owner | Table
--------+----------------------------+-------+-----------+------------------
public | chat_members_pkey | index | messenger | chat_members
public | chat_members_user_chat_idx | index | messenger | chat_members
public | chats_pkey | index | messenger | chats
public | goose_db_version_pkey | index | messenger | goose_db_version
public | messages_pkey | index | messenger | messages
public | users_pkey | index | messenger | users
public | users_username_key | index | messenger | users
(7 rows)
$ valkey-cli CONFIG GET (persistence of the session store)
appendonly yes
appendfsync always
save
maxmemory 268435456
maxmemory-policy noeviction
$ second start: migrations are a no-op
{"time":"2026-10-21T12:10:18.658799511Z","level":"INFO","msg":"schema ready","applied_migrations":[]}
+16
View File
@@ -0,0 +1,16 @@
{
"base_url": "http://localhost:8080",
"started_at": "2026-10-21T12:11:30.6825994Z",
"clients": 10,
"per_client": 10,
"expected_messages": 100,
"created_201": 100,
"failed_posts": 0,
"listed_messages": 100,
"unique_ids": 100,
"created_but_not_listed": 0,
"history_ordered_by_id": true,
"pages_read": 1,
"elapsed_seconds": 0.0793356,
"passed": true
}
+37
View File
@@ -0,0 +1,37 @@
# Dependency outages on the stand (request deadline 5 s, dial/connect and host lookup 1 s, readiness budget 1 s)
# date: 2026-10-21T12:14:15Z, commit: 7aa86d3 (branch solution/bpi2301-bakulin)
# host: Windows 11, Docker Desktop 28.5.1 (4 CPU, 4111327232 bytes RAM), Go go1.27.1, Python 3.13.1
baseline GET /users/me: 200
$ docker compose stop valkey
client sees only a safe message:
{"error":{"code":"unavailable","message":"session store unavailable","request_id":"dcf58dc8b038da34fbffaa398be2ae19"}}
GET /users/me: 503 in 1.029945s, request_id 409bc8d095cd5c0aa8bff3a5a6103336
POST /auth/sessions: 503 in 1.067333s, request_id b80c3cf8d77205be7d145d366e3eba7c
POST /users (PostgreSQL only): 201
GET /health/ready: 503
api log, by request_id:
409bc8d095cd5c0aa8bff3a5a6103336: session store unavailable <- dial tcp: lookup valkey: i/o timeout
b80c3cf8d77205be7d145d366e3eba7c: session store unavailable <- dial tcp: lookup valkey: i/o timeout
after docker compose start valkey, same token: 200 (session survived via AOF)
$ docker compose stop postgres
first request: the pooled connection was closed by the server on shutdown
GET /chats: 503 in 0.022848s, request_id 484577a2014613ccc2cc0af7a110147b
next requests: a new connection waits for the host lookup, bounded by 1 s
GET /chats: 503 in 1.018873s, request_id 68b40ce6917aac8cae5a3a06f53f0d3f
GET /chats: 503 in 1.019858s, request_id d085caa2d09226ceebe5b9aad55cbc2b
GET /chats: 503 in 1.016325s, request_id e646903eb0912bf1c2b75a3dee3c302e
client sees only a safe message:
{"error":{"code":"unavailable","message":"database unavailable","request_id":"0dc9f28ccba988caededb452faec06ac"}}
GET /health/ready: 503
api log, by request_id:
484577a2014613ccc2cc0af7a110147b: select chats: database unavailable <- FATAL: terminating connection due to administrator command (SQLSTATE 57P01)
68b40ce6917aac8cae5a3a06f53f0d3f: select chats: database unavailable <- failed to connect to `user=messenger database=messenger`: hostname resolving error: lookup postgres on 127.0.0.11:53: dial udp 127.0.0.11:53: i/o timeout
d085caa2d09226ceebe5b9aad55cbc2b: select chats: database unavailable <- failed to connect to `user=messenger database=messenger`: hostname resolving error: lookup postgres on 127.0.0.11:53: dial udp 127.0.0.11:53: i/o timeout
e646903eb0912bf1c2b75a3dee3c302e: select chats: database unavailable <- failed to connect to `user=messenger database=messenger`: hostname resolving error: lookup postgres on 127.0.0.11:53: dial udp 127.0.0.11:53: i/o timeout
after docker compose start postgres: 200
GET /health/ready: 200
+12
View File
@@ -0,0 +1,12 @@
# Session expiry with SESSION_TTL_SECONDS=2
# date: 2026-10-21T12:09:10Z, commit: 7aa86d3 (branch solution/bpi2301-bakulin)
# host: Windows 11, Docker Desktop 28.5.1 (4 CPU, 4111327232 bytes RAM), Go go1.27.1, Python 3.13.1
api SESSION_TTL_SECONDS=2
GET /users/me right after login: 200
GET /users/me 3 s later:
HTTP/1.1 401 Unauthorized
Www-Authenticate: Bearer realm="messenger"
{"error":{"code":"unauthorized","message":"a valid bearer token is required","request_id":"e191d8f08a51fced88868d6fac0d8674"}}
api restored with SESSION_TTL_SECONDS=3600
+61
View File
@@ -0,0 +1,61 @@
# EXPLAIN (ANALYZE, BUFFERS) of the history query: make explain
# date: 2026-10-21T12:09:10Z, commit: 7aa86d3 (branch solution/bpi2301-bakulin)
# host: Windows 11, Docker Desktop 28.5.1 (4 CPU, 4111327232 bytes RAM), Go go1.27.1, Python 3.13.1
big_chat_messages | all_messages
-------------------+--------------
12000 | 102003
(1 row)
== First page: no cursor, limit 50 (+1 row that tells whether a next page exists)
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.42..23.92 rows=51 width=67) (actual time=0.027..0.060 rows=51.00 loops=1)
Buffers: shared hit=51
-> Index Scan using messages_pkey on messages (cost=0.42..5526.02 rows=11988 width=67) (actual time=0.026..0.056 rows=51.00 loops=1)
Index Cond: ((chat_id = '01a15e5f-93aa-7f38-9ff3-684f0d6ded77'::uuid) AND (id > '00000000-0000-0000-0000-000000000000'::uuid))
Index Searches: 1
Buffers: shared hit=51
Planning:
Buffers: shared hit=17
Planning Time: 0.211 ms
Execution Time: 0.097 ms
(10 rows)
== Deep page: cursor after the 10 001st message of the chat
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.42..184.60 rows=51 width=67) (actual time=0.018..0.030 rows=51.00 loops=1)
Buffers: shared hit=6
-> Index Scan using messages_pkey on messages (cost=0.42..650.48 rows=180 width=67) (actual time=0.018..0.026 rows=51.00 loops=1)
Index Cond: ((chat_id = '01a15e5f-93aa-7f38-9ff3-684f0d6ded77'::uuid) AND (id > '01a15e5f-9557-7527-8fb0-c493cb1229d4'::uuid))
Index Searches: 1
Buffers: shared hit=6
Planning Time: 0.071 ms
Execution Time: 0.047 ms
(8 rows)
== For contrast, OFFSET pagination of the same page reads every skipped row
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=2832.42..2832.54 rows=51 width=67) (actual time=6.369..6.376 rows=51.00 loops=1)
Buffers: shared hit=495
-> Sort (cost=2807.41..2837.39 rows=11989 width=67) (actual time=5.728..6.109 rows=10052.00 loops=1)
Sort Key: id
Sort Method: quicksort Memory: 1978kB
Buffers: shared hit=495
-> Bitmap Heap Scan on messages (cost=585.33..1995.19 rows=11989 width=67) (actual time=0.717..2.712 rows=12000.00 loops=1)
Recheck Cond: (chat_id = '01a15e5f-93aa-7f38-9ff3-684f0d6ded77'::uuid)
Heap Blocks: exact=363
Buffers: shared hit=495
-> Bitmap Index Scan on messages_pkey (cost=0.00..582.34 rows=11989 width=0) (actual time=0.672..0.673 rows=12000.00 loops=1)
Index Cond: (chat_id = '01a15e5f-93aa-7f38-9ff3-684f0d6ded77'::uuid)
Index Searches: 1
Buffers: shared hit=132
Planning Time: 0.041 ms
Execution Time: 6.524 ms
(16 rows)
+17
View File
@@ -0,0 +1,17 @@
# Persistence: make test-persistence ACTION_SCRIPT=scripts/restart.cmd (scripts/restart.sh on Linux)
# date: 2026-10-21T12:09:10Z, commit: 7aa86d3 (branch solution/bpi2301-bakulin)
# host: Windows 11, Docker Desktop 28.5.1 (4 CPU, 4111327232 bytes RAM), Go go1.27.1, Python 3.13.1
== containers before
/mtusi-messenger-lab2 started=2026-10-21T12:10:18.43319842Z status=running
/mtusi2026lab2-postgres-1 started=2026-10-21T12:10:01.058712538Z status=running
/mtusi2026lab2-valkey-1 started=2026-10-21T12:10:01.069796526Z status=running
$ make test-persistence ACTION_SCRIPT=scripts/restart.cmd PYTHON=python
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
== containers after (every StartedAt changed: all three processes were restarted, volumes kept)
/mtusi-messenger-lab2 started=2026-10-21T12:10:34.891259448Z status=running
/mtusi2026lab2-postgres-1 started=2026-10-21T12:10:28.977896441Z status=running
/mtusi2026lab2-valkey-1 started=2026-10-21T12:10:28.995400471Z status=running
+12
View File
@@ -0,0 +1,12 @@
# Public checks: make check, make validate, make test
# date: 2026-10-21T12:09:10Z, commit: 7aa86d3 (branch solution/bpi2301-bakulin)
# host: Windows 11, Docker Desktop 28.5.1 (4 CPU, 4111327232 bytes RAM), Go go1.27.1, Python 3.13.1
$ make check PYTHON=python
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
$ make validate PYTHON=python # after pip install -r requirements-dev.txt
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
$ make test PYTHON=python
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
+50
View File
@@ -0,0 +1,50 @@
# Automated tests against real PostgreSQL and Valkey (testcontainers): go test -race -v
# date: 2026-10-21T12:09:10Z, commit: 7aa86d3 (branch solution/bpi2301-bakulin)
# host: Windows 11, Docker Desktop 28.5.1 (4 CPU, 4111327232 bytes RAM), Go go1.27.1, Python 3.13.1
# full suite: make unit (go test -race -count=1 ./...), 16 packages ok, 0 failed
--- PASS: TestRegisterUserShapeAndConflicts (0.18s)
--- PASS: TestConcurrentSendsProduceExactlyUniqueMessages (0.97s)
--- PASS: TestLoginReturnsBearerSession (0.14s)
--- PASS: TestLoginFailuresAreUniformBasicChallenges (0.26s)
--- PASS: TestLoginAcceptsColonAndUnicodePasswords (0.08s)
--- PASS: TestProtectedRoutesAcceptOnlyBearer (0.17s)
--- PASS: TestLogoutRevokesOnlyTheCurrentToken (0.16s)
--- PASS: TestSessionExpiresAfterTTL (1.29s)
--- PASS: TestValkeyOutageAnswers503 (3.75s)
--- PASS: TestPostgresOutageAnswers503 (3.83s)
--- PASS: TestHungPostgresAnswers503WithinTheRequestTimeout (5.34s)
ok messenger/internal/app 30.321s
--- PASS: TestLoginIssuesOpaqueTokenBackedByStoredSession (0.11s)
--- PASS: TestLoginWithBadCredentialsCreatesNoSession (0.21s)
--- PASS: TestAuthenticateResolvesTheOwner (0.15s)
--- PASS: TestLogoutRevokesOnlyThatSession (0.14s)
--- PASS: TestSessionExpiresAfterTTL (1.19s)
ok messenger/internal/auth 15.854s
ok messenger/internal/chat 12.655s [no tests to run]
--- PASS: TestConcurrentAppendsKeepEveryMessage (0.17s)
ok messenger/internal/chat/store 13.188s
ok messenger/internal/platform/apperr 1.627s [no tests to run]
ok messenger/internal/platform/config 1.627s [no tests to run]
--- PASS: TestUnavailableCauseIsLoggedButNotReturned (0.03s)
--- PASS: TestTimeoutBoundsTheRequestContext (0.05s)
ok messenger/internal/platform/httpx 2.942s
ok messenger/internal/platform/ident 1.656s [no tests to run]
ok messenger/internal/platform/pagination 1.778s [no tests to run]
ok messenger/internal/platform/password 1.641s [no tests to run]
--- PASS: TestMigrateIsRepeatable (0.02s)
--- PASS: TestPoolAppliesLimitsAndTimeouts (0.01s)
--- PASS: TestClassifyMarksUnreachableDatabaseAsUnavailable (0.00s)
--- PASS: TestClassifyRealConnectFailure (0.01s)
ok messenger/internal/platform/postgres 9.771s
ok messenger/internal/platform/valkey 2.782s [no tests to run]
ok messenger/internal/server 3.156s [no tests to run]
ok messenger/internal/testenv 2.767s [no tests to run]
--- PASS: TestRegisterStoresUserWithPasswordHash (0.08s)
--- PASS: TestRegisterRejectsInvalidInputAndStoresNothing (0.01s)
--- PASS: TestRegisterReportsDuplicateAsConflict (0.14s)
--- PASS: TestConcurrentRegistrationOfOneUsernameHasOneWinner (0.24s)
--- PASS: TestExistingIDsReturnsOnlyRegistered (0.16s)
--- PASS: TestAuthenticateChecksPassword (0.14s)
--- PASS: TestAuthenticateFailuresLookTheSame (0.32s)
ok messenger/internal/user 12.868s
+4 -2
View File
@@ -9,8 +9,10 @@ dir /data
# The append-only file already persists everything; RDB snapshots are off.
save ""
# Sessions are never evicted to free memory: a full store refuses new logins
# (503) instead of silently logging users out.
# Sessions are never evicted to free memory: once maxmemory is reached the
# store refuses new sessions (login answers 503) instead of silently logging
# users out. A session key takes about a hundred bytes.
maxmemory 256mb
maxmemory-policy noeviction
# requirepass comes from the compose secret, never from the repository.
+1 -1
View File
@@ -396,7 +396,7 @@ func TestMessagesEndToEnd(t *testing.T) {
first := ts.message(alice.token, room.ID, "Привет, мир 👋")
second := ts.message(bob.token, room.ID, "Сообщение Боба")
if first.SenderID != alice.ID || second.SenderID != bob.ID {
t.Fatalf("sender must come from X-User-Id: %+v %+v", first, second)
t.Fatalf("sender must come from the bearer token: %+v %+v", first, second)
}
if first.ChatID != room.ID || first.Text != "Привет, мир 👋" {
t.Fatalf("message = %+v", first)
+2
View File
@@ -54,6 +54,8 @@ func TestLoginFailuresAreUniformBasicChallenges(t *testing.T) {
"bearer scheme": {"Authorization": "Bearer " + strings.Repeat("A", 43)},
"not base64": {"Authorization": "Basic !!!"},
"no colon": {"Authorization": "Basic " + encoded("alice")},
"nul username": basic("a\x00b", testPassword),
"non-utf-8 name": basic("\xff\xfe", testPassword),
}
messages := map[string]string{}
for name, headers := range cases {
+3 -6
View File
@@ -2,19 +2,16 @@ package auth
import (
"context"
"errors"
"github.com/google/uuid"
)
// ErrSessionNotFound means the token is unknown, expired or revoked; the
// store cannot tell these apart, and the client must not either.
var ErrSessionNotFound = errors.New("session not found")
type Repository interface {
// Create stores the session until its absolute ExpiresAt.
Create(ctx context.Context, s Session) error
// UserID returns the owner of a live session or ErrSessionNotFound.
// UserID returns the owner of a live session, or ErrUnauthenticated when
// the token is unknown, expired or revoked: the store cannot tell these
// apart, and the client must not either.
UserID(ctx context.Context, tokenHash string) (uuid.UUID, error)
// Delete revokes the session; deleting a missing one is not an error.
Delete(ctx context.Context, tokenHash string) error
+4 -9
View File
@@ -2,7 +2,6 @@ package auth
import (
"context"
"errors"
"time"
"github.com/google/uuid"
@@ -53,15 +52,11 @@ func (s *Service) Login(ctx context.Context, username, password string) (Issued,
return Issued{Token: token, ExpiresAt: expiresAt, User: u}, nil
}
// Authenticate returns the owner of the token's live session. A store
// failure is returned as is, never as ErrUnauthenticated: an outage must not
// look like a bad token to the client.
// Authenticate returns the owner of the token's live session or
// ErrUnauthenticated. A store failure stays an unavailability, never
// ErrUnauthenticated: an outage must not look like a bad token to the client.
func (s *Service) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
id, err := s.sessions.UserID(ctx, HashToken(token))
if errors.Is(err, ErrSessionNotFound) {
return uuid.Nil, ErrUnauthenticated
}
return id, err
return s.sessions.UserID(ctx, HashToken(token))
}
func (s *Service) Logout(ctx context.Context, token string) error {
+4 -4
View File
@@ -27,10 +27,10 @@ func NewSessions(client *redis.Client) *Sessions {
return &Sessions{client: client}
}
// Create sets an absolute expiry (PXAT): a restart of the store replays it
// from the append-only file and does not extend the session.
// Create sets an absolute expiry (EXAT/PXAT): a restart of the store replays
// it from the append-only file and does not extend the session.
func (r *Sessions) Create(ctx context.Context, s auth.Session) error {
err := r.client.Do(ctx, "SET", keyPrefix+s.TokenHash, s.UserID.String(), "PXAT", s.ExpiresAt.UnixMilli()).Err()
err := r.client.SetArgs(ctx, keyPrefix+s.TokenHash, s.UserID.String(), redis.SetArgs{ExpireAt: s.ExpiresAt}).Err()
if err != nil {
return unavailable(err)
}
@@ -40,7 +40,7 @@ func (r *Sessions) Create(ctx context.Context, s auth.Session) error {
func (r *Sessions) UserID(ctx context.Context, tokenHash string) (uuid.UUID, error) {
raw, err := r.client.Get(ctx, keyPrefix+tokenHash).Result()
if errors.Is(err, redis.Nil) {
return uuid.Nil, auth.ErrSessionNotFound
return uuid.Nil, auth.ErrUnauthenticated
}
if err != nil {
return uuid.Nil, unavailable(err)
+4
View File
@@ -46,6 +46,10 @@ func NewChat(id uuid.UUID, title string) (Chat, error) {
if utf8.RuneCountInString(title) > MaxTitleCodePoints {
return Chat{}, apperr.Invalid(fmt.Sprintf("title must be at most %d characters", MaxTitleCodePoints))
}
// PostgreSQL text cannot hold U+0000.
if strings.ContainsRune(title, 0) {
return Chat{}, apperr.Invalid("title must not contain the NUL character")
}
return Chat{ID: id, Title: title, CreatedAt: ident.TimeOf(id)}, nil
}
+3 -1
View File
@@ -23,7 +23,9 @@ func TestNewChatDerivesCreatedAtFromID(t *testing.T) {
}
func TestNewChatValidatesTitle(t *testing.T) {
for _, title := range []string{"", " ", strings.Repeat("я", 101)} {
// PostgreSQL text cannot hold U+0000, so a title with it is invalid input,
// not a storage failure.
for _, title := range []string{"", " ", strings.Repeat("я", 101), "nul\x00inside"} {
_, err := chat.NewChat(ident.New(), title)
if apperr.KindOf(err) != apperr.KindInvalid {
t.Errorf("title %q must be rejected as invalid, got %v", title, err)
+4
View File
@@ -30,6 +30,10 @@ func NewMessage(id, chatID, senderID uuid.UUID, text string) (Message, error) {
if utf8.RuneCountInString(text) > MaxTextCodePoints {
return Message{}, apperr.Invalid(fmt.Sprintf("text must be at most %d characters", MaxTextCodePoints))
}
// PostgreSQL text cannot hold U+0000.
if strings.ContainsRune(text, 0) {
return Message{}, apperr.Invalid("text must not contain the NUL character")
}
return Message{
ID: id,
ChatID: chatID,
+1 -1
View File
@@ -28,7 +28,7 @@ func TestNewMessageValidatesTextByCodePoints(t *testing.T) {
if _, err := chat.NewMessage(ident.New(), chatID, alice, strings.Repeat("я", 4000)); err != nil {
t.Errorf("4000 code points must be accepted: %v", err)
}
for _, text := range []string{"", " ", "\n\t ", strings.Repeat("я", 4001)} {
for _, text := range []string{"", " ", "\n\t ", strings.Repeat("я", 4001), "nul\x00inside"} {
_, err := chat.NewMessage(ident.New(), chatID, alice, text)
if apperr.KindOf(err) != apperr.KindInvalid {
t.Errorf("text %q must be rejected as invalid, got %v", text, err)
+4 -8
View File
@@ -31,10 +31,6 @@ func NewChats(pool *pgxpool.Pool) *Chats {
return &Chats{pool: pool}
}
// chatWithMembers selects the projection from a chats row aliased c.
const chatWithMembers = `c.id, c.title, c.created_at,
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)`
func (r *Chats) Create(ctx context.Context, c chat.Chat, memberIDs []uuid.UUID) error {
return postgres.Classify(pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx,
@@ -53,7 +49,8 @@ func (r *Chats) Create(ctx context.Context, c chat.Chat, memberIDs []uuid.UUID)
func (r *Chats) GetForMember(ctx context.Context, chatID, userID uuid.UUID) (chat.ChatWithMembers, error) {
row := r.pool.QueryRow(ctx, `
SELECT `+chatWithMembers+`
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
FROM chats c
WHERE c.id = $1
AND EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
@@ -81,7 +78,8 @@ func (r *Chats) IsMember(ctx context.Context, chatID, userID uuid.UUID) (bool, e
func (r *Chats) ListByMember(ctx context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]chat.ChatWithMembers, error) {
rows, err := r.pool.Query(ctx, `
SELECT `+chatWithMembers+`
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
FROM chat_members own
JOIN chats c ON c.id = own.chat_id
WHERE own.user_id = $1
@@ -106,7 +104,6 @@ func scanChat(row pgx.Row) (chat.ChatWithMembers, error) {
if err := row.Scan(&c.ID, &c.Title, &c.CreatedAt, &c.MemberIDs); err != nil {
return chat.ChatWithMembers{}, err
}
c.CreatedAt = c.CreatedAt.UTC()
return c, nil
}
@@ -147,7 +144,6 @@ func (r *Messages) ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid
messages, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (chat.Message, error) {
var m chat.Message
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
m.CreatedAt = m.CreatedAt.UTC()
return m, err
})
if err != nil {
+22
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
@@ -307,6 +308,27 @@ func TestWithUserWithoutIdentityIsAWiringError(t *testing.T) {
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
}
// A 5xx tells the client only the safe message; the operator must still see
// why the dependency failed, so the cause goes to the log.
func TestUnavailableCauseIsLoggedButNotReturned(t *testing.T) {
logs := &bytes.Buffer{}
e := newEngine(t, logs)
e.GET("/down", func(c *gin.Context) {
cause := errors.New("dial tcp 10.0.0.7:5432: connect: connection refused")
httpx.Error(c, fmt.Errorf("select user: %w", apperr.Wrap(apperr.KindUnavailable, "database unavailable", cause)))
})
rec, eb := do(t, e, http.MethodGet, "/down", "", nil)
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
// Neither the cause nor the wrapping context of internal operations
// ("select user: ...") may reach the client.
if eb.Error.Message != "database unavailable" {
t.Fatalf("client message = %q, want only the application message", eb.Error.Message)
}
if !strings.Contains(logs.String(), "connection refused") || !strings.Contains(logs.String(), eb.Error.RequestID) {
t.Fatalf("log must carry the cause and the request id, got:\n%s", logs.String())
}
}
// Everything below Timeout sees one deadline, so waiting on a dependency
// ends with the request instead of holding the client.
func TestTimeoutBoundsTheRequestContext(t *testing.T) {
+1 -3
View File
@@ -10,9 +10,7 @@ import (
const keyUserID = "messenger.user_id"
// SetUserID records the authenticated caller for the handlers behind the
// authentication middleware and for the access log. It lives here rather
// than in the auth package because the access log needs it and the business
// modules must not depend on auth.
// authentication middleware and for the access log.
func SetUserID(c *gin.Context, id uuid.UUID) {
c.Set(keyUserID, id)
}
+19 -3
View File
@@ -1,6 +1,7 @@
package httpx
import (
"errors"
"net/http"
"time"
@@ -52,15 +53,30 @@ func Fail(c *gin.Context, status int, code, message string) {
// Error maps an application error to its status. Anything that is not an
// application error is logged with its text and reported as an opaque 500,
// so internal details never reach the client.
// so internal details never reach the client. An application error shows the
// client only its own message, never the context it was wrapped in on the
// way up; when it is answered with a 5xx (a dependency outage) the full
// chain and the cause go to the log for the operator.
func Error(c *gin.Context, err error) {
mapped, known := kinds[apperr.KindOf(err)]
appErr, isApp := errors.AsType[*apperr.Error](err)
var mapped statusCode
known := false
if isApp {
mapped, known = kinds[appErr.Kind]
}
if !known {
logger(c).Error("request failed", "request_id", RequestID(c), "error", err.Error())
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
return
}
Fail(c, mapped.status, mapped.code, err.Error())
if mapped.status >= http.StatusInternalServerError {
attrs := []any{"request_id", RequestID(c), "error", err.Error()}
if appErr.Cause != nil {
attrs = append(attrs, "cause", appErr.Cause.Error())
}
logger(c).Error("request failed", attrs...)
}
Fail(c, mapped.status, mapped.code, appErr.Message)
}
// Timestamp renders RFC 3339 UTC with a fixed millisecond width: Python 3.9
+1 -1
View File
@@ -54,7 +54,7 @@ func Verify(encoded, plain string) (bool, error) {
var memory, time uint32
var parallelism uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &parallelism); err != nil ||
memory == 0 || time == 0 || parallelism == 0 || params(memory, time, parallelism) != parts[3] {
memory == 0 || time == 0 || parallelism == 0 {
return false, ErrMalformed
}
salt, err := b64.DecodeString(parts[4])
+37 -10
View File
@@ -14,7 +14,9 @@ import (
"strconv"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
@@ -26,7 +28,7 @@ import (
const (
maxConns = 10
connectTimeout = 3 * time.Second
connectTimeout = time.Second
statementTimeout = 5 * time.Second
idleInTxTimeout = 10 * time.Second
)
@@ -40,8 +42,27 @@ func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
}
cfg.MaxConns = maxConns
cfg.ConnConfig.ConnectTimeout = connectTimeout
// Unlike net.Dialer, pgx resolves the host before ConnectTimeout starts.
// Docker DNS takes seconds to give up on a stopped container: unbounded,
// every request would wait out its deadline and log only "context
// deadline exceeded" instead of the failed lookup.
cfg.ConnConfig.LookupFunc = func(ctx context.Context, host string) ([]string, error) {
ctx, cancel := context.WithTimeout(ctx, connectTimeout)
defer cancel()
return net.DefaultResolver.LookupHost(ctx, host)
}
cfg.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(statementTimeout.Milliseconds(), 10)
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = strconv.FormatInt(idleInTxTimeout.Milliseconds(), 10)
// The application keeps every time in UTC; pgx would otherwise scan
// timestamptz into time.Local.
cfg.AfterConnect = func(_ context.Context, conn *pgx.Conn) error {
conn.TypeMap().RegisterType(&pgtype.Type{
Name: "timestamptz",
OID: pgtype.TimestamptzOID,
Codec: &pgtype.TimestamptzCodec{ScanLocation: time.UTC},
})
return nil
}
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
@@ -54,24 +75,30 @@ func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
return pool, nil
}
// Migrate applies pending migrations. A session advisory lock serialises
// concurrent starts, so several API replicas may call it at once; applied
// versions are recorded, which makes a repeated run a no-op.
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
// Migrate applies pending migrations and returns the versions it applied. A
// session advisory lock serialises concurrent starts, so several API
// replicas may call it at once; applied versions are recorded, which makes a
// repeated run a no-op.
func Migrate(ctx context.Context, pool *pgxpool.Pool) ([]int64, error) {
db := stdlib.OpenDBFromPool(pool)
defer db.Close()
locker, err := lock.NewPostgresSessionLocker()
if err != nil {
return fmt.Errorf("migration lock: %w", err)
return nil, fmt.Errorf("migration lock: %w", err)
}
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker))
if err != nil {
return fmt.Errorf("load migrations: %w", err)
return nil, fmt.Errorf("load migrations: %w", err)
}
if _, err := provider.Up(ctx); err != nil {
return fmt.Errorf("apply migrations: %w", err)
results, err := provider.Up(ctx)
if err != nil {
return nil, fmt.Errorf("apply migrations: %w", err)
}
return nil
applied := make([]int64, 0, len(results))
for _, r := range results {
applied = append(applied, r.Source.Version)
}
return applied, nil
}
// Classify marks a failure to reach the database as apperr.KindUnavailable,
+19 -1
View File
@@ -8,6 +8,7 @@ import (
"net"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgconn"
@@ -30,11 +31,25 @@ func TestMain(m *testing.M) {
os.Exit(code)
}
func TestPoolScansTimestamptzInUTC(t *testing.T) {
var got time.Time
if err := db.Pool.QueryRow(context.Background(), `SELECT now()`).Scan(&got); err != nil {
t.Fatal(err)
}
if got.Location() != time.UTC {
t.Fatalf("timestamptz scanned in %v, want UTC", got.Location())
}
}
func TestMigrateIsRepeatable(t *testing.T) {
ctx := context.Background()
if err := postgres.Migrate(ctx, db.Pool); err != nil {
applied, err := postgres.Migrate(ctx, db.Pool)
if err != nil {
t.Fatalf("second migrate: %v", err)
}
if len(applied) != 0 {
t.Fatalf("second migrate applied %v, want nothing", applied)
}
var version int64
if err := db.Pool.QueryRow(ctx, `SELECT max(version_id) FROM goose_db_version`).Scan(&version); err != nil {
t.Fatal(err)
@@ -57,6 +72,9 @@ func TestPoolAppliesLimitsAndTimeouts(t *testing.T) {
if got := db.Pool.Config().MaxConns; got != 10 {
t.Fatalf("MaxConns = %d, want 10", got)
}
if got := db.Pool.Config().ConnConfig.ConnectTimeout; got != time.Second {
t.Fatalf("ConnectTimeout = %v, want 1s", got)
}
ctx := context.Background()
for setting, want := range map[string]string{
"statement_timeout": "5s",
+12 -7
View File
@@ -1,9 +1,12 @@
// Package valkey connects to the Valkey session store.
//
// Timeouts are constants: every authenticated request reads a session, so
// they bound how long a request can wait when the store is slow. Retries are
// disabled for the same reason: a request that cannot reach the store fails
// fast with 503 instead of waiting through a backoff.
// they bound how long a request can wait when the store is slow. Command
// retries are disabled and a connection is dialled once for the same reason:
// a request that cannot reach the store fails fast with 503 instead of
// waiting through a backoff. On the compose stand Docker DNS takes seconds
// to give up on a stopped container, so one dial attempt is already bounded
// only by dialTimeout.
package valkey
import (
@@ -16,10 +19,11 @@ import (
)
const (
dialTimeout = 2 * time.Second
ioTimeout = time.Second
poolSize = 10
noRetries = -1
dialTimeout = time.Second
ioTimeout = time.Second
poolSize = 10
noRetries = -1
singleAttempt = 1
)
// NewClient connects to url (redis:// scheme) and pings the server. Errors
@@ -34,6 +38,7 @@ func NewClient(ctx context.Context, url string) (*redis.Client, error) {
opts.WriteTimeout = ioTimeout
opts.PoolSize = poolSize
opts.MaxRetries = noRetries
opts.DialerRetries = singleAttempt
client := redis.NewClient(opts)
if err := client.Ping(ctx).Err(); err != nil {
+8 -2
View File
@@ -24,8 +24,14 @@ func TestNewClientPingsAndBoundsWaiting(t *testing.T) {
}
defer client.Close()
opts := client.Options()
if opts.DialTimeout != 2*time.Second || opts.ReadTimeout != time.Second || opts.WriteTimeout != time.Second {
t.Fatalf("timeouts = %v/%v/%v, want 2s/1s/1s", opts.DialTimeout, opts.ReadTimeout, opts.WriteTimeout)
if opts.DialTimeout != time.Second || opts.ReadTimeout != time.Second || opts.WriteTimeout != time.Second {
t.Fatalf("timeouts = %v/%v/%v, want 1s each", opts.DialTimeout, opts.ReadTimeout, opts.WriteTimeout)
}
// go-redis dials up to five times by default; with Docker DNS taking
// seconds to give up on a stopped container that alone would exceed the
// request deadline.
if opts.DialerRetries != 1 {
t.Fatalf("DialerRetries = %d, want a single dial attempt", opts.DialerRetries)
}
// go-redis stores the requested -1 ("no retries") as 0 after init; its
// default would be 3.
+5 -4
View File
@@ -19,6 +19,7 @@ import (
tcvalkey "github.com/testcontainers/testcontainers-go/modules/valkey"
"messenger/internal/platform/postgres"
"messenger/internal/platform/valkey"
)
const (
@@ -66,7 +67,7 @@ func StartPostgres(ctx context.Context) (*DB, error) {
db.Close()
return nil, err
}
if err := postgres.Migrate(ctx, db.Pool); err != nil {
if _, err := postgres.Migrate(ctx, db.Pool); err != nil {
db.Close()
return nil, err
}
@@ -150,12 +151,12 @@ func StartValkey(ctx context.Context) (*KV, error) {
kv.Close()
return nil, fmt.Errorf("valkey address: %w", err)
}
opts, err := redis.ParseURL(kv.URL)
// The production client, so outage tests see its fail-fast settings.
kv.Client, err = valkey.NewClient(ctx, kv.URL)
if err != nil {
kv.Close()
return nil, fmt.Errorf("valkey url: %w", err)
return nil, err
}
kv.Client = redis.NewClient(opts)
return kv, nil
}
+7
View File
@@ -45,7 +45,14 @@ var dummyHash = sync.OnceValue(func() string {
// Authenticate returns the user whose password matches, or
// ErrInvalidCredentials for an unknown username and a wrong password alike.
// The username comes straight from the Basic header, so one that cannot
// exist (including NUL or invalid UTF-8, which the database would reject)
// is answered without a query, but after the same KDF work.
func (s *Service) Authenticate(ctx context.Context, username, plain string) (User, error) {
if !usernamePattern.MatchString(username) {
_, _ = password.Verify(dummyHash(), plain)
return User{}, ErrInvalidCredentials
}
u, err := s.repo.GetByUsername(ctx, username)
if errors.Is(err, ErrNotFound) {
_, _ = password.Verify(dummyHash(), plain)
+7 -1
View File
@@ -172,7 +172,13 @@ func TestAuthenticateFailuresLookTheSame(t *testing.T) {
}
_, wrong := svc.Authenticate(ctx, "alice", pw+"!")
_, unknown := svc.Authenticate(ctx, "nobody", pw)
for name, err := range map[string]error{"wrong password": wrong, "unknown user": unknown} {
// Basic credentials are client bytes: a username the database cannot
// even compare must still be a plain credential failure.
_, nul := svc.Authenticate(ctx, "a\x00b", pw)
_, notUTF8 := svc.Authenticate(ctx, "\xff\xfe", pw)
for name, err := range map[string]error{
"wrong password": wrong, "unknown user": unknown, "nul username": nul, "invalid utf-8 username": notUTF8,
} {
if !errors.Is(err, user.ErrInvalidCredentials) || apperr.KindOf(err) != apperr.KindUnauthorized {
t.Errorf("%s: err = %v, want ErrInvalidCredentials", name, err)
}
+3 -6
View File
@@ -16,8 +16,6 @@ import (
"messenger/internal/user"
)
const userColumns = `id, username, display_name, password_hash, created_at`
type Users struct {
pool *pgxpool.Pool
}
@@ -32,7 +30,7 @@ func NewUsers(pool *pgxpool.Pool) *Users {
// concurrent registrations of one username cannot both succeed.
func (r *Users) Create(ctx context.Context, u user.User) error {
_, err := r.pool.Exec(ctx,
`INSERT INTO users (`+userColumns+`) VALUES ($1, $2, $3, $4, $5)`,
`INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
u.ID, u.Username, u.DisplayName, u.PasswordHash, u.CreatedAt)
if postgres.IsUniqueViolation(err, "users_username_key") {
return user.ErrUsernameTaken
@@ -44,11 +42,11 @@ func (r *Users) Create(ctx context.Context, u user.User) error {
}
func (r *Users) GetByID(ctx context.Context, id uuid.UUID) (user.User, error) {
return r.one(ctx, `SELECT `+userColumns+` FROM users WHERE id = $1`, id)
return r.one(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1`, id)
}
func (r *Users) GetByUsername(ctx context.Context, username string) (user.User, error) {
return r.one(ctx, `SELECT `+userColumns+` FROM users WHERE username = $1`, username)
return r.one(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1`, username)
}
func (r *Users) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
@@ -72,6 +70,5 @@ func (r *Users) one(ctx context.Context, query string, arg any) (user.User, erro
if err != nil {
return user.User{}, fmt.Errorf("select user: %w", postgres.Classify(err))
}
u.CreatedAt = u.CreatedAt.UTC()
return u, nil
}
+4
View File
@@ -51,6 +51,10 @@ func New(id uuid.UUID, username, displayName string) (User, error) {
if utf8.RuneCountInString(displayName) > MaxDisplayNameCodePoints {
return User{}, apperr.Invalid(fmt.Sprintf("display_name must be at most %d characters", MaxDisplayNameCodePoints))
}
// PostgreSQL text cannot hold U+0000.
if strings.ContainsRune(displayName, 0) {
return User{}, apperr.Invalid("display_name must not contain the NUL character")
}
return User{
ID: id,
Username: username,
+1 -1
View File
@@ -68,7 +68,7 @@ func TestNewValidatesDisplayNameByCodePoints(t *testing.T) {
t.Errorf("display_name %q must be accepted: %v", name, err)
}
}
invalid := []string{"", " ", "\t\n", strings.Repeat("я", 101)}
invalid := []string{"", " ", "\t\n", strings.Repeat("я", 101), "nul\x00inside"}
for _, name := range invalid {
_, err := user.New(ident.New(), "alice", name)
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "display_name") {
+7 -5
View File
@@ -22,17 +22,19 @@ CREATE TABLE chat_members (
-- Lists the chats of one user in (created_at, id) order: chat ids are UUIDv7.
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
-- The key is (chat_id, id) and serves the history query directly:
-- WHERE chat_id = $1 AND id > $2 ORDER BY id LIMIT $3. Nothing looks a
-- message up by id alone, and a separate index on id would only cost writes
-- and tempt the planner into scanning every chat's messages in id order.
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id),
id uuid NOT NULL,
sender_id uuid NOT NULL REFERENCES users (id),
text text NOT NULL,
created_at timestamptz NOT NULL
created_at timestamptz NOT NULL,
PRIMARY KEY (chat_id, id)
);
-- Keyset pagination of one chat's history: WHERE chat_id = $1 AND id > $2 ORDER BY id.
CREATE INDEX messages_chat_id_idx ON messages (chat_id, id);
-- +goose Down
DROP TABLE messages;
DROP TABLE chat_members;
+75
View File
@@ -0,0 +1,75 @@
-- EXPLAIN evidence for the message history query (make explain).
--
-- Everything runs in one transaction that is rolled back: it seeds 12 000
-- messages in one chat and 90 000 in 300 other chats, so the plan is measured
-- on a realistic volume without leaving data on the stand. The PREPARE text
-- is the statement of Messages.ListByChat in internal/chat/store/postgres.go;
-- keep them identical.
\set ON_ERROR_STOP on
\pset pager off
BEGIN;
SELECT uuidv7() AS author \gset
SELECT uuidv7() AS big_chat \gset
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (:'author', 'explain_' || substr(md5(random()::text), 1, 12), 'EXPLAIN', 'not-a-password-hash',
uuid_extract_timestamp(:'author'));
CREATE TEMP TABLE noise_chats ON COMMIT DROP AS
SELECT uuidv7() AS id FROM generate_series(1, 300);
INSERT INTO chats (id, title, created_at)
SELECT :'big_chat'::uuid, 'explain: big chat', uuid_extract_timestamp(:'big_chat')
UNION ALL
SELECT id, 'explain: other chat', uuid_extract_timestamp(id) FROM noise_chats;
INSERT INTO chat_members (chat_id, user_id)
SELECT id, :'author' FROM chats WHERE title LIKE 'explain:%';
-- Rows are inserted ordered by n, so the messages of all chats interleave in
-- the heap as they would under real traffic; ids stay increasing per chat.
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT id, chat_id, :'author', 'message ' || n, uuid_extract_timestamp(id)
FROM (
SELECT uuidv7() AS id, chat_id, n
FROM (
SELECT :'big_chat'::uuid AS chat_id, n FROM generate_series(1, 12000) AS n
UNION ALL
SELECT c.id, n FROM noise_chats AS c, generate_series(1, 300) AS n
) AS planned
ORDER BY n
) AS generated;
ANALYZE users, chats, chat_members, messages;
SELECT (SELECT count(*) FROM messages WHERE chat_id = :'big_chat') AS big_chat_messages,
(SELECT count(*) FROM messages) AS all_messages;
PREPARE history(uuid, uuid, int) AS
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
AND id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
ORDER BY id
LIMIT $3;
\echo
\echo == First page: no cursor, limit 50 (+1 row that tells whether a next page exists)
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history(:'big_chat', NULL, 51);
SELECT id AS deep_cursor FROM messages WHERE chat_id = :'big_chat' ORDER BY id OFFSET 10000 LIMIT 1 \gset
\echo
\echo == Deep page: cursor after the 10 001st message of the chat
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history(:'big_chat', :'deep_cursor', 51);
\echo
\echo == For contrast, OFFSET pagination of the same page reads every skipped row
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :'big_chat'
ORDER BY id
OFFSET 10001 LIMIT 51;
ROLLBACK;