Complete lab2 grade 4 implementation and report
This commit is contained in:
@@ -11,3 +11,4 @@ DATABASE_PASSWORD_FILE=/run/secrets/postgres_password
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
REDIS_ADDR=redis:6379
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
## Лабораторная 2
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
Автор / группа: Ситникова Дарья Евгеньевна / БВТ2303.
|
||||
Целевая оценка (3/4/5): 4.
|
||||
Трек 5, если заявлен: не заявлен.
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
Что реализовано и что перенесено: из lab1 перенесены Go API, собственные тесты и Dockerfile. Добавлены PostgreSQL, миграции, транзакции, Argon2id, Bearer-сессии с expiry/logout и Redis-кэш профилей с TTL 60 с. Lab1 не изменялась.
|
||||
|
||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [ ] Контракт и публичные тесты не ослаблены.
|
||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
Команды запуска из чистого clone (PowerShell, из корня репозитория):
|
||||
|
||||
```powershell
|
||||
./scripts/init-local.ps1
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait api
|
||||
make check test PYTHON=py
|
||||
py tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080
|
||||
```
|
||||
|
||||
Результаты проверок и ссылка на REPORT.md: make check/test, persistence, гонка username, rollback, expiry/logout, неверный пароль, отказы Redis/БД и EXPLAIN на 12 000 сообщениях — PASS. Доказательства: [REPORT.md](REPORT.md).
|
||||
|
||||
Ограничения / известные ошибки: локальный стенд без HA/backup и TLS. Linux-hook, удалённый CI и git clone после финального коммита отдельно не проверены. Проверен запуск отдельной копии с пустой БД. Истёкшие сессии автоматически не удаляются; доступ по ним запрещён.
|
||||
|
||||
Источники и использование ИИ: задание, собственная lab1, документация PostgreSQL, pgxpool, Redis, RFC 9106. Codex использован для реализации, объяснений и проверок; ссылки в отчёте.
|
||||
|
||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [x] Контракт и публичные тесты не ослаблены.
|
||||
- [x] make check и make test выполнены; приложен реальный вывод.
|
||||
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
name: Application checks
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
application:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Initialize local configuration
|
||||
shell: pwsh
|
||||
run: ./scripts/init-local.ps1
|
||||
- run: docker compose --env-file .env up -d --build --wait api
|
||||
- run: make check test PYTHON=python
|
||||
- run: make test-persistence PYTHON=python ACTION_SCRIPT=scripts/restart.sh
|
||||
- name: Stop test stack
|
||||
if: always()
|
||||
run: docker compose down
|
||||
@@ -1,133 +1,104 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- **Автор:** Ситникова Дарья Евгеньевна, БВТ2303.
|
||||
- **Целевая оценка:** 4; Redis и эксперименты уровня 4 ещё в работе.
|
||||
- **Ветка решения:** `solution/bvt2303-sitnikova`.
|
||||
- **Commit/PR:** будут указаны после публикации.
|
||||
- **Статус:** публичные smoke и persistence пройдены на Windows; чистый clone отдельно не проверен.
|
||||
- **Автор / группа:** Ситникова Дарья Евгеньевна / БВТ2303.
|
||||
- **Целевая оценка:** 4; трек 5 не заявлен.
|
||||
- **Ветка:** solution/bvt2303-sitnikova.
|
||||
- **Дата проверок:** 09.10.2026; контрольные check/test, Compose, go test/vet — 10.10.2026.
|
||||
|
||||
## Запуск
|
||||
|
||||
Нужны Docker Desktop с Linux-контейнерами, PowerShell и Python 3.9+. Команды из корня lab2:
|
||||
Нужны Docker Desktop с Linux-контейнерами, PowerShell и Python 3.9+. Команды выполняются из корня lab2 после clone и перехода в ветку решения:
|
||||
|
||||
```powershell
|
||||
./scripts/init-local.ps1
|
||||
# .env необязателен: Compose использует значения по умолчанию.
|
||||
docker compose config --quiet
|
||||
docker compose up -d --build --wait api
|
||||
py tests/smoke.py --base-url http://localhost:8080
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait api
|
||||
make check test PYTHON=py
|
||||
py tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080
|
||||
```
|
||||
|
||||
| Компонент | Настройка |
|
||||
Без make: `py scripts/check_contract.py` и `py tests/smoke.py --base-url http://localhost:8080`.
|
||||
|
||||
Bootstrap копирует `.env.example` в локальный `.env`, если его нет, и генерирует пароль в `secrets/postgres_password.txt`. Существующие файлы сохраняются. `.env` задаёт `SESSION_TTL_SECONDS=3600`; пароль передаётся через Compose secrets. `.env`, secrets и данные исключены из Git. Изменение файла пароля не меняет пароль роли в уже созданной БД.
|
||||
|
||||
| Компонент | Конфигурация |
|
||||
| --- | --- |
|
||||
| API | Go 1.26.3; сборка в Docker; непривилегированный пользователь; localhost:8080 |
|
||||
| PostgreSQL | `postgres:17.9-bookworm`; внутренний порт 5432 |
|
||||
| Миграции | Одноразовый сервис `migrate`; API ждёт успешного завершения |
|
||||
| Данные | Именованный volume `postgres_data` → `/var/lib/postgresql/data` |
|
||||
| Пароль БД | `scripts/init-local.ps1` создаёт `secrets/postgres_password.txt`; повторно не перезаписывает |
|
||||
| Конфигурация | `DATABASE_PASSWORD_FILE`, `SESSION_TTL_SECONDS` (по умолчанию 3600) |
|
||||
| API | Go 1.26.3; Docker build выполняет go vet/test/build; непривилегированный пользователь; 127.0.0.1:8080 |
|
||||
| PostgreSQL | postgres:17.9-bookworm; postgres:5432; db/user=messenger; именованный volume postgres_data |
|
||||
| Redis | redis:7.4.11-alpine; redis:6379; без публикации порта; 64mb, allkeys-lru; /data в tmpfs |
|
||||
| Миграции | Одноразовый сервис migrate; API ждёт его успешного завершения и готовности БД |
|
||||
| Health | live проверяет процесс; ready — доступность PostgreSQL; Redis не является критической зависимостью |
|
||||
|
||||
`secrets/`, `.env` и данные исключены из Git. Изменение файла пароля не меняет пароль уже созданной роли БД. `APP_HOST`/`APP_PORT` поддерживаются Go, но Compose публикует фиксированный порт 8080. Остальные переменные исходного `.env.example` пока не используются.
|
||||
Адрес PostgreSQL задан в коде; `DATABASE_PASSWORD_FILE` и `REDIS_ADDR` — в Compose. Остальные предложенные skeleton настройки (`APP_ENV`, `DATABASE_URL_FILE`, `CACHE_URL_FILE`, `SESSION_STORE`) не используются. Go поддерживает APP_HOST/APP_PORT, но Compose использует defaults и фиксированный порт.
|
||||
|
||||
- Остановка с сохранением данных: `docker compose down`.
|
||||
- **Намеренное удаление учебной БД:** `docker compose down --volumes`. Не использовать в проверках сохранности.
|
||||
- Linux/macOS: `chmod +x scripts/restart.sh`, затем `make test-persistence ACTION_SCRIPT=scripts/restart.sh`. Linux-hook отдельно не запускался; executable bit нужно сохранить в Git.
|
||||
Остановка с сохранением данных: `docker compose down`. В проверках сохранности `down --volumes` не применяется. Linux-hook: `make test-persistence ACTION_SCRIPT=scripts/restart.sh`; executable bit сохранён в Git, запуск hook на Linux отдельно не проверен.
|
||||
|
||||
### Дополнительные проверки
|
||||
## Реализация
|
||||
|
||||
```powershell
|
||||
py student-tests/registration.py
|
||||
py student-tests/sessions.py
|
||||
py student-tests/chat-rollback.py
|
||||
go test ./...
|
||||
go vet ./...
|
||||
```
|
||||
|
||||
Проверка expiry с восстановлением прежней настройки:
|
||||
|
||||
```powershell
|
||||
$previousSessionTTL = $env:SESSION_TTL_SECONDS
|
||||
try {
|
||||
$env:SESSION_TTL_SECONDS = '2'
|
||||
docker compose up -d --wait api
|
||||
if ($LASTEXITCODE -ne 0) { throw 'API did not start' }
|
||||
py student-tests/sessions.py --expiry
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Expiry test failed' }
|
||||
}
|
||||
finally {
|
||||
if ($null -eq $previousSessionTTL) {
|
||||
Remove-Item Env:SESSION_TTL_SECONDS -ErrorAction SilentlyContinue
|
||||
} else {
|
||||
$env:SESSION_TTL_SECONDS = $previousSessionTTL
|
||||
}
|
||||
docker compose up -d --wait api
|
||||
}
|
||||
```
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
**Клиент → Go API → PostgreSQL.** Из lab1 перенесены исходники, собственные тесты, go.mod и Dockerfile. Lab1 не изменялась; контракт и публичные тесты lab2 сохранены. Старое хранилище в памяти оставлено для регрессионных тестов, сервер использует PostgreSQL.
|
||||
**Клиент → Go API → PostgreSQL + Redis-кэш профилей.** Из lab1 перенесены исходники, собственные тесты, go.mod и Dockerfile. Lab1 не изменялась. Контракт, README задания и публичные tests lab2 сохранены. Старое хранилище в памяти используется только регрессионными тестами.
|
||||
|
||||
| Область | Решение |
|
||||
| --- | --- |
|
||||
| Схема | users, chats, chat_members, messages, sessions; PK, FK, UNIQUE(username), CHECK |
|
||||
| Миграции | Версия в schema_migrations; SQL и запись версии в одной транзакции; advisory lock; повторный запуск пропускает версию |
|
||||
| Пароли | Библиотечный Argon2id: 64 MiB, 3 прохода, параллелизм 4, соль 16 байт, результат 32 байта; 12–128 Unicode code points |
|
||||
| Нагрузка KDF | Общие 2 слота для регистрации и входа; начатое вычисление не прерывается контекстом |
|
||||
| Сессии | Basic только для входа; случайный токен 256 бит; в БД SHA-256 токена и expires_at; защищённые запросы принимают Bearer |
|
||||
| Expiry/logout | Время проверяется в БД; срок не продлевается; logout удаляет текущую сессию; неизвестный/истёкший/отозванный токен — 401 |
|
||||
| Доступ | X-User-Id игнорируется; проверяется членство; чужой/отсутствующий чат — 404 |
|
||||
| Транзакции | Создание чата и участников атомарно; сообщение подтверждается после COMMIT; конфликт username — 409 |
|
||||
| История | Keyset по (created_at,id), индекс (chat_id,created_at,id), LIMIT limit+1; курсор привязан к чату |
|
||||
| Конкурентная запись | FOR UPDATE строки чата; время нового сообщения ≥ последнего + 1 мкс; записи одного чата последовательны |
|
||||
| Пул и таймауты | До 10 соединений; connect 3 с; statement 3 с; lock 2 с; SQL-контексты до 3 с; регистрация/вход до 5 с, кроме непрерываемого KDF |
|
||||
| Health | live — процесс; ready — Ping PostgreSQL; версия схемы в readiness не проверяется |
|
||||
| Ошибки | Ошибки БД обобщаются в 503; пароли, токены и детали SQL не выводятся |
|
||||
| Миграции | schema_migrations; DDL и версия в одной транзакции; advisory lock; повтор пропускает применённую версию |
|
||||
| Пароли | Argon2id: 64 MiB, 3 прохода, параллелизм 4, соль 16 байт, результат 32 байта; 12–128 Unicode code points; общий лимит 2 KDF-операции |
|
||||
| Сессии | Basic только при входе; случайный Bearer-токен 256 бит; в PostgreSQL SHA-256 токена, user_id и expires_at |
|
||||
| Expiry/logout | Время проверяет БД; TTL не продлевается; logout удаляет сессию; недействительный токен → 401 |
|
||||
| Доступ | X-User-Id игнорируется; членство проверяется отдельно; чужой/отсутствующий чат → 404 |
|
||||
| SQL и транзакции | Параметры $1…; чат и участники атомарны; сообщение подтверждается после COMMIT; конфликт username → 409 |
|
||||
| Пул и таймауты | 10 соединений PostgreSQL; connect 3 с, statement 3 с, lock 2 с; SQL-контексты до 3 с, вход/регистрация до 5 с; начатый KDF не прерывается |
|
||||
| История | Keyset (created_at,id); индекс (chat_id,created_at,id); limit+1; курсор привязан к чату |
|
||||
| Конкурентная запись | FOR UPDATE строки чата; время сообщения ≥ предыдущего + 1 мкс; запись внутри чата последовательна |
|
||||
| Redis | profile:v1:<UUID> → публичный User; TTL 60 с без продления при чтении; источник истины — PostgreSQL |
|
||||
| Инвалидация | Профили через API не изменяются; TTL/вытеснение; промах или повреждённая запись → БД и заполнение кэша |
|
||||
| Отказы | Потеря Redis → чтение профиля из БД; потеря PostgreSQL → 503; кэш не заменяет проверку сессии |
|
||||
| Redis-таймауты | Контекст 250 мс; dial/read/write/pool 200 мс; повторы отключены; до 10 соединений |
|
||||
|
||||
Пагинация не создаёт общий snapshot между запросами. При откате часов время сообщений может временно опережать физические часы. Подробности схемы: [storage-design.md](docs/storage-design.md), [миграции](migrations/README.md).
|
||||
Redis persistence выключена: обязательные данные и сессии находятся в PostgreSQL. Перезапуск Redis теряет только восстановимый кэш. История не кэшируется. Cache hit сокращает чтения users, но не отменяет SQL-проверку сессии; ускорение HTTP latency не заявляется.
|
||||
|
||||
## Доказательства критериев
|
||||
Подробности схемы: [storage-design.md](docs/storage-design.md), [миграции](migrations/README.md).
|
||||
|
||||
| Проверка | Команда/сценарий | Результат | Доказательство |
|
||||
| --- | --- | --- | --- |
|
||||
| Сборка API | `docker compose up -d --build --wait api` | go vet/test/build успешны; API и БД Healthy | [вывод](evidence/registration-http.txt) |
|
||||
| Публичный smoke | `py tests/smoke.py --base-url http://localhost:8080` | PASS, сквозной API lab2 | [вывод](evidence/postgres-chats-checks.txt) |
|
||||
| Persistence | `py tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080` | PASS, прежние токены и подтверждённое сообщение сохранены | [вывод](evidence/persistence.txt) |
|
||||
| Область рестарта | restart.ps1: stop/start api и postgres | StartedAt обоих изменился; volume сохранился | [снимки](evidence/restart-containers.json) |
|
||||
| Миграция с нуля и повтор | `psql -f /migrations/apply.psql` внутри postgres | 6 таблиц; версия 1 одна; повтор пропущен | [вывод](evidence/postgres-migration.txt) |
|
||||
| Автомиграции | `docker compose up -d --wait api` | migrate завершился с кодом 0; API Healthy | [вывод](evidence/persistence.txt) |
|
||||
| Регистрация и гонка имени | `py student-tests/registration.py`; SQL-проверка users | 201; дубликат 409; неверные поля 400; гонка → 201/409 | [вывод](evidence/registration-http.txt) |
|
||||
| Password KDF | `go test ./internal/password -v -count=1` | PASS: Unicode, соль, неверный пароль, повреждённый хеш | [вывод](evidence/password-tests.txt) |
|
||||
| Вход и выход | `py student-tests/sessions.py` | PASS: Basic/Bearer, неверный пароль, logout; X-User-Id не даёт доступ | [вывод](evidence/sessions-http.txt) |
|
||||
| Expiry | TTL=2; `py student-tests/sessions.py --expiry` | До истечения доступ есть, после — 401 | [вывод](evidence/sessions-http.txt) |
|
||||
| Rollback | `py student-tests/chat-rollback.py` | Неизвестный второй участник → 400; строка чата не осталась | [вывод](evidence/postgres-chats-checks.txt) |
|
||||
## Проверки требований
|
||||
|
||||
В evidence сохранены команды и результаты проверок; дата проверок — 09.10.2026. Проверки выполнены на рабочем дереве до первого коммита решения; commit будет указан после фиксации и контрольного запуска. Smoke и persistence запущены напрямую через Python — это сценарии Makefile; сам make на Windows не запускался. Начальная миграция проверена на новом volume, автомиграции — на существующей БД.
|
||||
|
||||
## Эксперименты и ограничения
|
||||
|
||||
| Воздействие | Ожидание | Наблюдение |
|
||||
| Требование / команда | Результат | Доказательство |
|
||||
| --- | --- | --- |
|
||||
| Управляемый stop/start API и PostgreSQL | Прежние данные и сессии доступны | PASS, потерь в сценарии нет; время восстановления отдельно не измерялось |
|
||||
| TTL=2 | Токен перестаёт работать | После истечения — 401 |
|
||||
| Несуществующий участник | Создание чата отменяется целиком | Rollback подтверждён SQL |
|
||||
| make check test PYTHON=py | PASS: структура и публичный API | [final-review.txt](evidence/final-review.txt) |
|
||||
| Пустая БД и автомиграции | Новая копия без secrets/.env, новый volume; миграция 1; smoke PASS | [clean-start.txt](evidence/clean-start.txt) |
|
||||
| Повторная миграция | Применённая версия пропущена; одна запись версии 1 | [postgres-migration.txt](evidence/postgres-migration.txt) |
|
||||
| Полный persistence | API/PostgreSQL/Redis перезапущены; прежний токен и сообщение сохранены | [вывод](evidence/cache-failures.txt), [снимки](evidence/restart-all-containers.json) |
|
||||
| py student-tests/registration.py | Регистрация; дубликат; гонка → 201/409 | [registration-http.txt](evidence/registration-http.txt) |
|
||||
| py student-tests/chat-rollback.py | Ошибка участника → 400; чат не остался в БД | [postgres-chats-checks.txt](evidence/postgres-chats-checks.txt) |
|
||||
| go test ./internal/password -v -count=1 | Unicode, соль, неверный пароль, повреждённый hash — PASS | [password-tests.txt](evidence/password-tests.txt) |
|
||||
| py student-tests/sessions.py | Неверные credentials, Bearer, logout, X-User-Id — PASS | [sessions-http.txt](evidence/sessions-http.txt) |
|
||||
| TTL=2; py student-tests/sessions.py --expiry | До expiry — 200; после — 401; повторено с Redis | [final-review.txt](evidence/final-review.txt) |
|
||||
| py student-tests/cache-failures.py | Hit, TTL, восстановление; Redis stop → 200 за 0,438 с; PostgreSQL stop → 503 за 3,172 с; анонимный запрос → 401 | [cache-failures.txt](evidence/cache-failures.txt) |
|
||||
| py student-tests/explain-history.py | 12 000 сообщений; обе страницы используют индекс; HTTP после позиции 6000 начинает с 6001 | [планы](evidence/history-explain.txt), [замеры](evidence/history-explain.json) |
|
||||
|
||||
- Стенд одноузловой, без HA и backup; потеря диска, удаление volume и отключение питания не проверялись.
|
||||
- Роль messenger имеет superuser-права; TCP без TLS допускается только в локальном стенде.
|
||||
- Истёкшие сессии не очищаются автоматически; доступ по ним запрещён.
|
||||
- Новый чистый clone и Linux-hook отдельно не проверены.
|
||||
Базовые проверки выполнены до коммита 83e3810; Redis, EXPLAIN и финальная сверка — в рабочем дереве после него. Persistence выполнен через Python-сценарий Makefile с Windows-hook.
|
||||
|
||||
## Осталось на оценку 4
|
||||
## Обоснование индекса
|
||||
|
||||
- Redis как кэш профилей: TTL 60 с, источник истины PostgreSQL, обход кэша при отказе.
|
||||
- Автотесты недоступности Redis/БД и повторный persistence со всеми хранилищами.
|
||||
- EXPLAIN (ANALYZE, BUFFERS) на ≥10 000 сообщениях и обоснование индекса.
|
||||
- Финальная проверка запуска, оформление commit/PR.
|
||||
Индекс `(chat_id,created_at,id)` соответствует фильтру чата и порядку истории. Условие `(created_at,id)>($3,$4)` входит в Index Cond. Сортировка использует исходный `messages.id` типа UUID. Для страницы из 50 запрашивается 51 строка, чтобы определить наличие продолжения.
|
||||
|
||||
| Страница | План / строки | Shared hit в текстовом плане | Медиана Execution Time |
|
||||
| --- | --- | --- | --- |
|
||||
| Первая | Index Scan / 51 | 3 | 0,111 мс |
|
||||
| После сообщения 6000 | Index Scan / 51 | 4 | 0,193 мс |
|
||||
|
||||
Методика: 12 000 SQL-сгенерированных сообщений в одном чате, ANALYZE, один прогрев и три последовательных замера, без конкурентных записей. Полного сканирования и отдельной сортировки в обоих планах нет. Текстовые планы сняты отдельно от трёх JSON-замеров. Это SQL-тест с прогретым кэшем, не измерение HTTP latency. Версия БД и ресурсы Docker сохранены в JSON. Повтор теста создаёт новый чат с 12 000 сообщениями.
|
||||
|
||||
## Ограничения
|
||||
|
||||
- Один узел, без HA/backup; потеря диска, отключение питания и удаление volume не проверялись.
|
||||
- HTTP без TLS, PostgreSQL superuser messenger и Redis без пароля — только локальный стенд с синтетическими данными. Файловые secrets не шифруются, доступ зависит от прав ОС.
|
||||
- Истёкшие сессии запрещают доступ, но автоматически не удаляются. При добавлении редактирования профилей потребуется инвалидация кэша.
|
||||
- Между страницами нет общего snapshot; при откате часов время сообщений может опережать физические часы.
|
||||
- Проверена отдельная копия с пустой БД и кешем Docker build; git clone после финального коммита, Linux-hook и удалённый CI не проверены.
|
||||
- Добавлен отдельный GitHub application workflow; его запуск на используемом Gitea не подтверждён.
|
||||
|
||||
## Источники и помощь
|
||||
|
||||
- Задание и контракт lab2; собственная реализация lab1.
|
||||
- [pgxpool](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool), pgx v5.7.6.
|
||||
- [RFC 9106](https://www.rfc-editor.org/rfc/rfc9106.html#section-4), Argon2id из golang.org/x/crypto v0.37.0.
|
||||
- Codex: помощь с реализацией, объяснениями, проверками и ведением отчёта.
|
||||
- [pgxpool](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool), [PostgreSQL EXPLAIN](https://www.postgresql.org/docs/17/using-explain.html).
|
||||
- [go-redis](https://redis.io/docs/latest/develop/clients/go/produsage/), [RFC 9106](https://www.rfc-editor.org/rfc/rfc9106.html).
|
||||
- Codex: помощь с реализацией, объяснениями, проверками и отчётом.
|
||||
|
||||
+4
-1
@@ -14,6 +14,7 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/cache"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
@@ -54,7 +55,9 @@ func run() error {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
db := store.NewPostgresStore(pool)
|
||||
profiles := cache.NewProfiles(envOrDefault("REDIS_ADDR", "redis:6379"))
|
||||
defer profiles.Close()
|
||||
db := store.NewPostgresStore(pool).WithProfiles(profiles)
|
||||
|
||||
var stopping atomic.Bool
|
||||
ttl, err := strconv.ParseInt(envOrDefault("SESSION_TTL_SECONDS", "3600"), 10, 64)
|
||||
|
||||
@@ -6,6 +6,7 @@ services:
|
||||
environment:
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DATABASE_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
REDIS_ADDR: redis:6379
|
||||
secrets:
|
||||
- postgres_password
|
||||
ports:
|
||||
@@ -15,8 +16,21 @@ services:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_started
|
||||
stop_grace_period: 15s
|
||||
|
||||
redis:
|
||||
image: redis:7.4.11-alpine
|
||||
command: ["redis-server", "--save", "", "--appendonly", "no", "--maxmemory", "64mb", "--maxmemory-policy", "allkeys-lru"]
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 3s
|
||||
timeout: 2s
|
||||
retries: 10
|
||||
tmpfs:
|
||||
- /data
|
||||
|
||||
migrate:
|
||||
image: postgres:17.9-bookworm
|
||||
environment:
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# План хранения lab2
|
||||
|
||||
Статус: начальная SQL-миграция `migrations/000001_initial.up.sql` применена через `apply.psql`; повторный запуск пропускает версию 1. Запросы приложения к PostgreSQL ещё не реализованы. Приложение пока использует MemoryStore.
|
||||
Статус: все обязательные данные и сессии перенесены в PostgreSQL. Миграции применяет Compose-сервис migrate; повторный запуск пропускает версию 1. Redis подключён как кэш профилей.
|
||||
|
||||
## Источник истины
|
||||
|
||||
PostgreSQL хранит пользователей, чаты, членство, сообщения и сессии. Планируемая роль Redis — кэш публичного профиля пользователя по ID с ограниченным TTL. В кэш не попадают пароль, его hash или Bearer-токен. Сессия и её срок проверяются в PostgreSQL на каждом защищённом запросе; кэш профиля не даёт права доступа.
|
||||
PostgreSQL хранит пользователей, чаты, членство, сообщения и сессии. Redis хранит публичный профиль в JSON по ключу profile:v1:<UUID>, TTL 60 секунд. В кэш не попадают пароль, его hash или Bearer-токен. Сессия и её срок проверяются в PostgreSQL на каждом защищённом запросе до обращения к кэшу; кэш профиля не даёт права доступа. При попадании отдельный SELECT профиля не выполняется; улучшение latency не заявляется без измерений.
|
||||
|
||||
При недоступности Redis профиль читается из PostgreSQL после ограниченного таймаутом обращения к кэшу. При недоступности PostgreSQL защищённый запрос получает 503; успешная аутентификация только по кэшу запрещена. История сообщений не кэшируется.
|
||||
|
||||
Профиль не изменяется обязательным API lab2, поэтому инвалидация происходит по TTL (план: 60 секунд); при добавлении редактирования потребуется отдельное решение об инвалидации. При потере кэша он заполняется заново. Все обязательные данные, включая сессии, сохраняются в PostgreSQL volume.
|
||||
Профиль не изменяется обязательным API lab2, поэтому инвалидация происходит по TTL 60 секунд; чтение TTL не продлевает. При добавлении редактирования потребуется отдельное решение об инвалидации. Истёкшая, отсутствующая или повреждённая запись заполняется из PostgreSQL. Logout удаляет сессию в PostgreSQL, профиль можно оставить: каждый запрос сначала проверяет сессию. Все обязательные данные сохраняются в PostgreSQL volume. Redis использует maxmemory 64mb, allkeys-lru, persistence отключена, /data — tmpfs: потеря всего кэша допустима.
|
||||
|
||||
## Таблицы
|
||||
|
||||
@@ -42,4 +42,4 @@ PostgreSQL хранит пользователей, чаты, членство,
|
||||
- Вход: после проверки пароля сохраняется сессия; токен возвращается только после успешного сохранения.
|
||||
- Выход: удаление текущей сессии; 204 выдаётся после успешного COMMIT. Следующий запрос с этим токеном получает 401.
|
||||
|
||||
Версия 1 учитывается в служебной таблице schema_migrations. Повторный запуск apply.psql пропускает её; это проверено на поднятом через Compose PostgreSQL. Подключение API и Redis будет реализовано следующими этапами.
|
||||
Версия 1 учитывается в служебной таблице schema_migrations. Повторный запуск apply.psql пропускает её; это проверено на поднятом через Compose PostgreSQL. Restart hooks теперь перезапускают API, PostgreSQL и Redis с сохранением PostgreSQL volume.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
Дата: 2026-10-09.
|
||||
Версия: рабочее дерево после 83e3810 (добавление Redis).
|
||||
|
||||
> docker compose up -d --build --wait api
|
||||
Сборка успешна (go vet, go test, go build); API, PostgreSQL и Redis Healthy.
|
||||
|
||||
> py student-tests/cache-failures.py
|
||||
PASS: public profile cached; TTL <=60s; Redis hit confirmed; TTL not extended
|
||||
PASS: malformed cache entry replaced from PostgreSQL
|
||||
PASS: expired profile refilled from PostgreSQL
|
||||
PASS: Redis stopped -> PostgreSQL fallback 200 (0.438s); anonymous request 401
|
||||
PASS: Redis restart -> profile refilled; same Bearer token remains valid
|
||||
PASS: PostgreSQL stopped with warm cache -> 503 (3.172s); anonymous request 401
|
||||
PASS: PostgreSQL recovered; logout invalidates token even with cached profile
|
||||
|
||||
Код завершения: 0. Зависимости восстановлены в finally.
|
||||
Для проверки истечения тест сокращает TTL только собственного ключа через PEXPIRE;
|
||||
реальный TTL 60 секунд отдельно проверяется по PTTL, чтение его не продлевает.
|
||||
Тест не выводит пароли/токены. Измерения — одиночные запросы, не нагрузочный benchmark.
|
||||
|
||||
> py tests/smoke.py --base-url http://localhost:8080
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
> py tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
Область рестарта: api, postgres, redis; снимки в restart-all-containers.json.
|
||||
StartedAt всех трёх изменился; именованный volume PostgreSQL сохранился.
|
||||
@@ -0,0 +1,17 @@
|
||||
Дата: 2026-10-09.
|
||||
Версия: рабочее дерево после 83e3810.
|
||||
|
||||
Метод: отдельная копия git ls-files --cached --others --exclude-standard,
|
||||
без .git, .env и secrets. Это не git clone: изменения ещё не закоммичены.
|
||||
Compose project: lab2-clean-check; порт копии изменён на 18080.
|
||||
Новый пароль создан scripts/init-local.ps1; новый volume lab2-clean-check_postgres_data.
|
||||
Docker использовал кеш слоёв сборки; загрузка зависимостей с нуля не проверялась.
|
||||
|
||||
> ./scripts/init-local.ps1
|
||||
Local PostgreSQL password created in secrets/ (value not printed).
|
||||
> docker compose -p lab2-clean-check up -d --build --wait api
|
||||
PASS: новый volume создан; migrate завершён; api/postgres/redis Healthy.
|
||||
> py tests/smoke.py --base-url http://localhost:18080
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
> docker compose -p lab2-clean-check exec -T postgres psql -X -U messenger -d messenger -c 'TABLE schema_migrations;'
|
||||
version: 1; applied_at: 2026-10-09 20:12:41.436626+00; 1 row.
|
||||
@@ -0,0 +1,42 @@
|
||||
Дата: 2026-10-09.
|
||||
Версия: рабочее дерево после 83e3810, перед MR.
|
||||
|
||||
> ./scripts/init-local.ps1
|
||||
Local .env created (non-secret session TTL).
|
||||
Existing PostgreSQL password preserved.
|
||||
> docker compose --env-file .env config --quiet
|
||||
Exit code: 0.
|
||||
> make check test PYTHON=py
|
||||
py scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
py tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
> py student-tests/sessions.py --expiry
|
||||
Условие: API пересоздан с SESSION_TTL_SECONDS=2, Redis включён.
|
||||
PASS: wrong/missing credentials 401; login JSON body 400
|
||||
PASS: short TTL session works before expiry and returns 401 after expiry
|
||||
|
||||
> git check-ignore .env secrets/postgres_password.txt
|
||||
.env
|
||||
secrets/postgres_password.txt
|
||||
> git ls-files secrets .env
|
||||
Пустой вывод: секреты не отслеживаются.
|
||||
> git diff 65003b6 --stat -- README.md COURSE.md contracts tests
|
||||
Пустой вывод: задание, контракт и публичные тесты сохранены.
|
||||
|
||||
Повторная проверка перед загрузкой: 10.10.2026.
|
||||
> make check test PYTHON=py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
> docker compose --env-file .env config --quiet
|
||||
Exit code: 0.
|
||||
> go test ./...
|
||||
PASS: все пакеты с тестами; internal/password — cached.
|
||||
> go vet ./...
|
||||
Exit code: 0; замечаний нет.
|
||||
> git diff --check
|
||||
Ошибок whitespace нет; Git предупреждает о преобразовании LF/CRLF.
|
||||
Все локальные ссылки REPORT.md существуют. Lab1: git status --short пуст.
|
||||
Отказы, persistence и EXPLAIN в этой повторной проверке не запускались;
|
||||
их результаты от 09.10.2026 сохранены в соответствующих evidence-файлах.
|
||||
@@ -0,0 +1,461 @@
|
||||
{
|
||||
"date": "2026-10-09",
|
||||
"messages_in_chat": 12000,
|
||||
"chat_id": "06ecd609-697c-48aa-9150-8bce12447663",
|
||||
"page_size": 50,
|
||||
"sql_limit": 51,
|
||||
"concurrency": 1,
|
||||
"warmups": 1,
|
||||
"repeats": 3,
|
||||
"postgres_version": "17.9 (Debian 17.9-1.pgdg12+1)",
|
||||
"docker_cpus_memory_bytes": "16 16389435392",
|
||||
"postgres_cpu_memory_limits": "0 0",
|
||||
"method": "SQL-generated fixture; ANALYZE; prepared query; one warmup and three serial measurements; no concurrent writers",
|
||||
"limitations": "warm cache, one synthetic chat; not HTTP latency or throughput; no crash-durability measurement",
|
||||
"cases": {
|
||||
"first_page": {
|
||||
"prepare": "PREPARE history(uuid,integer) AS SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1 ORDER BY messages.created_at,messages.id LIMIT $2;",
|
||||
"execute": "EXECUTE history('06ecd609-697c-48aa-9150-8bce12447663',51)",
|
||||
"plans": [
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 5.04,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.039,
|
||||
"Actual Total Time": 0.066,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 3,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_chat_history_idx",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 1118.17,
|
||||
"Plan Rows": 12000,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.038,
|
||||
"Actual Total Time": 0.059,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "(chat_id = '06ecd609-697c-48aa-9150-8bce12447663'::uuid)",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 3,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 113,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.692,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.116
|
||||
},
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 5.04,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.035,
|
||||
"Actual Total Time": 0.059,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 3,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_chat_history_idx",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 1118.17,
|
||||
"Plan Rows": 12000,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.034,
|
||||
"Actual Total Time": 0.053,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "(chat_id = '06ecd609-697c-48aa-9150-8bce12447663'::uuid)",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 3,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 113,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.632,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.106
|
||||
},
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 5.04,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.037,
|
||||
"Actual Total Time": 0.064,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 3,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_chat_history_idx",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 1118.17,
|
||||
"Plan Rows": 12000,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.036,
|
||||
"Actual Total Time": 0.057,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "(chat_id = '06ecd609-697c-48aa-9150-8bce12447663'::uuid)",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 3,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 113,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.681,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.111
|
||||
}
|
||||
]
|
||||
},
|
||||
"after_6000": {
|
||||
"prepare": "PREPARE history(uuid,integer,timestamptz,uuid) AS SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($3,$4::uuid) ORDER BY messages.created_at,messages.id LIMIT $2;",
|
||||
"execute": "EXECUTE history('06ecd609-697c-48aa-9150-8bce12447663',51,'2026-10-08T19:47:14.460524+00:00','fc066765-6778-4d9f-b1ed-60f49ecef3db')",
|
||||
"plans": [
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 6.41,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.172,
|
||||
"Actual Total Time": 0.208,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_chat_history_idx",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 721.62,
|
||||
"Plan Rows": 6004,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.171,
|
||||
"Actual Total Time": 0.201,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "((chat_id = '06ecd609-697c-48aa-9150-8bce12447663'::uuid) AND (ROW(created_at, id) > ROW('2026-10-08 19:47:14.460524+00'::timestamp with time zone, 'fc066765-6778-4d9f-b1ed-60f49ecef3db'::uuid)))",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 112,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 1.21,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.432
|
||||
},
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 6.41,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.045,
|
||||
"Actual Total Time": 0.076,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_chat_history_idx",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 721.62,
|
||||
"Plan Rows": 6004,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.043,
|
||||
"Actual Total Time": 0.069,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "((chat_id = '06ecd609-697c-48aa-9150-8bce12447663'::uuid) AND (ROW(created_at, id) > ROW('2026-10-08 19:47:14.460524+00'::timestamp with time zone, 'fc066765-6778-4d9f-b1ed-60f49ecef3db'::uuid)))",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 112,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.609,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.143
|
||||
},
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 6.41,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.045,
|
||||
"Actual Total Time": 0.076,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_chat_history_idx",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 721.62,
|
||||
"Plan Rows": 6004,
|
||||
"Plan Width": 143,
|
||||
"Actual Startup Time": 0.044,
|
||||
"Actual Total Time": 0.069,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "((chat_id = '06ecd609-697c-48aa-9150-8bce12447663'::uuid) AND (ROW(created_at, id) > ROW('2026-10-08 19:47:14.460524+00'::timestamp with time zone, 'fc066765-6778-4d9f-b1ed-60f49ecef3db'::uuid)))",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 4,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 112,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.603,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.193
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
Date: 2026-10-09
|
||||
Command: py student-tests/explain-history.py
|
||||
Messages: 12000
|
||||
|
||||
PASS: first_page: history index, 51 rows, no full scan; median SQL execution 0.111 ms
|
||||
PASS: after_6000: history index, 51 rows, no full scan; median SQL execution 0.193 ms
|
||||
PASS: 12000 messages; HTTP cursor after 6000 returns message 6001; plans saved in evidence
|
||||
|
||||
Control: py tests/smoke.py --base-url http://localhost:8080
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
first_page
|
||||
PREPARE history(uuid,integer) AS SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1 ORDER BY messages.created_at,messages.id LIMIT $2;
|
||||
Limit (cost=0.29..5.04 rows=51 width=143) (actual time=0.042..0.066 rows=51 loops=1)
|
||||
Buffers: shared hit=3
|
||||
-> Index Scan using messages_chat_history_idx on messages (cost=0.29..1118.17 rows=12000 width=143) (actual time=0.040..0.059 rows=51 loops=1)
|
||||
Index Cond: (chat_id = '06ecd609-697c-48aa-9150-8bce12447663'::uuid)
|
||||
Buffers: shared hit=3
|
||||
Planning:
|
||||
Buffers: shared hit=113
|
||||
Planning Time: 0.702 ms
|
||||
Execution Time: 0.118 ms
|
||||
|
||||
after_6000
|
||||
PREPARE history(uuid,integer,timestamptz,uuid) AS SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($3,$4::uuid) ORDER BY messages.created_at,messages.id LIMIT $2;
|
||||
Limit (cost=0.29..6.41 rows=51 width=143) (actual time=0.043..0.080 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_history_idx on messages (cost=0.29..721.62 rows=6004 width=143) (actual time=0.042..0.074 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = '06ecd609-697c-48aa-9150-8bce12447663'::uuid) AND (ROW(created_at, id) > ROW('2026-10-08 19:47:14.460524+00'::timestamp with time zone, 'fc066765-6778-4d9f-b1ed-60f49ecef3db'::uuid)))
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=112
|
||||
Planning Time: 0.629 ms
|
||||
Execution Time: 0.152 ms
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"before": [
|
||||
{
|
||||
"service": "api",
|
||||
"id": "67ad51ae8ed17299021179b31c5d1125c35ee0679af469710762a295bf8e5687",
|
||||
"started_at": "2026-10-09T15:14:50.117640501Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "postgres",
|
||||
"id": "836bb4b071ea3cb8ed7b3bd1622898b3e5beb2bb28237616b4bca6e11d9cc55a",
|
||||
"started_at": "2026-10-09T15:15:20.187696938Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
"messenger-lab2_postgres_data"
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "redis",
|
||||
"id": "1014dede60b3f51332adc8f3b988e8c69dcac3ce8ab01fa18d81094b12b53cd7",
|
||||
"started_at": "2026-10-09T15:15:11.322251556Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
|
||||
]
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"service": "api",
|
||||
"id": "67ad51ae8ed17299021179b31c5d1125c35ee0679af469710762a295bf8e5687",
|
||||
"started_at": "2026-10-09T15:16:04.389539436Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "postgres",
|
||||
"id": "836bb4b071ea3cb8ed7b3bd1622898b3e5beb2bb28237616b4bca6e11d9cc55a",
|
||||
"started_at": "2026-10-09T15:15:56.366913858Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
"messenger-lab2_postgres_data"
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "redis",
|
||||
"id": "1014dede60b3f51332adc8f3b988e8c69dcac3ce8ab01fa18d81094b12b53cd7",
|
||||
"started_at": "2026-10-09T15:15:56.350855874Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
|
||||
]
|
||||
}
|
||||
],
|
||||
"volumes_preserved": true
|
||||
}
|
||||
@@ -4,10 +4,13 @@ go 1.26.3
|
||||
|
||||
require (
|
||||
github.com/jackc/pgx/v5 v5.7.6
|
||||
github.com/redis/go-redis/v9 v9.7.3
|
||||
golang.org/x/crypto v0.37.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
@@ -11,6 +19,8 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
|
||||
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
|
||||
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const ProfileTTL = 60 * time.Second
|
||||
|
||||
type Profiles struct{ client *redis.Client }
|
||||
|
||||
func NewProfiles(address string) *Profiles {
|
||||
return &Profiles{client: redis.NewClient(&redis.Options{
|
||||
Addr: address,
|
||||
Protocol: 2,
|
||||
MaxRetries: -1,
|
||||
DialTimeout: 200 * time.Millisecond,
|
||||
ReadTimeout: 200 * time.Millisecond,
|
||||
WriteTimeout: 200 * time.Millisecond,
|
||||
PoolTimeout: 200 * time.Millisecond,
|
||||
ContextTimeoutEnabled: true,
|
||||
PoolSize: 10,
|
||||
MaxActiveConns: 10,
|
||||
MinIdleConns: 0,
|
||||
})}
|
||||
}
|
||||
|
||||
func (p *Profiles) Close() error { return p.client.Close() }
|
||||
|
||||
func (p *Profiles) Get(ctx context.Context, id string) (model.User, bool) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
defer cancel()
|
||||
raw, err := p.client.Get(ctx, "profile:v1:"+id).Bytes()
|
||||
if err != nil {
|
||||
return model.User{}, false
|
||||
}
|
||||
var user model.User
|
||||
if json.Unmarshal(raw, &user) != nil || user.ID != id || user.Username == "" || user.DisplayName == "" || user.CreatedAt.IsZero() {
|
||||
return model.User{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func (p *Profiles) Set(ctx context.Context, user model.User) {
|
||||
raw, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
defer cancel()
|
||||
_ = p.client.Set(ctx, "profile:v1:"+user.ID, raw, ProfileTTL).Err()
|
||||
}
|
||||
@@ -140,7 +140,7 @@ func (s *PostgresStore) MessagePage(ctx context.Context, chatID string, limit in
|
||||
query += ` AND (created_at,id)>($3,$4::uuid)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY created_at,id LIMIT $2`
|
||||
query += ` ORDER BY messages.created_at,messages.id LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
|
||||
@@ -42,18 +42,17 @@ func (s *PostgresStore) CreateSession(ctx context.Context, hash []byte, userID s
|
||||
func (s *PostgresStore) SessionUser(ctx context.Context, hash []byte) (model.User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, `SELECT u.id::text, u.username, u.display_name, u.created_at
|
||||
FROM sessions s JOIN users u ON u.id=s.user_id
|
||||
WHERE s.token_hash=$1 AND s.expires_at > clock_timestamp()`, hash).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
var userID string
|
||||
// Validate the session in the source of truth BEFORE consulting any cache.
|
||||
err := s.pool.QueryRow(ctx, `SELECT user_id::text FROM sessions
|
||||
WHERE token_hash=$1 AND expires_at > clock_timestamp()`, hash).Scan(&userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrSessionNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
return s.profile(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *PostgresStore) DeleteSession(ctx context.Context, hash []byte) error {
|
||||
|
||||
@@ -12,12 +12,46 @@ import (
|
||||
|
||||
var ErrUnavailable = errors.New("storage unavailable")
|
||||
|
||||
type PostgresStore struct{ pool *pgxpool.Pool }
|
||||
type ProfileCache interface {
|
||||
Get(context.Context, string) (model.User, bool)
|
||||
Set(context.Context, model.User)
|
||||
}
|
||||
|
||||
type PostgresStore struct {
|
||||
pool *pgxpool.Pool
|
||||
profiles ProfileCache
|
||||
}
|
||||
|
||||
func NewPostgresStore(pool *pgxpool.Pool) *PostgresStore {
|
||||
return &PostgresStore{pool: pool}
|
||||
}
|
||||
|
||||
// Configure once before the HTTP server starts.
|
||||
func (s *PostgresStore) WithProfiles(profiles ProfileCache) *PostgresStore {
|
||||
s.profiles = profiles
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *PostgresStore) profile(ctx context.Context, id string) (model.User, error) {
|
||||
if s.profiles != nil {
|
||||
if user, ok := s.profiles.Get(ctx, id); ok {
|
||||
return user, nil
|
||||
}
|
||||
}
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, `SELECT id::text, username, display_name, created_at FROM users WHERE id=$1`, id).Scan(
|
||||
&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
if s.profiles != nil {
|
||||
s.profiles.Set(ctx, user)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$envPath = Join-Path $repoRoot '.env'
|
||||
if (-not (Test-Path -LiteralPath $envPath)) {
|
||||
Copy-Item -LiteralPath (Join-Path $repoRoot '.env.example') -Destination $envPath
|
||||
Write-Output 'Local .env created (non-secret session TTL).'
|
||||
} else {
|
||||
Write-Output 'Existing .env preserved.'
|
||||
}
|
||||
|
||||
$secretsDirectory = Join-Path $repoRoot 'secrets'
|
||||
$passwordPath = Join-Path $secretsDirectory 'postgres_password.txt'
|
||||
|
||||
|
||||
+5
-5
@@ -3,7 +3,7 @@ Set-Location (Split-Path -Parent $PSScriptRoot)
|
||||
|
||||
function Read-Containers {
|
||||
$result = @()
|
||||
foreach ($service in @('api', 'postgres')) {
|
||||
foreach ($service in @('api', 'postgres', 'redis')) {
|
||||
$containerID = docker compose ps -q $service
|
||||
if ($LASTEXITCODE -ne 0 -or -not $containerID) { throw "Cannot find $service container" }
|
||||
$json = docker inspect --format '{{json .}}' $containerID
|
||||
@@ -22,9 +22,9 @@ function Read-Containers {
|
||||
}
|
||||
|
||||
$before = @(Read-Containers)
|
||||
docker compose stop api postgres
|
||||
docker compose stop api postgres redis
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Stop failed' }
|
||||
docker compose up -d --wait postgres
|
||||
docker compose up -d --wait postgres redis
|
||||
if ($LASTEXITCODE -ne 0) { throw 'PostgreSQL restart failed' }
|
||||
docker compose up -d --wait api
|
||||
if ($LASTEXITCODE -ne 0) { throw 'API restart failed' }
|
||||
@@ -39,6 +39,6 @@ foreach ($old in $before) {
|
||||
}
|
||||
}
|
||||
$evidence = [ordered]@{ before = $before; after = $after; volumes_preserved = $true }
|
||||
$path = Join-Path $PWD 'evidence/restart-containers.json'
|
||||
$path = Join-Path $PWD 'evidence/restart-all-containers.json'
|
||||
[System.IO.File]::WriteAllText($path, ($evidence | ConvertTo-Json -Depth 5), [System.Text.UTF8Encoding]::new($false))
|
||||
Write-Output 'PASS: API and PostgreSQL restarted; named volumes preserved.'
|
||||
Write-Output 'PASS: API, PostgreSQL and Redis restarted; named volumes preserved.'
|
||||
|
||||
+4
-4
@@ -3,7 +3,7 @@ set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
snapshot() {
|
||||
for service in api postgres; do
|
||||
for service in api postgres redis; do
|
||||
id=$(docker compose ps -q "$service")
|
||||
test -n "$id"
|
||||
docker inspect --format '{{.Name}} {{.Id}} {{.State.StartedAt}} {{.State.Status}} {{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}' "$id"
|
||||
@@ -11,8 +11,8 @@ snapshot() {
|
||||
}
|
||||
|
||||
snapshot > evidence/restart-containers-before.txt
|
||||
docker compose stop api postgres
|
||||
docker compose up -d --wait postgres
|
||||
docker compose stop api postgres redis
|
||||
docker compose up -d --wait postgres redis
|
||||
docker compose up -d --wait api
|
||||
snapshot > evidence/restart-containers-after.txt
|
||||
printf '%s\n' 'API and PostgreSQL restarted without removing volumes.'
|
||||
printf '%s\n' 'API, PostgreSQL and Redis restarted without removing volumes.'
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from sessions import request, basic
|
||||
|
||||
|
||||
def compose(*args):
|
||||
result = subprocess.run(["docker", "compose", *args], capture_output=True, text=True, encoding="utf-8", timeout=60)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Docker Compose command failed: " + " ".join(args[:3]))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def redis(*args):
|
||||
return compose("exec", "-T", "redis", "redis-cli", "--raw", *args)
|
||||
|
||||
|
||||
def hits():
|
||||
stats = redis("INFO", "stats")
|
||||
return int(next(line.split(":")[1] for line in stats.splitlines() if line.startswith("keyspace_hits:")))
|
||||
|
||||
|
||||
def bounded_get(headers, status):
|
||||
start = time.monotonic()
|
||||
result = request("GET", "/users/me", status, headers=headers)
|
||||
elapsed = time.monotonic() - start
|
||||
assert elapsed < 5, f"dependency request took {elapsed:.3f}s"
|
||||
return result, elapsed
|
||||
|
||||
|
||||
def main():
|
||||
username = "cache_" + uuid.uuid4().hex[:20]
|
||||
password = "учебный:пароль:кэш"
|
||||
user = request("POST", "/users", 201, {"username": username, "display_name": "Кэш", "password": password})
|
||||
session = request("POST", "/auth/sessions", 201, headers=basic(username, password))
|
||||
headers = {"Authorization": "Bearer " + session["token"]}
|
||||
key = "profile:v1:" + user["id"]
|
||||
request("GET", "/users/me", 200, headers=headers)
|
||||
cached = json.loads(redis("GET", key))
|
||||
assert cached == user, "cache must contain only public User fields"
|
||||
ttl = int(redis("PTTL", key))
|
||||
assert 0 < ttl <= 60000, "profile TTL must be 60 seconds"
|
||||
before = hits()
|
||||
time.sleep(0.1)
|
||||
assert request("GET", "/users/me", 200, headers=headers) == user
|
||||
assert hits() > before, "API did not read Redis"
|
||||
assert 0 < int(redis("PTTL", key)) < ttl, "cache hit refreshed TTL"
|
||||
print("PASS: public profile cached; TTL <=60s; Redis hit confirmed; TTL not extended")
|
||||
|
||||
redis("SET", key, "invalid-json", "EX", "60")
|
||||
assert request("GET", "/users/me", 200, headers=headers) == user
|
||||
assert json.loads(redis("GET", key)) == user
|
||||
print("PASS: malformed cache entry replaced from PostgreSQL")
|
||||
|
||||
redis("PEXPIRE", key, "1")
|
||||
time.sleep(0.05)
|
||||
assert redis("EXISTS", key) == "0"
|
||||
assert request("GET", "/users/me", 200, headers=headers) == user
|
||||
assert redis("EXISTS", key) == "1"
|
||||
print("PASS: expired profile refilled from PostgreSQL")
|
||||
|
||||
try:
|
||||
compose("stop", "redis")
|
||||
result, elapsed = bounded_get(headers, 200)
|
||||
assert result == user
|
||||
request("GET", "/users/me", 401, headers={"X-User-Id": user["id"]})
|
||||
print(f"PASS: Redis stopped -> PostgreSQL fallback 200 ({elapsed:.3f}s); anonymous request 401")
|
||||
finally:
|
||||
compose("up", "-d", "--wait", "redis")
|
||||
|
||||
assert request("GET", "/users/me", 200, headers=headers) == user
|
||||
assert redis("EXISTS", key) == "1"
|
||||
print("PASS: Redis restart -> profile refilled; same Bearer token remains valid")
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
result, elapsed = bounded_get(headers, 503)
|
||||
assert result["error"]["code"] == "unavailable"
|
||||
request("GET", "/users/me", 401, headers={"X-User-Id": user["id"]})
|
||||
print(f"PASS: PostgreSQL stopped with warm cache -> 503 ({elapsed:.3f}s); anonymous request 401")
|
||||
finally:
|
||||
compose("up", "-d", "--wait", "postgres")
|
||||
|
||||
assert request("GET", "/users/me", 200, headers=headers) == user
|
||||
request("DELETE", "/auth/sessions/current", 204, headers=headers)
|
||||
assert redis("EXISTS", key) == "1", "expected a warm profile cache"
|
||||
request("GET", "/users/me", 401, headers=headers)
|
||||
print("PASS: PostgreSQL recovered; logout invalidates token even with cached profile")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,101 @@
|
||||
import datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import subprocess
|
||||
import uuid
|
||||
from sessions import request, basic
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def command(args, input_text=None):
|
||||
result = subprocess.run(args, cwd=ROOT, input=input_text, text=True, encoding="utf-8", capture_output=True, timeout=90)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Command failed: " + " ".join(args[:4]) + ": " + result.stderr[:1000])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return command(["docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-qAt", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger"], statement)
|
||||
|
||||
|
||||
def nodes(plan):
|
||||
yield plan
|
||||
for child in plan.get("Plans", []):
|
||||
yield from nodes(child)
|
||||
|
||||
|
||||
def main():
|
||||
username = "explain_" + uuid.uuid4().hex[:20]
|
||||
password = "учебный:пароль:explain"
|
||||
user = request("POST", "/users", 201, {"username": username, "display_name": "EXPLAIN", "password": password})
|
||||
session = request("POST", "/auth/sessions", 201, headers=basic(username, password))
|
||||
headers = {"Authorization": "Bearer " + session["token"]}
|
||||
chat = request("POST", "/chats", 201, {"title": "History index experiment", "member_ids": [user["id"]]}, headers)
|
||||
# Validate identifiers before inserting them into this standalone experiment SQL.
|
||||
chat_id, user_id = str(uuid.UUID(chat["id"])), str(uuid.UUID(user["id"]))
|
||||
sql(f"""BEGIN;
|
||||
SET LOCAL statement_timeout='60s';
|
||||
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT gen_random_uuid(), '{chat_id}'::uuid, '{user_id}'::uuid,
|
||||
'synthetic message ' || n,
|
||||
CURRENT_TIMESTAMP - INTERVAL '1 day' + n * INTERVAL '1 millisecond'
|
||||
FROM generate_series(1,12000) AS n;
|
||||
COMMIT;
|
||||
ANALYZE messages;
|
||||
""")
|
||||
count = int(sql(f"SELECT count(*) FROM messages WHERE chat_id='{chat_id}'::uuid;"))
|
||||
assert count == 12000
|
||||
# OFFSET is used once to choose a fixture cursor, never in the measured page query.
|
||||
cursor = json.loads(sql(f"""SELECT row_to_json(p) FROM (
|
||||
SELECT created_at, id FROM messages WHERE chat_id='{chat_id}'::uuid
|
||||
ORDER BY created_at,id OFFSET 5999 LIMIT 1) p;"""))
|
||||
cursor_id = str(uuid.UUID(cursor["id"]))
|
||||
cursor_time = datetime.datetime.fromisoformat(cursor["created_at"]).isoformat()
|
||||
columns = "id::text,chat_id::text,sender_id::text,text,created_at"
|
||||
first = f"SELECT {columns} FROM messages WHERE chat_id=$1 ORDER BY messages.created_at,messages.id LIMIT $2"
|
||||
following = f"SELECT {columns} FROM messages WHERE chat_id=$1 AND (created_at,id)>($3,$4::uuid) ORDER BY messages.created_at,messages.id LIMIT $2"
|
||||
cases = {
|
||||
"first_page": (f"PREPARE history(uuid,integer) AS {first};", f"EXECUTE history('{chat_id}',51)"),
|
||||
"after_6000": (f"PREPARE history(uuid,integer,timestamptz,uuid) AS {following};", f"EXECUTE history('{chat_id}',51,'{cursor_time}','{cursor_id}')"),
|
||||
}
|
||||
metadata = {
|
||||
"date": "2026-10-09", "messages_in_chat": count, "chat_id": chat_id,
|
||||
"page_size": 50, "sql_limit": 51, "concurrency": 1, "warmups": 1, "repeats": 3,
|
||||
"postgres_version": sql("SHOW server_version;"),
|
||||
"docker_cpus_memory_bytes": command(["docker", "info", "--format", "{{.NCPU}} {{.MemTotal}}"]),
|
||||
"postgres_cpu_memory_limits": command(["docker", "inspect", "--format", "{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}", command(["docker", "compose", "ps", "-q", "postgres"])]),
|
||||
"method": "SQL-generated fixture; ANALYZE; prepared query; one warmup and three serial measurements; no concurrent writers",
|
||||
"limitations": "warm cache, one synthetic chat; not HTTP latency or throughput; no crash-durability measurement",
|
||||
"cases": {},
|
||||
}
|
||||
text_plans = []
|
||||
for name, (prepare, execute) in cases.items():
|
||||
sql(prepare + "\nEXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + execute + ";")
|
||||
plans = [json.loads(sql(prepare + "\nEXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + execute + ";"))[0] for _ in range(3)]
|
||||
for result in plans:
|
||||
tree = list(nodes(result["Plan"]))
|
||||
assert any(node.get("Index Name") == "messages_chat_history_idx" for node in tree), "history index not used"
|
||||
assert not any(node["Node Type"] == "Seq Scan" and node.get("Relation Name") == "messages" for node in tree), "full history scan"
|
||||
assert result["Plan"]["Actual Rows"] == 51
|
||||
scanned = [node for node in tree if node.get("Relation Name") == "messages"]
|
||||
assert all(node["Actual Rows"] <= 51 and node.get("Rows Removed by Filter", 0) == 0 for node in scanned), "page reads extra history"
|
||||
metadata["cases"][name] = {"prepare": prepare, "execute": execute, "plans": plans}
|
||||
text_plans.append(name + "\n" + prepare + "\n" + sql(prepare + "\nEXPLAIN (ANALYZE, BUFFERS) " + execute + ";"))
|
||||
median = statistics.median(plan["Execution Time"] for plan in plans)
|
||||
print(f"PASS: {name}: history index, 51 rows, no full scan; median SQL execution {median:.3f} ms")
|
||||
# Exercise the real HTTP cursor at the same position, not only SQL plans.
|
||||
import base64
|
||||
from urllib.parse import quote
|
||||
encoded = base64.urlsafe_b64encode(json.dumps({"scope": "messages:" + chat_id, "after": cursor}).encode()).decode().rstrip("=")
|
||||
page = request("GET", f"/chats/{chat_id}/messages?limit=50&cursor=" + quote(encoded), 200, headers=headers)
|
||||
assert len(page["items"]) == 50 and page["items"][0]["text"] == "synthetic message 6001"
|
||||
request("DELETE", "/auth/sessions/current", 204, headers=headers)
|
||||
(ROOT / "evidence/history-explain.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
(ROOT / "evidence/history-explain.txt").write_text("Date: 2026-10-09\nCommand: py student-tests/explain-history.py\nMessages: 12000\n\n" + "\n\n".join(text_plans) + "\n", encoding="utf-8")
|
||||
print("PASS: 12000 messages; HTTP cursor after 6000 returns message 6001; plans saved in evidence")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user