forked from mtusi2026/mtusi2026lab2
Prepare verified laboratory 2 implementation and evidence
This commit is contained in:
@@ -18,3 +18,6 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
.stress
|
||||
student-tests
|
||||
.local/
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
## Лабораторная 2
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
Автор / группа: Медведев Андрей Михайлович, БПИ2303
|
||||
Целевая оценка (3/4/5): 5
|
||||
Трек 5: 2 «План запроса и восстановление»
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
Что реализовано и что перенесено: PostgreSQL, миграции, Argon2id, общие persisted sessions и Valkey; исследование индекса и backup/restore. Собственный Go core перенесён из предыдущей лабы с объявленными изменениями API.
|
||||
Команды запуска из чистого clone: RUN.md, начиная с bootstrap и Compose build.
|
||||
Результаты проверок и ссылка на REPORT.md: REPORT.md; фактический вывод в evidence/, хеши проверенных исходников в evidence/SOURCE.sha256.
|
||||
Ограничения / известные ошибки: один host и общие зависимости; ограничения измерений и сценариев перечислены в REPORT.md.
|
||||
Источники и использование ИИ: оригинальный skeleton и собственная предыдущая работа; Codex использован для кода, тестов и отчёта. Независимый review сохранён в evidence/REVIEW.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 и RUN.md описывают моё решение.
|
||||
|
||||
@@ -30,3 +30,7 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
.stress
|
||||
.trash-1792138598/
|
||||
|
||||
.local/
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# Сборка: тег и digest закреплены, модули строго по go.sum (-mod=readonly).
|
||||
# Вместо слоя `go mod download` — cache mount: go.mod объявляет ещё и dev-
|
||||
# инструменты (oapi-codegen, golangci-lint), а `go mod download` тянул бы их
|
||||
# в образ сборки; `go build` скачивает только то, что нужно бинарнику.
|
||||
FROM golang:1.27.2-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d AS build
|
||||
WORKDIR /src
|
||||
ENV CGO_ENABLED=0 GOFLAGS=-mod=readonly
|
||||
COPY backend/ ./
|
||||
RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
--mount=type=cache,target=/root/.cache/go-build \
|
||||
go build -trimpath -ldflags='-s -w' -o /out/messenger ./cmd/app
|
||||
|
||||
# Runtime: только статический бинарник, без shell и пакетного менеджера,
|
||||
# пользователь nonroot (uid 65532).
|
||||
FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
COPY --from=build /out/messenger /messenger
|
||||
USER 65532:65532
|
||||
# GOMEMLIMIT рассчитан на запуск с --memory=256m (REPORT.md): GC начинает
|
||||
# работать активнее до того, как ядро убьёт процесс по OOM.
|
||||
ENV APP_HOST=0.0.0.0 APP_PORT=8080 GOMEMLIMIT=200MiB
|
||||
EXPOSE 8080
|
||||
# curl в образе нет: healthcheck — тот же бинарник с флагом.
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD ["/messenger", "-healthcheck"]
|
||||
STOPSIGNAL SIGTERM
|
||||
# Exec-форма: сервер — PID 1 и сам получает SIGTERM.
|
||||
ENTRYPOINT ["/messenger"]
|
||||
@@ -1,37 +1,59 @@
|
||||
# Отчёт — лабораторная 2
|
||||
# Лабораторная 2. PostgreSQL, сессии и Valkey
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
Автор: Медведев Андрей Михайлович, БПИ2303. Целевая оценка: 5, трек 2 «План запроса и восстановление». Оценку выставляет преподаватель; здесь описаны реализация и результаты проверок.
|
||||
|
||||
## Запуск из чистого clone
|
||||
Использованы Go 1.27.2, chi, oapi-codegen, pgx/v5, sqlc, goose, Argon2id и go-redis. Код, тесты и отчёт подготовлены при помощи Codex; независимый агент проверял транзакции, авторизацию, ресурсы и скрипты. Исходный skeleton: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2. Команды запуска и prerequisites находятся в [RUN.md](RUN.md).
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
## Архитектура
|
||||
|
||||
## Архитектура и решения
|
||||
PostgreSQL хранит пользователей, хеши паролей, сессии, чаты, членство и сообщения. Valkey кэширует только неизменяемые открытые профили на 60 секунд. История и сессии не кэшируются: запись сразу читается из PostgreSQL, logout действует и при отказе Valkey. Ошибка кэша приводит к ограниченному обходу кэша, а не к анонимному доступу.
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Из первой лабы перенесены доменные модели, keyset-пагинация, HTTP-адаптер, JSON-ошибки, ограниченная очередь и graceful shutdown. In-memory adapter заменён PostgreSQL. Core зависит от портов; SQL и HTTP-модели генерируются из схем, границы импортов проверяет depguard.
|
||||
|
||||
## Доказательства критериев
|
||||
Создание чата, списание квоты и вставка всех участников выполняются одной транзакцией. Квота сообщения и его запись также атомарны. Регистрацию защищает UNIQUE(username), остальные связи защищены внешними ключами. Сетевых вызовов Valkey внутри SQL-транзакций нет.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Пароль содержит 12–128 Unicode code points, включая UTF-8 и двоеточия. Argon2id использует случайную соль 16 байт, память 32 МиБ, два прохода, один поток и результат 32 байта. Bearer содержит 32 случайных байта; в БД хранится только SHA-256 токена. Это хеширование высокоэнтропийного токена, а не замена password KDF.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Basic разрешён только при создании сессии. Срок жизни по умолчанию 3600 секунд; Bearer проверяется в PostgreSQL на каждом защищённом запросе. Logout удаляет сессию, рестарт не продлевает expiry. X-User-Id не предоставляет доступ и не меняет владельца Bearer.
|
||||
|
||||
## Эксперименты и отказы
|
||||
Keyset-обход использует серверный timestamp PostgreSQL и UUID. Он стабилен для неизменного набора, но не является снимком: конкурентная транзакция может подтвердить строку с timestamp до уже пройденного курсора. Порядок подтверждения конкурентных записей не обещается.
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
## Ресурсы и воспроизводимость
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
API ограничен одним CPU и 512 МиБ, PostgreSQL двумя CPU и 768 МиБ, Valkey 0,25 CPU и 128 МиБ. Пул PostgreSQL по умолчанию содержит не более восьми соединений; PG_MAX_CONNS допускает 1–64. Connect timeout равен 1 секунде, statement timeout 2 секундам, lock timeout 1 секунде, контекст обычного запроса 5 секундам. Обход кэша ограничен 80 мс.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Одновременно исполняются не более четырёх API-запросов; очередь и время ожидания ограничены. JSON body ограничен 64 КиБ. На пользователя допускаются 1000 созданных чатов, 1 млн сообщений и 100 действующих сессий. Квоты списываются атомарно, подтверждённые сообщения не вытесняются.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Compose создаёт именованные volumes. Credentials генерируются в .local/, не выводятся и исключены из git и build context. Версии образов закреплены digest. Отдельный migrate service применяет goose до API; повторный запуск использует текущую версию миграций. scripts/compose.sh явно закрепляет manifest и имя проекта.
|
||||
|
||||
## Проверенные критерии
|
||||
|
||||
| Критерий | Проверка и результат | Доказательство |
|
||||
| --- | --- | --- |
|
||||
| Структура и OpenAPI | make check и полная валидация схемы | evidence/check.txt, evidence/validate.txt |
|
||||
| Обязательный API | Публичный smoke прошёл | evidence/smoke.txt |
|
||||
| Сохранность | Прежний токен и сообщения сохранились после рестарта API, PostgreSQL и Valkey | evidence/persistence.txt |
|
||||
| Аутентификация | Basic/Bearer, неверный пароль, logout, X-User-Id и короткий TTL проверены | evidence/failures.txt |
|
||||
| Регистрация | Один 201 и один 409 при конкурентном одинаковом username | evidence/acceptance.txt |
|
||||
| Rollback | Неизвестный участник даёт 400, чат не появляется | evidence/acceptance.txt |
|
||||
| Доступ и страницы | Чужой чат скрыт; limit и обход без потерь/повторов проверены | evidence/acceptance.txt |
|
||||
| Отказ кэша | Действующая сессия работает через PostgreSQL, анонимного доступа нет | evidence/failures.txt |
|
||||
| Отказ БД | Запрос и readiness дают 503, liveness работает | evidence/failures.txt |
|
||||
| Индекс истории | 100 тыс. сообщений, два индекса и стоимость вставок | evidence/research/run-16q3rN/ |
|
||||
| Восстановление | Бэкап восстановлен в отдельный PostgreSQL container/volume | evidence/research/run-16q3rN/summary.json |
|
||||
|
||||
## Исследование индекса и восстановления
|
||||
|
||||
Гипотеза: индекс только по chat_id требует сортировки оставшейся истории, а составной `(chat_id,created_at,id)` позволяет сразу читать продолжение в порядке ключей. Создано 100 000 сообщений в трёх чатах с распределением 90 000 / 9000 / 1000. Для горячего чата запрошена глубокая страница из 51 строки после позиции 70 000; дополнительная строка определяет next_cursor.
|
||||
|
||||
EXPLAIN (ANALYZE, BUFFERS) дал 7,009 → 0,072 мс. Вставка 1000 строк заняла 16,243 → 16,610 мс. Это наблюдение одной пары на данном наборе, а не универсальная оценка стоимости записи. Польза чтения также подтверждается планом и отсутствием сортировки большой оставшейся истории; все исходные планы сохранены.
|
||||
|
||||
Затем pg_dump восстановлен в новую БД отдельного PostgreSQL с собственным volume. Бэкап содержит 3 034 766 байт; создание заняло примерно 0,49 секунды, pg_restore в подготовленную БД примерно 1,51 секунды. Сошлись 7 пользователей, 5 чатов, 7 membership и 102 003 сообщения, включая 102 000 исследовательских строк после двух серий вставок. Совпали ID, текст и время выбранных сообщений.
|
||||
|
||||
API был остановлен на время снимка, поэтому потери относительно снимка для этой остановленной нагрузки нет. Время pg_restore не включает подготовку host/образа, переключение приложения и восстановление трафика. Непрерывное восстановление по WAL, репликация PostgreSQL и отказ host не реализованы.
|
||||
|
||||
Исследовательский скрипт создаёт отдельный каталог запуска, проверяет отсутствие игры, восстанавливает штатный индекс и API, удаляет только собственные исследовательские UUID. PASS и итоговый summary появляются после уборки. Новый запуск не подменяет старое успешное доказательство.
|
||||
|
||||
## Защита
|
||||
|
||||
Показать регистрацию и Basic-вход, чтение по Bearer и отказ X-User-Id. Запустить persistence hook и прочитать прежнее сообщение тем же токеном, затем выполнить logout и получить 401. Объяснить разницу COMMIT и backup, роль кэша и составного индекса. Показать план запроса и результаты восстановления, отдельно назвать неподдержанные отказы.
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# Запуск лабораторной 2
|
||||
|
||||
Автор: Медведев Андрей Михайлович, БПИ2303. Исходное задание и контракт сохранены в README.md и contracts/. Реализация находится в backend/, дополнительные проверки в student-tests/.
|
||||
|
||||
Нужны Docker Engine с Compose, Bun 1.4 и Python 3.9+. Для Go-тестов на хосте нужен Go 1.27.2 или новее. Проверенный стенд: Linux x86_64, Docker 29.9.2, Compose 5.6.1, Bun 1.4.4; образ компилируется Go 1.27.2. Образы PostgreSQL 18.6 и Valkey 9 закреплены digest в compose.yaml.
|
||||
|
||||
Команды выполняются из этого каталога. scripts/compose.sh закрепляет manifest и имя vp-lab2-medvedev, чтобы переменные другого проекта не перенаправили операции.
|
||||
|
||||
```sh
|
||||
bun --no-env-file scripts/bootstrap.ts
|
||||
./scripts/compose.sh up -d --build
|
||||
BASE_URL=http://127.0.0.1:28202 bun --no-env-file student-tests/wait.ts
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip install -r requirements-dev.txt
|
||||
make check
|
||||
make validate PYTHON=.venv/bin/python
|
||||
make test BASE_URL=http://127.0.0.1:28202
|
||||
BASE_URL=http://127.0.0.1:28202 bun --no-env-file student-tests/acceptance.ts
|
||||
make test-persistence BASE_URL=http://127.0.0.1:28202 ACTION_SCRIPT=scripts/restart.sh
|
||||
cd backend
|
||||
go test -race ./...
|
||||
go tool golangci-lint run
|
||||
go generate ./...
|
||||
```
|
||||
|
||||
Bootstrap создаёт отдельные случайные учебные credentials в .local/ и не печатает их. Каталог исключён из git и Docker context. Существующие файлы не перезаписываются. Миграции запускает отдельный service migrate; API не выполняет их конкурентно.
|
||||
|
||||
HTTP доступен только через localhost. Все данные тестов синтетические; публичные тесты сохраняют свой набор данных для демонстрации, дополнительные acceptance-тесты удаляют только свой случайный набор. Пароли и сессии не выводятся в отчёты.
|
||||
|
||||
Обычная остановка сохраняет volumes:
|
||||
|
||||
```sh
|
||||
./scripts/compose.sh stop
|
||||
```
|
||||
|
||||
Повторный запуск с сохранением данных:
|
||||
|
||||
```sh
|
||||
./scripts/compose.sh up -d
|
||||
```
|
||||
|
||||
Только для намеренного полного сброса собственных учебных данных:
|
||||
|
||||
```sh
|
||||
./scripts/compose.sh down --volumes
|
||||
```
|
||||
|
||||
Проверка отказов БД/кэша и короткого срока сессии:
|
||||
|
||||
```sh
|
||||
FAILURES=1 BASE_URL=http://127.0.0.1:28202 bun --no-env-file student-tests/acceptance.ts
|
||||
```
|
||||
|
||||
Исследование трека 2 запускается на omarchy без игры после обычного bootstrap и сборки. Скрипт сам проверяет game-running, останавливает API на время снимка, использует отдельный PostgreSQL для восстановления и возвращает API после очистки своего набора. Публичные демонстрационные данные сохраняются.
|
||||
|
||||
```sh
|
||||
bun --no-env-file student-tests/research.ts
|
||||
```
|
||||
|
||||
Новый результат появляется в evidence/research/run-*/summary.json. Для графика установите requirements-plots.txt в .venv и передайте файл конкретного завершённого запуска:
|
||||
|
||||
```sh
|
||||
.venv/bin/pip install -r requirements-plots.txt
|
||||
.venv/bin/python student-tests/plot_research.py evidence/research/run-16q3rN/summary.json
|
||||
```
|
||||
|
||||
Последняя команда воспроизводит приложенный график; для нового эксперимента подставьте его каталог. Подтверждённые результаты и ограничения перечислены в REPORT.md. Автоматические проверки не выставляют оценку преподавателя.
|
||||
@@ -0,0 +1,36 @@
|
||||
version: "2"
|
||||
run:
|
||||
allow-parallel-runners: true
|
||||
linters:
|
||||
default: standard
|
||||
enable: [depguard]
|
||||
settings:
|
||||
errcheck:
|
||||
# Close тела ответа и файла, открытого на чтение: ошибке некуда деться.
|
||||
exclude-functions:
|
||||
- (io.ReadCloser).Close
|
||||
- (*os.File).Close
|
||||
depguard:
|
||||
rules:
|
||||
# Гексагон: ядро и use-case'ы зависят от портов, а не от адаптеров и транспорта.
|
||||
inner-pure:
|
||||
files: ["**/internal/domain/**", "**/internal/application/**"]
|
||||
deny:
|
||||
- pkg: backend/internal/adapter
|
||||
desc: домен и приложение зависят от портов, не от адаптеров
|
||||
- pkg: backend/internal/config
|
||||
desc: конфиг читает только cmd
|
||||
- pkg: net/http
|
||||
desc: HTTP только в adapter/handler
|
||||
- pkg: github.com/go-chi
|
||||
desc: роутер только в adapter/handler
|
||||
- pkg: github.com/rs/zerolog
|
||||
desc: логирование на границе, в адаптерах
|
||||
domain-core:
|
||||
files: ["**/internal/domain/**"]
|
||||
deny:
|
||||
- pkg: backend/internal/application
|
||||
desc: домен не знает о use-case'ах
|
||||
exclusions:
|
||||
paths:
|
||||
- ".*\\.gen\\.go$"
|
||||
@@ -0,0 +1,133 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"backend/db"
|
||||
"backend/internal/adapter/handler"
|
||||
"backend/internal/adapter/password"
|
||||
"backend/internal/adapter/repository/postgres"
|
||||
"backend/internal/application/usecase"
|
||||
"backend/internal/config"
|
||||
"backend/pkg/logger"
|
||||
"backend/pkg/server"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func main() {
|
||||
healthcheck := flag.Bool("healthcheck", false, "проверить /health/ready и выйти (для Docker HEALTHCHECK)")
|
||||
migrate := flag.Bool("migrate", false, "apply migrations and exit")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "config:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if *healthcheck {
|
||||
os.Exit(probe(cfg.Port))
|
||||
}
|
||||
|
||||
log := logger.New(cfg.LogLevel)
|
||||
dsn, err := config.ReadSecret(cfg.DatabaseURLFile)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("database secret unavailable")
|
||||
}
|
||||
if *migrate {
|
||||
if err = db.Migrate(context.Background(), dsn); err != nil {
|
||||
log.Fatal().Err(err).Msg("migration failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
pc, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("invalid database configuration")
|
||||
}
|
||||
pc.MaxConns = cfg.MaxConns
|
||||
pc.MinConns = 0
|
||||
pc.ConnConfig.ConnectTimeout = time.Second
|
||||
pc.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
|
||||
pc.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), pc)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("database initialization failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
var cache *redis.Client
|
||||
if url, e := config.ReadSecret(cfg.CacheURLFile); e == nil {
|
||||
opts, e := redis.ParseURL(url)
|
||||
if e != nil {
|
||||
log.Fatal().Msg("invalid cache configuration")
|
||||
}
|
||||
opts.MaxRetries = 0
|
||||
opts.DialTimeout = 80 * time.Millisecond
|
||||
opts.ReadTimeout = 80 * time.Millisecond
|
||||
opts.WriteTimeout = 80 * time.Millisecond
|
||||
cache = redis.NewClient(opts)
|
||||
defer func(){_ = cache.Close()}()
|
||||
}
|
||||
store := postgres.New(pool, cache)
|
||||
app := usecase.NewMessenger(store)
|
||||
auth := usecase.NewAuth(store, password.New(), app, time.Duration(cfg.SessionTTLSeconds)*time.Second, time.Now)
|
||||
h := handler.New(app, auth, pool.Ping, handler.Limits{
|
||||
MaxBodyBytes: cfg.MaxBodyBytes,
|
||||
MaxInflight: cfg.MaxInflight,
|
||||
MaxQueue: cfg.MaxQueue,
|
||||
QueueTimeout: cfg.QueueTimeout,
|
||||
}, func() any {
|
||||
return map[string]any{"pool_total": pool.Stat().TotalConns(), "pool_acquired": pool.Stat().AcquiredConns(),"pool_max":pool.Stat().MaxConns()}
|
||||
}, &log)
|
||||
srv := server.New(cfg.Addr(), h.Router())
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
serveErr := make(chan error, 1)
|
||||
go func() { serveErr <- srv.ListenAndServe() }()
|
||||
log.Info().Str("addr", cfg.Addr()).Str("env", cfg.Env).
|
||||
Int("max_inflight", cfg.MaxInflight).
|
||||
Int("max_queue", cfg.MaxQueue).Msg("server started")
|
||||
|
||||
select {
|
||||
case err := <-serveErr:
|
||||
log.Fatal().Err(err).Msg("server failed")
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
log.Info().Dur("timeout", cfg.ShutdownTimeout).Msg("shutdown signal received, draining")
|
||||
h.Drain()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Error().Err(err).Msg("shutdown timed out, open requests aborted")
|
||||
}
|
||||
if err := <-serveErr; err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Error().Err(err).Msg("server error")
|
||||
}
|
||||
log.Info().Dur("took", time.Since(started)).Msg("shutdown complete")
|
||||
}
|
||||
|
||||
// probe — healthcheck без curl в образе distroless: сам бинарник ходит в
|
||||
// /health/ready и возвращает код выхода для Docker.
|
||||
func probe(port int) int {
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/health/ready", port))
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package: handler
|
||||
generate:
|
||||
models: true
|
||||
chi-server: true
|
||||
strict-server: true
|
||||
output: api.gen.go
|
||||
output-options:
|
||||
# date-time -> handler.Timestamp: ровно 6 цифр дробной части (см. timestamp.go)
|
||||
type-mapping:
|
||||
string:
|
||||
formats:
|
||||
date-time:
|
||||
type: Timestamp
|
||||
@@ -0,0 +1,25 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrations embed.FS
|
||||
|
||||
func Migrate(ctx context.Context, dsn string) error {
|
||||
conn, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func(){_ = conn.Close()}()
|
||||
goose.SetBaseFS(migrations)
|
||||
if err = goose.SetDialect("postgres"); err != nil {
|
||||
return err
|
||||
}
|
||||
return goose.UpContext(ctx, conn, "migrations")
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
chat_count integer NOT NULL DEFAULT 0 CHECK (chat_count BETWEEN 0 AND 1000),
|
||||
message_count integer NOT NULL DEFAULT 0 CHECK (message_count BETWEEN 0 AND 1000000)
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX member_chats ON chat_members(user_id,chat_id);
|
||||
CREATE INDEX chats_order ON chats(created_at,id);
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id,sender_id) REFERENCES chat_members(chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX messages_history ON messages(chat_id,created_at,id);
|
||||
CREATE TABLE sessions (
|
||||
token_hash text PRIMARY KEY CHECK (length(token_hash)=64),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_user ON sessions(user_id,expires_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE sessions;
|
||||
DROP TABLE messages;
|
||||
DROP TABLE chat_members;
|
||||
DROP TABLE chats;
|
||||
DROP TABLE users;
|
||||
@@ -0,0 +1,41 @@
|
||||
-- name: CreateUser :one
|
||||
INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
|
||||
RETURNING id,username,display_name,created_at;
|
||||
-- name: GetUser :one
|
||||
SELECT id,username,display_name,created_at FROM users WHERE id=$1;
|
||||
-- name: Credentials :one
|
||||
SELECT id,password_hash FROM users WHERE username=$1;
|
||||
-- name: ChargeChat :one
|
||||
UPDATE users SET chat_count=chat_count+1 WHERE id=$1 AND chat_count<1000 RETURNING id;
|
||||
-- name: ChargeMessage :one
|
||||
UPDATE users SET message_count=message_count+1 WHERE id=$1 AND message_count<1000000 RETURNING id;
|
||||
-- name: InsertChat :one
|
||||
INSERT INTO chats(id,title) VALUES($1,$2) RETURNING id,title,created_at;
|
||||
-- name: InsertMembers :exec
|
||||
INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[]);
|
||||
-- name: GetChat :one
|
||||
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
|
||||
FROM chats c WHERE c.id=$1;
|
||||
-- name: ListChats :many
|
||||
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
|
||||
FROM chats c JOIN chat_members m ON m.chat_id=c.id
|
||||
WHERE m.user_id=sqlc.arg(member_id) AND (c.created_at,c.id)>(sqlc.arg(after_time)::timestamptz,sqlc.arg(after_id)::uuid)
|
||||
ORDER BY c.created_at,c.id LIMIT sqlc.arg(page_limit);
|
||||
-- name: InsertMessage :one
|
||||
INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING id,chat_id,sender_id,text,created_at;
|
||||
-- name: ListMessages :many
|
||||
SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=$1 AND (created_at,id)>(sqlc.arg(after_time)::timestamptz,sqlc.arg(after_id)::uuid)
|
||||
ORDER BY created_at,id LIMIT sqlc.arg(page_limit);
|
||||
-- name: LockSessionOwner :one
|
||||
SELECT id FROM users WHERE id=$1 FOR UPDATE;
|
||||
-- name: DeleteExpiredSessions :exec
|
||||
DELETE FROM sessions WHERE user_id=$1 AND expires_at<=clock_timestamp();
|
||||
-- name: InsertSession :one
|
||||
INSERT INTO sessions(token_hash,user_id,expires_at)
|
||||
SELECT $1,$2,$3 WHERE (SELECT count(*) FROM sessions WHERE user_id=$2)<100
|
||||
RETURNING user_id;
|
||||
-- name: AuthenticateSession :one
|
||||
SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp();
|
||||
-- name: RevokeSession :exec
|
||||
DELETE FROM sessions WHERE token_hash=$1;
|
||||
@@ -0,0 +1,16 @@
|
||||
version: '2'
|
||||
sql:
|
||||
- schema: ../migrations
|
||||
queries: queries
|
||||
engine: postgresql
|
||||
gen:
|
||||
go:
|
||||
package: queries
|
||||
out: ../../internal/adapter/repository/postgres/queries
|
||||
sql_package: pgx/v5
|
||||
emit_empty_slices: true
|
||||
overrides:
|
||||
- db_type: uuid
|
||||
go_type: github.com/google/uuid.UUID
|
||||
- db_type: timestamptz
|
||||
go_type: time.Time
|
||||
+321
@@ -0,0 +1,321 @@
|
||||
module backend
|
||||
|
||||
go 1.27.2
|
||||
|
||||
tool (
|
||||
github.com/golangci/golangci-lint/v2/cmd/golangci-lint
|
||||
github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen
|
||||
github.com/pressly/goose/v3/cmd/goose
|
||||
github.com/sqlc-dev/sqlc/cmd/sqlc
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.5.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/oapi-codegen/runtime v1.7.0
|
||||
github.com/rs/zerolog v1.35.1
|
||||
github.com/spf13/viper v1.21.0
|
||||
)
|
||||
|
||||
require (
|
||||
4d63.com/gocheckcompilerdirectives v1.4.0 // indirect
|
||||
4d63.com/gochecknoglobals v0.2.2 // indirect
|
||||
cel.dev/expr v0.25.3 // indirect
|
||||
charm.land/lipgloss/v2 v2.0.6 // indirect
|
||||
codeberg.org/chavacava/garif v0.2.1 // indirect
|
||||
codeberg.org/polyfloyd/go-errorlint v1.9.0 // indirect
|
||||
dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect
|
||||
dev.gaijin.team/go/exhaustruct/v5 v5.2.0 // indirect
|
||||
dev.gaijin.team/go/golib v0.8.1 // indirect
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/4meepo/tagalign v1.4.4 // indirect
|
||||
github.com/Abirdcfly/dupword v0.1.8 // indirect
|
||||
github.com/AdminBenni/iota-mixing v1.0.0 // indirect
|
||||
github.com/AlwxSin/noinlineerr v1.0.6 // indirect
|
||||
github.com/Antonboom/errname v1.1.2 // indirect
|
||||
github.com/Antonboom/nilnil v1.1.2 // indirect
|
||||
github.com/Antonboom/testifylint v1.6.4 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 // indirect
|
||||
github.com/BurntSushi/toml v1.6.0 // indirect
|
||||
github.com/ClickHouse/ch-go v0.75.0 // indirect
|
||||
github.com/ClickHouse/clickhouse-go-linter v1.2.1 // indirect
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.51.0 // indirect
|
||||
github.com/Djarvur/go-err113 v0.1.1 // indirect
|
||||
github.com/Masterminds/semver/v3 v3.5.0 // indirect
|
||||
github.com/MirrexOne/unqueryvet v1.5.4 // indirect
|
||||
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
|
||||
github.com/alecthomas/chroma/v2 v2.27.0 // indirect
|
||||
github.com/alecthomas/go-check-sumtype v0.5.1-0.20260828200218-ae6904d28606 // indirect
|
||||
github.com/alexkohler/nakedret/v2 v2.0.6 // indirect
|
||||
github.com/alexkohler/prealloc v1.1.0 // indirect
|
||||
github.com/alfatraining/structtag v1.0.0 // indirect
|
||||
github.com/alingse/asasalint v0.0.11 // indirect
|
||||
github.com/alingse/nilnesserr v0.2.0 // indirect
|
||||
github.com/andybalholm/brotli v1.3.0 // indirect
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
|
||||
github.com/ashanbrown/forbidigo/v2 v2.3.1 // indirect
|
||||
github.com/ashanbrown/makezero/v2 v2.2.1 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bkielbasa/cyclop v1.2.3 // indirect
|
||||
github.com/blizzy78/varnamelen v0.8.0 // indirect
|
||||
github.com/bombsimon/wsl/v4 v4.7.0 // indirect
|
||||
github.com/bombsimon/wsl/v5 v5.9.0 // indirect
|
||||
github.com/breml/bidichk v0.3.3 // indirect
|
||||
github.com/breml/errchkjson v0.4.1 // indirect
|
||||
github.com/butuzov/ireturn v0.4.1 // indirect
|
||||
github.com/butuzov/mirror v1.3.3 // indirect
|
||||
github.com/catenacyber/perfsprint v0.10.1 // indirect
|
||||
github.com/ccojocar/zxcvbn-go v1.0.4 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/charithe/durationcheck v0.0.11 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.3 // indirect
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.8 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
github.com/charmbracelet/x/termios v0.1.1 // indirect
|
||||
github.com/charmbracelet/x/windows v0.2.2 // indirect
|
||||
github.com/ckaznocha/intrange v0.3.1 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/coreos/go-semver v0.3.1 // indirect
|
||||
github.com/cubicdaiya/gonp v1.0.4 // indirect
|
||||
github.com/curioswitch/go-reassign v0.3.0 // indirect
|
||||
github.com/daixiang0/gci v0.13.7 // indirect
|
||||
github.com/dave/dst v0.27.3 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/denis-tingaikin/go-header v0.5.0 // indirect
|
||||
github.com/dlclark/regexp2/v2 v2.2.1 // indirect
|
||||
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
|
||||
github.com/dustin/go-humanize v1.1.0 // indirect
|
||||
github.com/elastic/go-sysinfo v1.15.5 // indirect
|
||||
github.com/elastic/go-windows v1.0.2 // indirect
|
||||
github.com/ettle/strcase v0.2.0 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/fatih/structtag v1.2.0 // indirect
|
||||
github.com/firefart/nonamedreturns v1.0.8 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/fzipp/gocyclo v0.6.0 // indirect
|
||||
github.com/getkin/kin-openapi v0.142.0 // indirect
|
||||
github.com/ghostiam/protogetter v1.0.1 // indirect
|
||||
github.com/go-critic/go-critic v0.15.0 // indirect
|
||||
github.com/go-faster/city v1.0.1 // indirect
|
||||
github.com/go-faster/errors v0.8.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.23.1 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.26.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.10.1 // indirect
|
||||
github.com/go-toolsmith/astcast v1.1.0 // indirect
|
||||
github.com/go-toolsmith/astcopy v1.1.0 // indirect
|
||||
github.com/go-toolsmith/astequal v1.2.0 // indirect
|
||||
github.com/go-toolsmith/astfmt v1.1.0 // indirect
|
||||
github.com/go-toolsmith/astp v1.1.0 // indirect
|
||||
github.com/go-toolsmith/strparse v1.1.0 // indirect
|
||||
github.com/go-toolsmith/typep v1.1.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/godoc-lint/godoc-lint v0.11.4 // indirect
|
||||
github.com/gofrs/flock v0.13.1 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
|
||||
github.com/golang-sql/sqlexp v0.1.0 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/golangci/asciicheck v0.5.0 // indirect
|
||||
github.com/golangci/canonicalheader v0.0.0-20260827115959-a25c71c521f6 // indirect
|
||||
github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 // indirect
|
||||
github.com/golangci/go-printf-func-name v0.1.1 // indirect
|
||||
github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792 // indirect
|
||||
github.com/golangci/golangci-lint/v2 v2.14.0 // indirect
|
||||
github.com/golangci/golines v0.15.0 // indirect
|
||||
github.com/golangci/misspell v0.8.0 // indirect
|
||||
github.com/golangci/plugin-module-register v0.1.2 // indirect
|
||||
github.com/golangci/revgrep v0.8.0 // indirect
|
||||
github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba // indirect
|
||||
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect
|
||||
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect
|
||||
github.com/google/cel-go v0.28.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/gordonklaus/ineffassign v0.2.0 // indirect
|
||||
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
|
||||
github.com/gostaticanalysis/comment v1.5.0 // indirect
|
||||
github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect
|
||||
github.com/gostaticanalysis/nilerr v0.1.2 // indirect
|
||||
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect
|
||||
github.com/hashicorp/go-version v1.9.0 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/hexops/gotextdiff v1.0.3 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.13.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||
github.com/jgautheron/goconst v1.11.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jjti/go-spancheck v0.6.5 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/jonboulle/clockwork v0.5.0 // indirect
|
||||
github.com/julz/importas v0.2.0 // indirect
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect
|
||||
github.com/kisielk/errcheck v1.20.0 // indirect
|
||||
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/kulti/thelper v0.7.1 // indirect
|
||||
github.com/kunwardeep/paralleltest v1.0.15 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/ldez/exptostd v0.4.5 // indirect
|
||||
github.com/ldez/gomoddirectives v0.10.0 // indirect
|
||||
github.com/ldez/grignotin v0.10.1 // indirect
|
||||
github.com/ldez/structtags v0.6.1 // indirect
|
||||
github.com/ldez/tagliatelle v0.8.0 // indirect
|
||||
github.com/ldez/usetesting v0.5.0 // indirect
|
||||
github.com/leonklingele/grouper v1.1.2 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
|
||||
github.com/macabu/inamedparam v0.2.0 // indirect
|
||||
github.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect
|
||||
github.com/manuelarte/funcorder v0.6.0 // indirect
|
||||
github.com/maratori/testableexamples v1.0.1 // indirect
|
||||
github.com/maratori/testpackage v1.1.2 // indirect
|
||||
github.com/matoous/godox v1.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.24 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||
github.com/mfridman/xflag v0.1.0 // indirect
|
||||
github.com/mgechev/revive v1.17.0 // indirect
|
||||
github.com/microsoft/go-mssqldb v1.11.2 // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/moricho/tparallel v0.3.2 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/nakabonne/nestif v0.3.1 // indirect
|
||||
github.com/ncruces/go-sqlite3 v0.32.0 // indirect
|
||||
github.com/ncruces/go-strftime v1.1.0 // indirect
|
||||
github.com/ncruces/julianday v1.0.0 // indirect
|
||||
github.com/nishanths/exhaustive v0.13.0 // indirect
|
||||
github.com/nishanths/predeclared v0.2.2 // indirect
|
||||
github.com/nunnatsa/ginkgolinter v0.24.0 // indirect
|
||||
github.com/oapi-codegen/oapi-codegen/v2 v2.8.0 // indirect
|
||||
github.com/oasdiff/yaml v0.1.1 // indirect
|
||||
github.com/oasdiff/yaml3 v0.0.14 // indirect
|
||||
github.com/paulmach/orb v0.14.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/pganalyze/pg_query_go/v6 v6.2.2 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.33 // indirect
|
||||
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee // indirect
|
||||
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect
|
||||
github.com/pingcap/log v1.1.0 // indirect
|
||||
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pressly/goose/v3 v3.30.0 // indirect
|
||||
github.com/prometheus/client_golang v1.12.1 // indirect
|
||||
github.com/prometheus/client_model v0.2.0 // indirect
|
||||
github.com/prometheus/common v0.32.1 // indirect
|
||||
github.com/prometheus/procfs v0.23.0 // indirect
|
||||
github.com/quasilyte/go-ruleguard v0.4.5 // indirect
|
||||
github.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect
|
||||
github.com/quasilyte/gogrep v0.5.0 // indirect
|
||||
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect
|
||||
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
|
||||
github.com/raeperd/recvcheck v0.3.1 // indirect
|
||||
github.com/redis/go-redis/v9 v9.23.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/riza-io/grpc-go v0.2.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.16.0 // indirect
|
||||
github.com/ryancurrah/gomodguard v1.4.1 // indirect
|
||||
github.com/ryancurrah/gomodguard/v2 v2.1.3 // indirect
|
||||
github.com/ryanrolds/sqlclosecheck v0.6.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
|
||||
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
|
||||
github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect
|
||||
github.com/securego/gosec/v2 v2.29.0 // indirect
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
||||
github.com/shopspring/decimal v1.6.0 // indirect
|
||||
github.com/sirupsen/logrus v1.10.2 // indirect
|
||||
github.com/sivchari/containedctx v1.0.3 // indirect
|
||||
github.com/sonatard/noctx v0.5.1 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/sourcegraph/go-diff v0.9.0 // indirect
|
||||
github.com/speakeasy-api/jsonpath v0.6.3 // indirect
|
||||
github.com/speakeasy-api/openapi v1.24.0 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/cobra v1.10.2 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/sqlc-dev/doubleclick v1.0.0 // indirect
|
||||
github.com/sqlc-dev/sqlc v1.31.1 // indirect
|
||||
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
|
||||
github.com/stbenjam/no-sprintf-host-port v0.3.1 // indirect
|
||||
github.com/stretchr/objx v0.5.3 // indirect
|
||||
github.com/stretchr/testify v1.12.1 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/tetafro/godot v1.5.6 // indirect
|
||||
github.com/tetratelabs/wazero v1.11.0 // indirect
|
||||
github.com/timakin/bodyclose v0.0.0-20260723120731-857993a2939c // indirect
|
||||
github.com/timonwong/loggercheck v0.12.0 // indirect
|
||||
github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect
|
||||
github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect
|
||||
github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60 // indirect
|
||||
github.com/ultraware/funlen v0.2.0 // indirect
|
||||
github.com/ultraware/whitespace v0.2.0 // indirect
|
||||
github.com/uudashr/gocognit v1.2.1 // indirect
|
||||
github.com/uudashr/iface v1.5.1 // indirect
|
||||
github.com/vertica/vertica-sql-go v1.3.9 // indirect
|
||||
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
|
||||
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 // indirect
|
||||
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
|
||||
github.com/xen0n/gosmopolitan v1.3.0 // indirect
|
||||
github.com/xo/terminfo v1.0.0 // indirect
|
||||
github.com/yagipy/maintidx v1.0.0 // indirect
|
||||
github.com/yandex-cloud/go-genproto v0.137.0 // indirect
|
||||
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260810123728-f0c151ab31b9 // indirect
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.3 // indirect
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.156.1 // indirect
|
||||
github.com/ydb-platform/ydb-go-yc v0.12.5 // indirect
|
||||
github.com/ydb-platform/ydb-go-yc-metadata v0.6.2 // indirect
|
||||
github.com/yeya24/promlinter v0.3.0 // indirect
|
||||
github.com/ykadowak/zerologlint v0.1.5 // indirect
|
||||
github.com/ziutek/mymysql v1.5.4 // indirect
|
||||
gitlab.com/bosi/decorder v0.4.2 // indirect
|
||||
go-simpler.org/musttag v0.14.0 // indirect
|
||||
go-simpler.org/sloglint v0.12.0 // indirect
|
||||
go.augendre.info/arangolint v0.4.0 // indirect
|
||||
go.augendre.info/fatcontext v0.10.1 // indirect
|
||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.6 // indirect
|
||||
golang.org/x/crypto v0.59.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 // indirect
|
||||
golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect
|
||||
golang.org/x/mod v0.42.0 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect
|
||||
google.golang.org/grpc v1.85.0 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
honnef.co/go/tools v0.8.1 // indirect
|
||||
howett.net/plist v1.0.1 // indirect
|
||||
modernc.org/libc v1.80.2 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.12.1 // indirect
|
||||
modernc.org/sqlite v1.62.0 // indirect
|
||||
mvdan.cc/gofumpt v0.12.0 // indirect
|
||||
mvdan.cc/unparam v0.0.0-20260823230713-2fa3d841b0c8 // indirect
|
||||
)
|
||||
+1275
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,100 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
)
|
||||
|
||||
// Реализация StrictServerInterface: вызвать use-case и перевести результат в
|
||||
// API-модели. Ошибки уходят в writeError, он один решает про HTTP-статус.
|
||||
|
||||
func (h *API) Liveness(context.Context, LivenessRequestObject) (LivenessResponseObject, error) {
|
||||
return Liveness200JSONResponse{Body: Health{Status: Ok}}, nil
|
||||
}
|
||||
|
||||
// Readiness rejects draining instances and unavailable required dependencies.
|
||||
func (h *API) Readiness(ctx context.Context, _ ReadinessRequestObject) (ReadinessResponseObject, error) {
|
||||
if !h.ready.Load() {
|
||||
return nil, errDraining
|
||||
}
|
||||
if err := h.probe(ctx); err != nil {
|
||||
return nil, model.ErrUnavailable
|
||||
}
|
||||
return Readiness200JSONResponse{Body: Health{Status: Ok}}, nil
|
||||
}
|
||||
|
||||
func (h *API) RegisterUser(ctx context.Context, req RegisterUserRequestObject) (RegisterUserResponseObject, error) {
|
||||
if req.Body.Password == nil {
|
||||
return nil, &model.ValidationError{Message: "password is required"}
|
||||
}
|
||||
user, err := h.auth.Register(ctx, req.Body.Username, req.Body.DisplayName, *req.Body.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return RegisterUser201JSONResponse{Body: toUser(user)}, nil
|
||||
}
|
||||
|
||||
func (h *API) CurrentUser(ctx context.Context, _ CurrentUserRequestObject) (CurrentUserResponseObject, error) {
|
||||
return CurrentUser200JSONResponse{Body: toUser(currentUser(ctx))}, nil
|
||||
}
|
||||
|
||||
func (h *API) CreateChat(ctx context.Context, req CreateChatRequestObject) (CreateChatResponseObject, error) {
|
||||
chat, err := h.app.CreateChat(ctx, currentUser(ctx).ID, req.Body.Title, req.Body.MemberIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return CreateChat201JSONResponse{Body: toChat(chat)}, nil
|
||||
}
|
||||
|
||||
func (h *API) ListChats(ctx context.Context, req ListChatsRequestObject) (ListChatsResponseObject, error) {
|
||||
page, err := h.app.ListChats(ctx, currentUser(ctx).ID, req.Params.Limit, req.Params.Cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ListChats200JSONResponse{Body: ChatPage{Items: mapAll(page.Items, toChat), NextCursor: page.NextCursor}}, nil
|
||||
}
|
||||
|
||||
func (h *API) GetChat(ctx context.Context, req GetChatRequestObject) (GetChatResponseObject, error) {
|
||||
chat, err := h.app.GetChat(ctx, currentUser(ctx).ID, req.ChatId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return GetChat200JSONResponse{Body: toChat(chat)}, nil
|
||||
}
|
||||
|
||||
func (h *API) CreateMessage(ctx context.Context, req CreateMessageRequestObject) (CreateMessageResponseObject, error) {
|
||||
msg, err := h.app.SendMessage(ctx, currentUser(ctx).ID, req.ChatId, req.Body.Text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return CreateMessage201JSONResponse{Body: toMessage(msg)}, nil
|
||||
}
|
||||
|
||||
func (h *API) ListMessages(ctx context.Context, req ListMessagesRequestObject) (ListMessagesResponseObject, error) {
|
||||
page, err := h.app.ListMessages(ctx, currentUser(ctx).ID, req.ChatId, req.Params.Limit, req.Params.Cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ListMessages200JSONResponse{Body: MessagePage{Items: mapAll(page.Items, toMessage), NextCursor: page.NextCursor}}, nil
|
||||
}
|
||||
|
||||
func toUser(u model.User) User {
|
||||
return User{Id: u.ID, Username: u.Username, DisplayName: u.DisplayName, CreatedAt: Timestamp(u.CreatedAt)}
|
||||
}
|
||||
|
||||
func toChat(c model.Chat) Chat {
|
||||
return Chat{Id: c.ID, Title: c.Title, MemberIds: c.MemberIDs, CreatedAt: Timestamp(c.CreatedAt)}
|
||||
}
|
||||
|
||||
func toMessage(m model.Message) Message {
|
||||
return Message{Id: m.ID, ChatId: m.ChatID, SenderId: m.SenderID, Text: m.Text, CreatedAt: Timestamp(m.CreatedAt)}
|
||||
}
|
||||
|
||||
func mapAll[T, R any](items []T, f func(T) R) []R {
|
||||
out := make([]R, len(items))
|
||||
for i, item := range items {
|
||||
out[i] = f(item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type sessionRequestKey struct{}
|
||||
|
||||
func (h *API) CreateSession(ctx context.Context, _ CreateSessionRequestObject) (CreateSessionResponseObject, error) {
|
||||
r := ctx.Value(sessionRequestKey{}).(*http.Request)
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || len(username) > 32 || len(password) > 512 || utf8.RuneCountInString(password) > 128 {
|
||||
return nil, model.ErrUnauthorized
|
||||
}
|
||||
s, err := h.auth.Login(ctx, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return CreateSession201JSONResponse{Body: Session{Token: s.Token, TokenType: Bearer, ExpiresAt: Timestamp(s.ExpiresAt), User: toUser(s.User)}}, nil
|
||||
}
|
||||
func (h *API) RevokeSession(ctx context.Context, _ RevokeSessionRequestObject) (RevokeSessionResponseObject, error) {
|
||||
r := ctx.Value(sessionRequestKey{}).(*http.Request)
|
||||
parts := strings.Fields(r.Header.Get("Authorization"))
|
||||
if err := h.auth.Logout(ctx, parts[1]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return RevokeSession204Response{}, nil
|
||||
}
|
||||
func (h *API) requestContext(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(ctx, sessionRequestKey{}, r)))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
)
|
||||
|
||||
var (
|
||||
errRouteNotFound = errors.New("route not found")
|
||||
errMethodNotAllowed = errors.New("method not allowed")
|
||||
errPayloadTooLarge = errors.New("payload too large")
|
||||
errOverloaded = errors.New("overloaded")
|
||||
errDraining = errors.New("draining")
|
||||
)
|
||||
|
||||
type apiError struct {
|
||||
status int
|
||||
code ErrorErrorCode
|
||||
message string
|
||||
}
|
||||
|
||||
// classify — единственное место, где ошибка превращается в HTTP-статус.
|
||||
func classify(err error) apiError {
|
||||
var invalid *model.ValidationError
|
||||
switch {
|
||||
case errors.As(err, &invalid):
|
||||
return apiError{http.StatusBadRequest, InvalidRequest, invalid.Message}
|
||||
case errors.Is(err, model.ErrUnauthorized):
|
||||
return apiError{http.StatusUnauthorized, Unauthorized, "нужна действующая сессия"}
|
||||
case errors.Is(err, model.ErrNotFound), errors.Is(err, errRouteNotFound):
|
||||
return apiError{http.StatusNotFound, NotFound, "объект не найден"}
|
||||
case errors.Is(err, errMethodNotAllowed):
|
||||
return apiError{http.StatusMethodNotAllowed, InvalidRequest, "метод не поддерживается"}
|
||||
case errors.Is(err, model.ErrUsernameTaken):
|
||||
return apiError{http.StatusConflict, Conflict, "username уже занят"}
|
||||
case errors.Is(err, model.ErrConflict):
|
||||
return apiError{http.StatusConflict, Conflict, "конфликт запроса"}
|
||||
case errors.Is(err, model.ErrUnavailable):
|
||||
return apiError{http.StatusServiceUnavailable, Unavailable, "зависимость недоступна"}
|
||||
case errors.Is(err, errPayloadTooLarge):
|
||||
return apiError{http.StatusRequestEntityTooLarge, PayloadTooLarge, "тело запроса больше допустимого"}
|
||||
case errors.Is(err, model.ErrStorageFull):
|
||||
return apiError{http.StatusServiceUnavailable, Unavailable, "хранилище заполнено, запись невозможна; чтение работает"}
|
||||
case errors.Is(err, errOverloaded):
|
||||
return apiError{http.StatusServiceUnavailable, Unavailable, "сервер перегружен, повторите позже"}
|
||||
case errors.Is(err, errDraining):
|
||||
return apiError{http.StatusServiceUnavailable, Unavailable, "сервер останавливается"}
|
||||
default:
|
||||
return apiError{http.StatusInternalServerError, InternalError, "внутренняя ошибка"}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *API) writeError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
e := classify(err)
|
||||
if e.status == http.StatusInternalServerError {
|
||||
h.log.Error().Err(err).Str("request_id", requestIDFrom(r.Context())).Msg("unexpected error")
|
||||
}
|
||||
if errors.Is(err, errOverloaded) {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
}
|
||||
var body Error
|
||||
body.Error.Code = e.code
|
||||
body.Error.Message = e.message
|
||||
body.Error.RequestId = requestIDFrom(r.Context())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(e.status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
// bodyError — JSON синтаксически верен (это проверил jsonBody), но не
|
||||
// подходит к схеме: лишнее поле или неверный тип.
|
||||
func (h *API) bodyError(w http.ResponseWriter, r *http.Request, _ error) {
|
||||
h.writeError(w, r, &model.ValidationError{Message: "тело запроса не соответствует схеме: лишнее поле или неверный тип"})
|
||||
}
|
||||
|
||||
// paramError — path или query параметр не разобрался (UUID, целое число).
|
||||
func (h *API) paramError(w http.ResponseWriter, r *http.Request, _ error) {
|
||||
h.writeError(w, r, &model.ValidationError{Message: "некорректный параметр запроса"})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// gate ограничивает одновременную обработку запросов API: не больше inflight
|
||||
// в работе и не больше queue в ожидании слота. Лишние сразу получают 503 с
|
||||
// Retry-After, ждавшие дольше timeout — тоже 503. Так перегрузка превращается
|
||||
// в быстрый предсказуемый отказ, а не в рост горутин, памяти и задержки.
|
||||
type gate struct {
|
||||
slots chan struct{} // nil — без лимита
|
||||
maxQueue int64
|
||||
timeout time.Duration
|
||||
waiting atomic.Int64
|
||||
rejected atomic.Int64
|
||||
}
|
||||
|
||||
func newGate(inflight, queue int, timeout time.Duration) *gate {
|
||||
g := &gate{maxQueue: int64(queue), timeout: timeout}
|
||||
if inflight > 0 {
|
||||
g.slots = make(chan struct{}, inflight)
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
func (g *gate) middleware(reject func(http.ResponseWriter, *http.Request, error)) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if g.slots == nil {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if !g.acquire(r) {
|
||||
g.rejected.Add(1)
|
||||
reject(w, r, errOverloaded)
|
||||
return
|
||||
}
|
||||
defer func() { <-g.slots }()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (g *gate) acquire(r *http.Request) bool {
|
||||
select {
|
||||
case g.slots <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
}
|
||||
if g.waiting.Add(1) > g.maxQueue {
|
||||
g.waiting.Add(-1)
|
||||
return false
|
||||
}
|
||||
defer g.waiting.Add(-1)
|
||||
timer := time.NewTimer(g.timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case g.slots <- struct{}{}:
|
||||
return true
|
||||
case <-timer.C:
|
||||
return false
|
||||
case <-r.Context().Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type gateStats struct {
|
||||
Inflight int `json:"inflight"`
|
||||
Waiting int64 `json:"waiting"`
|
||||
Rejected int64 `json:"rejected"`
|
||||
}
|
||||
|
||||
func (g *gate) stats() gateStats {
|
||||
return gateStats{Inflight: len(g.slots), Waiting: g.waiting.Load(), Rejected: g.rejected.Load()}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// gatedServer пропускает запросы через gate в обработчик, который держит слот,
|
||||
// пока тест не закроет release.
|
||||
func gatedServer(t *testing.T, g *gate) (*httptest.Server, chan struct{}, chan struct{}) {
|
||||
t.Helper()
|
||||
entered, release := make(chan struct{}, 10), make(chan struct{})
|
||||
reject := func(w http.ResponseWriter, _ *http.Request, err error) {
|
||||
if !errors.Is(err, errOverloaded) {
|
||||
t.Errorf("unexpected error %v", err)
|
||||
}
|
||||
w.Header().Set("Retry-After", "1")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}
|
||||
h := g.middleware(reject)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
entered <- struct{}{}
|
||||
<-release
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
srv := httptest.NewServer(h)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, entered, release
|
||||
}
|
||||
|
||||
func get(t *testing.T, url string) int {
|
||||
t.Helper()
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return 0
|
||||
}
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, cond func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for !cond() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("condition not reached")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateRejectsBeyondQueueAndRecovers(t *testing.T) {
|
||||
t.Parallel()
|
||||
g := newGate(1, 1, time.Minute)
|
||||
srv, entered, release := gatedServer(t, g)
|
||||
|
||||
statuses := make(chan int, 2)
|
||||
var wg sync.WaitGroup
|
||||
wg.Go(func() { statuses <- get(t, srv.URL) }) // занимает слот
|
||||
<-entered
|
||||
wg.Go(func() { statuses <- get(t, srv.URL) }) // ждёт в очереди
|
||||
waitFor(t, func() bool { return g.waiting.Load() == 1 })
|
||||
|
||||
if code := get(t, srv.URL); code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("third request: %d, want 503", code)
|
||||
}
|
||||
close(release)
|
||||
wg.Wait()
|
||||
close(statuses)
|
||||
for code := range statuses {
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("admitted request got %d", code)
|
||||
}
|
||||
}
|
||||
if code := get(t, srv.URL); code != http.StatusOK {
|
||||
t.Fatalf("after load: %d, want recovery to 200", code)
|
||||
}
|
||||
if g.stats().Rejected != 1 {
|
||||
t.Fatalf("rejected %d", g.stats().Rejected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateTimesOutQueuedRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
g := newGate(1, 10, 20*time.Millisecond)
|
||||
srv, entered, release := gatedServer(t, g)
|
||||
defer close(release)
|
||||
|
||||
go get(t, srv.URL)
|
||||
<-entered
|
||||
start := time.Now()
|
||||
if code := get(t, srv.URL); code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("queued request: %d, want 503 after timeout", code)
|
||||
}
|
||||
if time.Since(start) > time.Second {
|
||||
t.Fatal("queue timeout not applied")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"backend/internal/application/usecase"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
// Limits — защитные лимиты HTTP-слоя (трек 5 «управляемая деградация»).
|
||||
// Нулевое значение отключает лимит.
|
||||
type Limits struct {
|
||||
MaxBodyBytes int64 // больше — 413
|
||||
MaxInflight int // одновременно обрабатываемые запросы API
|
||||
MaxQueue int // ждущие свободного слота; больше — сразу 503
|
||||
QueueTimeout time.Duration // дольше ждал слот — 503
|
||||
}
|
||||
|
||||
// API — driving HTTP-адаптер: реализует StrictServerInterface из api.gen.go.
|
||||
//
|
||||
//go:generate go tool oapi-codegen -config ../../../codegen.yaml ../../../../contracts/openapi.json
|
||||
type API struct {
|
||||
app *usecase.Messenger
|
||||
auth *usecase.Auth
|
||||
probe func(context.Context) error
|
||||
limits Limits
|
||||
gate *gate
|
||||
storeStats func() any
|
||||
ready atomic.Bool
|
||||
log *zerolog.Logger
|
||||
}
|
||||
|
||||
// New собирает HTTP-адаптер. storeStats отдаёт состояние хранилища для
|
||||
// /debug/stats.
|
||||
func New(app *usecase.Messenger, auth *usecase.Auth, probe func(context.Context) error, limits Limits, storeStats func() any, log *zerolog.Logger) *API {
|
||||
h := &API{
|
||||
app: app,
|
||||
auth: auth,
|
||||
probe: probe,
|
||||
limits: limits,
|
||||
gate: newGate(limits.MaxInflight, limits.MaxQueue, limits.QueueTimeout),
|
||||
storeStats: storeStats,
|
||||
log: log,
|
||||
}
|
||||
h.ready.Store(true)
|
||||
return h
|
||||
}
|
||||
|
||||
// Drain переводит /health/ready в 503 перед остановкой сервера.
|
||||
func (h *API) Drain() { h.ready.Store(false) }
|
||||
|
||||
func (h *API) Router() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(requestID, h.recoverer, h.accessLog, h.requestContext)
|
||||
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.writeError(w, r, errRouteNotFound)
|
||||
})
|
||||
r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.writeError(w, r, errMethodNotAllowed)
|
||||
})
|
||||
|
||||
strict := NewStrictHandlerWithOptions(h, nil, StrictHTTPServerOptions{
|
||||
RequestErrorHandlerFunc: h.bodyError,
|
||||
ResponseErrorHandlerFunc: h.writeError,
|
||||
})
|
||||
api := ServerInterfaceWrapper{Handler: strict, ErrorHandlerFunc: h.paramError}
|
||||
|
||||
// Health и статистика — мимо очереди: под перегрузкой они должны отвечать.
|
||||
r.Get("/health/live", api.Liveness)
|
||||
r.Get("/health/ready", api.Readiness)
|
||||
r.Get("/debug/stats", h.stats)
|
||||
|
||||
r.Route("/api/v1", func(r chi.Router) {
|
||||
r.Use(h.gate.middleware(h.writeError))
|
||||
r.With(h.jsonBody).Post("/users", api.RegisterUser)
|
||||
r.Post("/auth/sessions", api.CreateSession)
|
||||
// Сначала аутентификация, потом тело и доступ к ресурсу.
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(h.authenticate, h.validQuery, h.jsonBody)
|
||||
r.Delete("/auth/sessions/current", api.RevokeSession)
|
||||
r.Get("/users/me", api.CurrentUser)
|
||||
r.Post("/chats", api.CreateChat)
|
||||
r.Get("/chats", api.ListChats)
|
||||
r.Get("/chats/{chat_id}", api.GetChat)
|
||||
r.Post("/chats/{chat_id}/messages", api.CreateMessage)
|
||||
r.Get("/chats/{chat_id}/messages", api.ListMessages)
|
||||
})
|
||||
})
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Timestamp подставляется кодогенератором вместо time.Time (codegen.yaml,
|
||||
// type-mapping): RFC 3339 UTC с ровно шестью цифрами дробной части.
|
||||
// time.Time срезает хвостовые нули, а fromisoformat в Python 3.9–3.10
|
||||
// (на нём публичные тесты) понимает дробную часть только из 3 или 6 цифр.
|
||||
type Timestamp time.Time
|
||||
|
||||
const timestampLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
func (t Timestamp) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + time.Time(t).UTC().Format(timestampLayout) + `"`), nil
|
||||
}
|
||||
|
||||
func (t *Timestamp) UnmarshalJSON(data []byte) error {
|
||||
var parsed time.Time
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = Timestamp(parsed)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Тела запросов с лишними полями — 400 по контракту, а сгенерированный
|
||||
// декодер их молча игнорирует. Строгий разбор подключается методами на
|
||||
// сгенерированных типах.
|
||||
|
||||
func (c *CreateUser) UnmarshalJSON(data []byte) error {
|
||||
type plain CreateUser
|
||||
return decodeStrict(data, (*plain)(c))
|
||||
}
|
||||
|
||||
func (c *CreateChat) UnmarshalJSON(data []byte) error {
|
||||
type plain CreateChat
|
||||
return decodeStrict(data, (*plain)(c))
|
||||
}
|
||||
|
||||
func (c *CreateMessage) UnmarshalJSON(data []byte) error {
|
||||
type plain CreateMessage
|
||||
return decodeStrict(data, (*plain)(c))
|
||||
}
|
||||
|
||||
func decodeStrict(data []byte, dst any) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
return dec.Decode(dst)
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
requestIDKey ctxKey = iota
|
||||
userKey
|
||||
)
|
||||
|
||||
// requestID ставит X-Request-Id в каждый ответ, включая ошибки и health.
|
||||
func requestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := uuid.NewString()
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, id)))
|
||||
})
|
||||
}
|
||||
|
||||
func requestIDFrom(ctx context.Context) string {
|
||||
id, _ := ctx.Value(requestIDKey).(string)
|
||||
return id
|
||||
}
|
||||
|
||||
// recoverer превращает панику в 500 без деталей; стек — только в лог.
|
||||
func (h *API) recoverer(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
rec := recover()
|
||||
if rec == nil {
|
||||
return
|
||||
}
|
||||
if rec == http.ErrAbortHandler {
|
||||
panic(rec)
|
||||
}
|
||||
h.log.Error().Interface("panic", rec).Bytes("stack", debug.Stack()).
|
||||
Str("request_id", requestIDFrom(r.Context())).Msg("panic")
|
||||
h.writeError(w, r, errors.New("panic"))
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// accessLog пишет метод, шаблон маршрута, статус и длительность. Тело, query
|
||||
// и заголовки не логируются: там текст сообщений и идентификаторы.
|
||||
func (h *API) accessLog(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(ww, r)
|
||||
route := chi.RouteContext(r.Context()).RoutePattern()
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
event := h.log.Info()
|
||||
if ww.Status() >= http.StatusInternalServerError {
|
||||
event = h.log.Warn()
|
||||
}
|
||||
event.Str("request_id", requestIDFrom(r.Context())).
|
||||
Str("method", r.Method).
|
||||
Str("route", route).
|
||||
Int("status", ww.Status()).
|
||||
Dur("duration", time.Since(start)).
|
||||
Msg("request")
|
||||
})
|
||||
}
|
||||
|
||||
// authenticate verifies persisted Bearer sessions for protected business routes.
|
||||
// The session-creation endpoint separately validates Basic credentials.
|
||||
func (h *API) authenticate(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
parts := strings.Fields(r.Header.Get("Authorization"))
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
h.writeError(w, r, model.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
user, err := h.auth.Authenticate(r.Context(), parts[1])
|
||||
if err != nil {
|
||||
if errors.Is(err, model.ErrUnauthorized) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
h.writeError(w, r, err)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), userKey, user)))
|
||||
})
|
||||
}
|
||||
|
||||
// validQuery отсекает query с битым %-экранированием: url.Values молча
|
||||
// выбросил бы такой параметр, и cursor=%%% превратился бы в «с начала».
|
||||
func (h *API) validQuery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := url.ParseQuery(r.URL.RawQuery); err != nil {
|
||||
h.writeError(w, r, &model.ValidationError{Message: "некорректная строка запроса"})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func currentUser(ctx context.Context) model.User {
|
||||
user, _ := ctx.Value(userKey).(model.User)
|
||||
return user
|
||||
}
|
||||
|
||||
// jsonBody читает тело POST с лимитом размера (иначе 413) и отсекает
|
||||
// синтаксически неверный JSON (400) до кодогенерированного декодера: тот
|
||||
// читает только первое JSON-значение и пропустил бы мусор после него.
|
||||
func (h *API) jsonBody(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
reader := io.Reader(r.Body)
|
||||
if h.limits.MaxBodyBytes > 0 {
|
||||
reader = http.MaxBytesReader(w, r.Body, h.limits.MaxBodyBytes)
|
||||
}
|
||||
body, err := io.ReadAll(reader)
|
||||
var tooLarge *http.MaxBytesError
|
||||
switch {
|
||||
case errors.As(err, &tooLarge):
|
||||
h.writeError(w, r, errPayloadTooLarge)
|
||||
return
|
||||
case err != nil:
|
||||
h.writeError(w, r, &model.ValidationError{Message: "тело запроса не прочитано"})
|
||||
return
|
||||
case !utf8.Valid(body)||!json.Valid(body):
|
||||
h.writeError(w, r, &model.ValidationError{Message: "некорректный JSON"})
|
||||
return
|
||||
}
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// stats — расширение за пределами контракта (contracts/extensions.md): память
|
||||
// процесса, учтённый объём хранилища и очередь. Нужен для графиков трека 5.
|
||||
func (h *API) stats(w http.ResponseWriter, _ *http.Request) {
|
||||
var mem runtime.MemStats
|
||||
runtime.ReadMemStats(&mem)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"rss_bytes": rssBytes(),
|
||||
"heap_alloc": mem.HeapAlloc,
|
||||
"heap_sys": mem.HeapSys,
|
||||
"go_memory_limit": debug.SetMemoryLimit(-1),
|
||||
"num_gc": mem.NumGC,
|
||||
"goroutines": runtime.NumGoroutine(),
|
||||
"gate": h.gate.stats(),
|
||||
"store": h.storeStats(),
|
||||
})
|
||||
}
|
||||
|
||||
// rssBytes читает VmRSS из /proc (только Linux, то есть в контейнере); иначе 0.
|
||||
func rssBytes() int64 {
|
||||
f, err := os.Open("/proc/self/status")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer f.Close()
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
if kb, ok := strings.CutPrefix(sc.Text(), "VmRSS:"); ok {
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(strings.TrimSuffix(kb, "kB")), 10, 64)
|
||||
return n * 1024
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package handler
|
||||
import("bytes";"net/http";"net/http/httptest";"testing")
|
||||
func TestRejectsInvalidUTF8BeforeJSONDecoding(t *testing.T){
|
||||
body:=append([]byte(`{"display_name":"`),0xff);body=append(body,[]byte(`"}`)...)
|
||||
request:=httptest.NewRequest(http.MethodPost,"/api/v1/users",bytes.NewReader(body));response:=httptest.NewRecorder()
|
||||
h:=&API{limits:Limits{MaxBodyBytes:65536}};called:=false
|
||||
requestID(h.jsonBody(http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){called=true;w.WriteHeader(204)}))).ServeHTTP(response,request)
|
||||
if response.Code!=400||called{t.Fatalf("invalid UTF-8 reached decoder: status=%d called=%t",response.Code,called)}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"backend/internal/domain/port"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"golang.org/x/crypto/argon2"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Argon struct{}
|
||||
|
||||
func New() port.Passwords { return Argon{} }
|
||||
func (Argon) Hash(password string) (string, error) {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, 2, 32*1024, 1, 32)
|
||||
return fmt.Sprintf("argon2id$v19$m32768t2p1$%s$%s", base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(hash)), nil
|
||||
}
|
||||
func (Argon) Verify(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 5 || parts[0] != "argon2id" || parts[1] != "v19" || parts[2] != "m32768t2p1" {
|
||||
return false
|
||||
}
|
||||
salt, e1 := base64.RawStdEncoding.DecodeString(parts[3])
|
||||
want, e2 := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if e1 != nil || e2 != nil || len(salt) != 16 || len(want) != 32 {
|
||||
return false
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, 2, 32*1024, 1, 32)
|
||||
return subtle.ConstantTimeCompare(got, want) == 1
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: core.sql
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const authenticateSession = `-- name: AuthenticateSession :one
|
||||
SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()
|
||||
`
|
||||
|
||||
func (q *Queries) AuthenticateSession(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, authenticateSession, tokenHash)
|
||||
var user_id uuid.UUID
|
||||
err := row.Scan(&user_id)
|
||||
return user_id, err
|
||||
}
|
||||
|
||||
const chargeChat = `-- name: ChargeChat :one
|
||||
UPDATE users SET chat_count=chat_count+1 WHERE id=$1 AND chat_count<1000 RETURNING id
|
||||
`
|
||||
|
||||
func (q *Queries) ChargeChat(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, chargeChat, id)
|
||||
var id_2 uuid.UUID
|
||||
err := row.Scan(&id_2)
|
||||
return id_2, err
|
||||
}
|
||||
|
||||
const chargeMessage = `-- name: ChargeMessage :one
|
||||
UPDATE users SET message_count=message_count+1 WHERE id=$1 AND message_count<1000000 RETURNING id
|
||||
`
|
||||
|
||||
func (q *Queries) ChargeMessage(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, chargeMessage, id)
|
||||
var id_2 uuid.UUID
|
||||
err := row.Scan(&id_2)
|
||||
return id_2, err
|
||||
}
|
||||
|
||||
const createUser = `-- name: CreateUser :one
|
||||
INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
|
||||
RETURNING id,username,display_name,created_at
|
||||
`
|
||||
|
||||
type CreateUserParams struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
type CreateUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
|
||||
row := q.db.QueryRow(ctx, createUser,
|
||||
arg.ID,
|
||||
arg.Username,
|
||||
arg.DisplayName,
|
||||
arg.PasswordHash,
|
||||
)
|
||||
var i CreateUserRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const credentials = `-- name: Credentials :one
|
||||
SELECT id,password_hash FROM users WHERE username=$1
|
||||
`
|
||||
|
||||
type CredentialsRow struct {
|
||||
ID uuid.UUID
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) Credentials(ctx context.Context, username string) (CredentialsRow, error) {
|
||||
row := q.db.QueryRow(ctx, credentials, username)
|
||||
var i CredentialsRow
|
||||
err := row.Scan(&i.ID, &i.PasswordHash)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteExpiredSessions = `-- name: DeleteExpiredSessions :exec
|
||||
DELETE FROM sessions WHERE user_id=$1 AND expires_at<=clock_timestamp()
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteExpiredSessions(ctx context.Context, userID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, deleteExpiredSessions, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
const getChat = `-- name: GetChat :one
|
||||
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
|
||||
FROM chats c WHERE c.id=$1
|
||||
`
|
||||
|
||||
type GetChatRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
Members []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetChat(ctx context.Context, id uuid.UUID) (GetChatRow, error) {
|
||||
row := q.db.QueryRow(ctx, getChat, id)
|
||||
var i GetChatRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.Members,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUser = `-- name: GetUser :one
|
||||
SELECT id,username,display_name,created_at FROM users WHERE id=$1
|
||||
`
|
||||
|
||||
type GetUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) {
|
||||
row := q.db.QueryRow(ctx, getUser, id)
|
||||
var i GetUserRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertChat = `-- name: InsertChat :one
|
||||
INSERT INTO chats(id,title) VALUES($1,$2) RETURNING id,title,created_at
|
||||
`
|
||||
|
||||
type InsertChatParams struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertChat(ctx context.Context, arg InsertChatParams) (Chat, error) {
|
||||
row := q.db.QueryRow(ctx, insertChat, arg.ID, arg.Title)
|
||||
var i Chat
|
||||
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertMembers = `-- name: InsertMembers :exec
|
||||
INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[])
|
||||
`
|
||||
|
||||
type InsertMembersParams struct {
|
||||
ChatID uuid.UUID
|
||||
Column2 []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMembers(ctx context.Context, arg InsertMembersParams) error {
|
||||
_, err := q.db.Exec(ctx, insertMembers, arg.ChatID, arg.Column2)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertMessage = `-- name: InsertMessage :one
|
||||
INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING id,chat_id,sender_id,text,created_at
|
||||
`
|
||||
|
||||
type InsertMessageParams struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMessage(ctx context.Context, arg InsertMessageParams) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, insertMessage,
|
||||
arg.ID,
|
||||
arg.ChatID,
|
||||
arg.SenderID,
|
||||
arg.Text,
|
||||
)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertSession = `-- name: InsertSession :one
|
||||
INSERT INTO sessions(token_hash,user_id,expires_at)
|
||||
SELECT $1,$2,$3 WHERE (SELECT count(*) FROM sessions WHERE user_id=$2)<100
|
||||
RETURNING user_id
|
||||
`
|
||||
|
||||
type InsertSessionParams struct {
|
||||
TokenHash string
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, insertSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
|
||||
var user_id uuid.UUID
|
||||
err := row.Scan(&user_id)
|
||||
return user_id, err
|
||||
}
|
||||
|
||||
const listChats = `-- name: ListChats :many
|
||||
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
|
||||
FROM chats c JOIN chat_members m ON m.chat_id=c.id
|
||||
WHERE m.user_id=$1 AND (c.created_at,c.id)>($2::timestamptz,$3::uuid)
|
||||
ORDER BY c.created_at,c.id LIMIT $4
|
||||
`
|
||||
|
||||
type ListChatsParams struct {
|
||||
MemberID uuid.UUID
|
||||
AfterTime time.Time
|
||||
AfterID uuid.UUID
|
||||
PageLimit int32
|
||||
}
|
||||
|
||||
type ListChatsRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
Members []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listChats,
|
||||
arg.MemberID,
|
||||
arg.AfterTime,
|
||||
arg.AfterID,
|
||||
arg.PageLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListChatsRow{}
|
||||
for rows.Next() {
|
||||
var i ListChatsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.Members,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listMessages = `-- name: ListMessages :many
|
||||
SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=$1 AND (created_at,id)>($2::timestamptz,$3::uuid)
|
||||
ORDER BY created_at,id LIMIT $4
|
||||
`
|
||||
|
||||
type ListMessagesParams struct {
|
||||
ChatID uuid.UUID
|
||||
AfterTime time.Time
|
||||
AfterID uuid.UUID
|
||||
PageLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) {
|
||||
rows, err := q.db.Query(ctx, listMessages,
|
||||
arg.ChatID,
|
||||
arg.AfterTime,
|
||||
arg.AfterID,
|
||||
arg.PageLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Message{}
|
||||
for rows.Next() {
|
||||
var i Message
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockSessionOwner = `-- name: LockSessionOwner :one
|
||||
SELECT id FROM users WHERE id=$1 FOR UPDATE
|
||||
`
|
||||
|
||||
func (q *Queries) LockSessionOwner(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockSessionOwner, id)
|
||||
var id_2 uuid.UUID
|
||||
err := row.Scan(&id_2)
|
||||
return id_2, err
|
||||
}
|
||||
|
||||
const revokeSession = `-- name: RevokeSession :exec
|
||||
DELETE FROM sessions WHERE token_hash=$1
|
||||
`
|
||||
|
||||
func (q *Queries) RevokeSession(ctx context.Context, tokenHash string) error {
|
||||
_, err := q.db.Exec(ctx, revokeSession, tokenHash)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TokenHash string
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
CreatedAt time.Time
|
||||
ChatCount int32
|
||||
MessageCount int32
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"backend/internal/adapter/repository/postgres/queries"
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/repository"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
//go:generate go tool sqlc generate -f ../../../../db/sqlc/sqlc.yaml
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
q *queries.Queries
|
||||
cache *redis.Client
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, cache *redis.Client) repository.Persistent {
|
||||
return &Store{pool, queries.New(pool), cache}
|
||||
}
|
||||
func mapErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.ErrNotFound
|
||||
}
|
||||
var pg *pgconn.PgError
|
||||
if errors.As(err, &pg) {
|
||||
switch pg.Code {
|
||||
case "23505":
|
||||
return model.ErrUsernameTaken
|
||||
case "23503":
|
||||
return model.ErrUnknownMember
|
||||
case "23514":
|
||||
return &model.ValidationError{Message: "constraint violation"}
|
||||
}
|
||||
}
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
func (s *Store) CreateUser(ctx context.Context, d model.UserDraft) (model.User, error) {
|
||||
row, err := s.q.CreateUser(ctx, queries.CreateUserParams{ID: uuid.New(), Username: d.Username, DisplayName: d.DisplayName, PasswordHash: d.PasswordHash})
|
||||
return model.User{ID: row.ID, Username: row.Username, DisplayName: row.DisplayName, CreatedAt: row.CreatedAt}, mapErr(err)
|
||||
}
|
||||
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (model.User, error) {
|
||||
key := "profile:" + id.String()
|
||||
if s.cache != nil {
|
||||
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
||||
raw, err := s.cache.Get(c, key).Bytes()
|
||||
cancel()
|
||||
if err == nil {
|
||||
var u model.User
|
||||
if json.Unmarshal(raw, &u) == nil && u.ID == id {
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
row, err := s.q.GetUser(ctx, id)
|
||||
if err != nil {
|
||||
return model.User{}, mapErr(err)
|
||||
}
|
||||
user := model.User{ID: row.ID, Username: row.Username, DisplayName: row.DisplayName, CreatedAt: row.CreatedAt}
|
||||
if s.cache != nil {
|
||||
raw, e := json.Marshal(user)
|
||||
if e == nil {
|
||||
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
||||
_ = s.cache.Set(c, key, raw, time.Minute).Err()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
func (s *Store) CreateChat(ctx context.Context, d model.ChatDraft) (model.Chat, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := s.q.WithTx(tx)
|
||||
if _, err = q.ChargeChat(ctx, d.Creator); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, model.ErrStorageFull
|
||||
}
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
row, err := q.InsertChat(ctx, queries.InsertChatParams{ID: uuid.New(), Title: d.Title})
|
||||
if err != nil {
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
if err = q.InsertMembers(ctx, queries.InsertMembersParams{ChatID: row.ID, Column2: d.MemberIDs}); err != nil {
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, mapErr(err)
|
||||
}
|
||||
return model.Chat{ID: row.ID, Title: row.Title, CreatedAt: row.CreatedAt, MemberIDs: d.MemberIDs}, nil
|
||||
}
|
||||
func (s *Store) GetChat(ctx context.Context, id uuid.UUID) (model.Chat, error) {
|
||||
r, e := s.q.GetChat(ctx, id)
|
||||
return model.Chat{ID: r.ID, Title: r.Title, CreatedAt: r.CreatedAt, MemberIDs: r.Members}, mapErr(e)
|
||||
}
|
||||
func position(q model.PageQuery) (time.Time, uuid.UUID) {
|
||||
if q.After == nil {
|
||||
return time.Unix(0, 0).UTC(), uuid.Nil
|
||||
}
|
||||
return q.After.CreatedAt, q.After.ID
|
||||
}
|
||||
func (s *Store) ListChats(ctx context.Context, id uuid.UUID, p model.PageQuery) ([]model.Chat, bool, error) {
|
||||
at, aid := position(p)
|
||||
rows, err := s.q.ListChats(ctx, queries.ListChatsParams{MemberID: id, AfterTime: at, AfterID: aid, PageLimit: int32(p.Limit + 1)})
|
||||
if err != nil {
|
||||
return nil, false, mapErr(err)
|
||||
}
|
||||
more := len(rows) > p.Limit
|
||||
if more {
|
||||
rows = rows[:p.Limit]
|
||||
}
|
||||
out := make([]model.Chat, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = model.Chat{ID: r.ID, Title: r.Title, CreatedAt: r.CreatedAt, MemberIDs: r.Members}
|
||||
}
|
||||
return out, more, nil
|
||||
}
|
||||
func (s *Store) CreateMessage(ctx context.Context, d model.MessageDraft) (model.Message, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, mapErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := s.q.WithTx(tx)
|
||||
if _, err = q.ChargeMessage(ctx, d.SenderID); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, model.ErrStorageFull
|
||||
}
|
||||
return model.Message{}, mapErr(err)
|
||||
}
|
||||
r, err := q.InsertMessage(ctx, queries.InsertMessageParams{ID: uuid.New(), ChatID: d.ChatID, SenderID: d.SenderID, Text: d.Text})
|
||||
if err != nil {
|
||||
return model.Message{}, mapErr(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, mapErr(err)
|
||||
}
|
||||
return model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt}, nil
|
||||
}
|
||||
func (s *Store) ListMessages(ctx context.Context, id uuid.UUID, p model.PageQuery) ([]model.Message, bool, error) {
|
||||
at, aid := position(p)
|
||||
rows, err := s.q.ListMessages(ctx, queries.ListMessagesParams{ChatID: id, AfterTime: at, AfterID: aid, PageLimit: int32(p.Limit + 1)})
|
||||
if err != nil {
|
||||
return nil, false, mapErr(err)
|
||||
}
|
||||
more := len(rows) > p.Limit
|
||||
if more {
|
||||
rows = rows[:p.Limit]
|
||||
}
|
||||
out := make([]model.Message, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt}
|
||||
}
|
||||
return out, more, nil
|
||||
}
|
||||
func (s *Store) Credentials(ctx context.Context, name string) (uuid.UUID, string, error) {
|
||||
r, e := s.q.Credentials(ctx, name)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return uuid.Nil, "", model.ErrUnauthorized
|
||||
}
|
||||
return r.ID, r.PasswordHash, mapErr(e)
|
||||
}
|
||||
func (s *Store) CreateSession(ctx context.Context, hash string, id uuid.UUID, expiry time.Time) error {
|
||||
tx, e := s.pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return mapErr(e)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := s.q.WithTx(tx)
|
||||
if _, e = q.LockSessionOwner(ctx, id); e != nil {
|
||||
return mapErr(e)
|
||||
}
|
||||
if e = q.DeleteExpiredSessions(ctx, id); e != nil {
|
||||
return mapErr(e)
|
||||
}
|
||||
if _, e = q.InsertSession(ctx, queries.InsertSessionParams{TokenHash: hash, UserID: id, ExpiresAt: expiry}); e != nil {
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return model.ErrStorageFull
|
||||
}
|
||||
return mapErr(e)
|
||||
}
|
||||
return mapErr(tx.Commit(ctx))
|
||||
}
|
||||
func (s *Store) AuthenticateSession(ctx context.Context, hash string) (uuid.UUID, error) {
|
||||
r, e := s.q.AuthenticateSession(ctx, hash)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return uuid.Nil, model.ErrUnauthorized
|
||||
}
|
||||
return r, mapErr(e)
|
||||
}
|
||||
func (s *Store) RevokeSession(ctx context.Context, hash string) error {
|
||||
return mapErr(s.q.RevokeSession(ctx, hash))
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
sessions port.Sessions
|
||||
passwords port.Passwords
|
||||
messenger *Messenger
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
type Session struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User model.User
|
||||
}
|
||||
|
||||
func NewAuth(s port.Sessions, p port.Passwords, m *Messenger, ttl time.Duration, now func() time.Time) *Auth {
|
||||
return &Auth{s, p, m, ttl, now}
|
||||
}
|
||||
func (a *Auth) Register(ctx context.Context, username, name, password string) (model.User, error) {
|
||||
if n := utf8.RuneCountInString(password); n < 12 || n > 128 || !utf8.ValidString(password) {
|
||||
return model.User{}, &model.ValidationError{Message: "password: 12–128 Unicode characters"}
|
||||
}
|
||||
draft, err := model.NewUserDraft(username, name)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
hash, err := a.passwords.Hash(password)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
draft.PasswordHash = hash
|
||||
return a.messenger.repo.CreateUser(ctx, draft)
|
||||
}
|
||||
func (a *Auth) Login(ctx context.Context, username, password string) (Session, error) {
|
||||
id, hash, err := a.sessions.Credentials(ctx, username)
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
if !a.passwords.Verify(password, hash) {
|
||||
return Session{}, model.ErrUnauthorized
|
||||
}
|
||||
user, err := a.messenger.repo.GetUser(ctx, id)
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err = rand.Read(raw); err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
expires := a.now().UTC().Add(a.ttl)
|
||||
if err = a.sessions.CreateSession(ctx, TokenHash(token), id, expires); err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
return Session{token, expires, user}, nil
|
||||
}
|
||||
func TokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
func (a *Auth) Authenticate(ctx context.Context, token string) (model.User, error) {
|
||||
if len(token) != 43 {
|
||||
return model.User{}, model.ErrUnauthorized
|
||||
}
|
||||
id, err := a.sessions.AuthenticateSession(ctx, TokenHash(token))
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
return a.messenger.repo.GetUser(ctx, id)
|
||||
}
|
||||
func (a *Auth) Logout(ctx context.Context, token string) error {
|
||||
return a.sessions.RevokeSession(ctx, TokenHash(token))
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/repository"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const chatsCursorScope = "chats"
|
||||
|
||||
// Page — страница списка; NextCursor == nil, если следующей записи нет.
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
NextCursor *string
|
||||
}
|
||||
|
||||
type Messenger struct {
|
||||
repo repository.Repository
|
||||
}
|
||||
|
||||
func NewMessenger(repo repository.Repository) *Messenger {
|
||||
return &Messenger{repo: repo}
|
||||
}
|
||||
|
||||
func (m *Messenger) CreateChat(ctx context.Context, caller uuid.UUID, title string, memberIDs []uuid.UUID) (model.Chat, error) {
|
||||
draft, err := model.NewChatDraft(caller, title, memberIDs)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
return m.repo.CreateChat(ctx, draft)
|
||||
}
|
||||
|
||||
func (m *Messenger) ListChats(ctx context.Context, caller uuid.UUID, limit *int, cursor *string) (Page[model.Chat], error) {
|
||||
q, err := model.NewPageQuery(limit, cursor, chatsCursorScope)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
chats, more, err := m.repo.ListChats(ctx, caller, q)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
return newPage(chats, more, chatsCursorScope, model.Chat.Position), nil
|
||||
}
|
||||
|
||||
// GetChat отдаёт чат только участнику; постороннему — ErrNotFound, чтобы не
|
||||
// раскрывать существование чужого чата.
|
||||
func (m *Messenger) GetChat(ctx context.Context, caller, chatID uuid.UUID) (model.Chat, error) {
|
||||
chat, err := m.repo.GetChat(ctx, chatID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if !chat.HasMember(caller) {
|
||||
return model.Chat{}, model.ErrNotFound
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
// SendMessage сначала проверяет доступ, затем тело: посторонний получает 404
|
||||
// даже на невалидное сообщение. Проверка членства и запись не атомарны, но
|
||||
// участники чата неизменяемы, а чаты не удаляются, поэтому гонки здесь нет.
|
||||
func (m *Messenger) SendMessage(ctx context.Context, caller, chatID uuid.UUID, text string) (model.Message, error) {
|
||||
if _, err := m.GetChat(ctx, caller, chatID); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
draft, err := model.NewMessageDraft(chatID, caller, text)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
return m.repo.CreateMessage(ctx, draft)
|
||||
}
|
||||
|
||||
func (m *Messenger) ListMessages(ctx context.Context, caller, chatID uuid.UUID, limit *int, cursor *string) (Page[model.Message], error) {
|
||||
if _, err := m.GetChat(ctx, caller, chatID); err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
scope := "messages:" + chatID.String()
|
||||
q, err := model.NewPageQuery(limit, cursor, scope)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
messages, more, err := m.repo.ListMessages(ctx, chatID, q)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
return newPage(messages, more, scope, model.Message.Position), nil
|
||||
}
|
||||
|
||||
func newPage[T any](items []T, more bool, scope string, position func(T) model.Position) Page[T] {
|
||||
page := Page[T]{Items: items}
|
||||
if more && len(items) > 0 {
|
||||
next := model.EncodeCursor(scope, position(items[len(items)-1]))
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// Config приходит только из окружения (12-factor): в контейнер не копируются
|
||||
// ни .env, ни файлы конфигурации. Значения по умолчанию — ниже.
|
||||
type Config struct {
|
||||
Host string `mapstructure:"APP_HOST"`
|
||||
Port int `mapstructure:"APP_PORT"`
|
||||
Env string `mapstructure:"APP_ENV"`
|
||||
LogLevel string `mapstructure:"LOG_LEVEL"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"SHUTDOWN_TIMEOUT"`
|
||||
MaxBodyBytes int64 `mapstructure:"MAX_BODY_BYTES"`
|
||||
MaxInflight int `mapstructure:"MAX_INFLIGHT"`
|
||||
MaxQueue int `mapstructure:"MAX_QUEUE"`
|
||||
QueueTimeout time.Duration `mapstructure:"QUEUE_TIMEOUT"`
|
||||
DatabaseURLFile string `mapstructure:"DATABASE_URL_FILE"`
|
||||
CacheURLFile string `mapstructure:"CACHE_URL_FILE"`
|
||||
SessionTTLSeconds int `mapstructure:"SESSION_TTL_SECONDS"`
|
||||
MaxConns int32 `mapstructure:"PG_MAX_CONNS"`
|
||||
}
|
||||
|
||||
var defaults = map[string]any{
|
||||
"APP_HOST": "0.0.0.0",
|
||||
"APP_PORT": 8080,
|
||||
"APP_ENV": "lab",
|
||||
"LOG_LEVEL": "info",
|
||||
"SHUTDOWN_TIMEOUT": "8s",
|
||||
"MAX_BODY_BYTES": 64 << 10,
|
||||
"MAX_INFLIGHT": 4,
|
||||
"MAX_QUEUE": 32,
|
||||
"QUEUE_TIMEOUT": "1s",
|
||||
"DATABASE_URL_FILE": "/run/secrets/database_url",
|
||||
"CACHE_URL_FILE": "/run/secrets/cache_url",
|
||||
"SESSION_TTL_SECONDS": 3600,
|
||||
"PG_MAX_CONNS": 8,
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
v := viper.New()
|
||||
for key, value := range defaults {
|
||||
v.SetDefault(key, value)
|
||||
}
|
||||
v.AutomaticEnv()
|
||||
var cfg Config
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("parse config: %w", err)
|
||||
}
|
||||
if cfg.ShutdownTimeout <= 0 || cfg.ShutdownTimeout > 9*time.Second {
|
||||
return Config{}, fmt.Errorf("SHUTDOWN_TIMEOUT must be in (0, 9s]: docker stop ждёт 10 с")
|
||||
}
|
||||
if cfg.SessionTTLSeconds < 1 || cfg.SessionTTLSeconds > 86400 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be 1..86400")
|
||||
}
|
||||
if cfg.MaxConns<1||cfg.MaxConns>64{return Config{},fmt.Errorf("PG_MAX_CONNS must be 1..64")}
|
||||
if cfg.MaxInflight<1||cfg.MaxInflight>4||cfg.MaxQueue<0||cfg.MaxQueue>128||cfg.QueueTimeout<=0||cfg.QueueTimeout>2*time.Second{return Config{},fmt.Errorf("HTTP gate exceeds the tested resource budget")}
|
||||
if cfg.MaxBodyBytes<1||cfg.MaxBodyBytes>65536{return Config{},fmt.Errorf("MAX_BODY_BYTES must be 1..65536")}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string { return fmt.Sprintf("%s:%d", c.Host, c.Port) }
|
||||
|
||||
func ReadSecret(path string) (string, error) {
|
||||
b, e := os.ReadFile(path)
|
||||
if e != nil {
|
||||
return "", fmt.Errorf("required secret file unavailable")
|
||||
}
|
||||
v := strings.TrimSpace(string(b))
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("required secret is empty")
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package config
|
||||
import "testing"
|
||||
func TestRejectsConfigurationOutsideResourceBudget(t *testing.T){
|
||||
for _,tc:=range []struct{key,value string}{{"MAX_INFLIGHT","0"},{"MAX_INFLIGHT","5"},{"MAX_QUEUE","-1"},{"MAX_QUEUE","129"},{"QUEUE_TIMEOUT","0s"},{"QUEUE_TIMEOUT","3s"},{"MAX_BODY_BYTES","0"},{"MAX_BODY_BYTES","65537"},{"PG_MAX_CONNS","0"},{"PG_MAX_CONNS","65"},{"SESSION_TTL_SECONDS","0"},{"SESSION_TTL_SECONDS","86401"}}{t.Run(tc.key+tc.value,func(t *testing.T){t.Setenv(tc.key,tc.value);if _,e:=Load();e==nil{t.Fatal("accepted configuration beyond tested bounds")}})}
|
||||
}
|
||||
func TestPoolSizeIsConfigurableWithinBounds(t *testing.T){t.Setenv("PG_MAX_CONNS","1");cfg,e:=Load();if e!=nil{t.Fatal(e)};if cfg.MaxConns!=1{t.Fatal("configured pool size ignored")}}
|
||||
@@ -0,0 +1,52 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const maxChatMembers = 100
|
||||
|
||||
// Chat неизменяем после создания: участники задаются один раз, удаления в API нет.
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (c Chat) HasMember(userID uuid.UUID) bool {
|
||||
return slices.Contains(c.MemberIDs, userID)
|
||||
}
|
||||
|
||||
// ChatDraft — проверенные данные нового чата. Существование участников
|
||||
// проверяет хранилище атомарно с созданием.
|
||||
type ChatDraft struct {
|
||||
Creator uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
}
|
||||
|
||||
func NewChatDraft(creator uuid.UUID, title string, memberIDs []uuid.UUID) (ChatDraft, error) {
|
||||
if err := requireText("title", title, 1, 100); err != nil {
|
||||
return ChatDraft{}, err
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > maxChatMembers {
|
||||
return ChatDraft{}, invalidf("member_ids: от 1 до %d участников", maxChatMembers)
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return ChatDraft{}, invalidf("member_ids: повторяющийся участник")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if _, ok := seen[creator]; !ok {
|
||||
return ChatDraft{}, invalidf("member_ids: должен содержать создателя чата")
|
||||
}
|
||||
return ChatDraft{Creator: creator, Title: title, MemberIDs: slices.Clone(memberIDs)}, nil
|
||||
}
|
||||
|
||||
func (c Chat) Position() Position { return Position{CreatedAt: c.CreatedAt, ID: c.ID} }
|
||||
@@ -0,0 +1,32 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnavailable = errors.New("dependency unavailable")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUsernameTaken = errors.New("username taken")
|
||||
// ErrStorageFull — исчерпан бюджет памяти хранилища. Подтверждённые данные
|
||||
// не вытесняются, поэтому новые записи отклоняются, а чтение продолжает работать.
|
||||
ErrStorageFull = errors.New("storage full")
|
||||
// ErrUnknownMember возвращает хранилище, если среди участников нового чата
|
||||
// есть несуществующий пользователь; для клиента это ошибка ввода (400).
|
||||
ErrUnknownMember error = &ValidationError{Message: "member_ids: неизвестный пользователь"}
|
||||
)
|
||||
|
||||
// ValidationError — нарушение правил входных данных; Message безопасно
|
||||
// показывать клиенту.
|
||||
type ValidationError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *ValidationError) Error() string { return e.Message }
|
||||
|
||||
func invalidf(format string, args ...any) error {
|
||||
return &ValidationError{Message: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const MaxMessageRunes = 4000
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// MessageDraft — проверенное сообщение; отправитель берётся из идентификации,
|
||||
// а не из тела запроса.
|
||||
type MessageDraft struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
func NewMessageDraft(chatID, senderID uuid.UUID, text string) (MessageDraft, error) {
|
||||
if err := requireText("text", text, 1, MaxMessageRunes); err != nil {
|
||||
return MessageDraft{}, err
|
||||
}
|
||||
return MessageDraft{ChatID: chatID, SenderID: senderID, Text: text}, nil
|
||||
}
|
||||
|
||||
func (m Message) Position() Position { return Position{CreatedAt: m.CreatedAt, ID: m.ID} }
|
||||
@@ -0,0 +1,126 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func isValidationError(err error) bool {
|
||||
var v *ValidationError
|
||||
return errors.As(err, &v)
|
||||
}
|
||||
|
||||
func TestNewUserDraft(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name, username, display string
|
||||
ok bool
|
||||
}{
|
||||
{"minimal", "abc", "A", true},
|
||||
{"max username 32", strings.Repeat("a", 32), "A", true},
|
||||
{"username too short", "ab", "A", false},
|
||||
{"username too long", strings.Repeat("a", 33), "A", false},
|
||||
{"uppercase rejected", "Alice", "A", false},
|
||||
{"cyrillic username rejected", "алиса", "A", false},
|
||||
{"display 100 emoji ok", "abc", strings.Repeat("😀", 100), true},
|
||||
{"display 101 code points rejected", "abc", strings.Repeat("ж", 101), false},
|
||||
{"display whitespace only", "abc", " \t\n", false},
|
||||
{"display empty", "abc", "", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := NewUserDraft(tc.username, tc.display)
|
||||
if tc.ok && err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !tc.ok && !isValidationError(err) {
|
||||
t.Fatalf("want ValidationError, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewChatDraft(t *testing.T) {
|
||||
t.Parallel()
|
||||
me, other := uuid.New(), uuid.New()
|
||||
tooMany := []uuid.UUID{me}
|
||||
for range 100 {
|
||||
tooMany = append(tooMany, uuid.New())
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
members []uuid.UUID
|
||||
ok bool
|
||||
}{
|
||||
{"creator only", []uuid.UUID{me}, true},
|
||||
{"two members", []uuid.UUID{me, other}, true},
|
||||
{"empty", nil, false},
|
||||
{"creator missing", []uuid.UUID{other}, false},
|
||||
{"duplicate member", []uuid.UUID{me, other, other}, false},
|
||||
{"over 100 members", tooMany, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := NewChatDraft(me, "Чат", tc.members)
|
||||
if tc.ok != (err == nil) {
|
||||
t.Fatalf("ok=%v, err=%v", tc.ok, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMessageDraftLimitsInCodePoints(t *testing.T) {
|
||||
t.Parallel()
|
||||
if _, err := NewMessageDraft(uuid.New(), uuid.New(), strings.Repeat("👋", MaxMessageRunes)); err != nil {
|
||||
t.Fatalf("4000 four-byte code points must pass: %v", err)
|
||||
}
|
||||
if _, err := NewMessageDraft(uuid.New(), uuid.New(), strings.Repeat("a", MaxMessageRunes+1)); !isValidationError(err) {
|
||||
t.Fatalf("4001 code points must be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorRoundTripAndScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
pos := Position{CreatedAt: time.Date(2026, 9, 1, 12, 0, 0, 123456000, time.UTC), ID: uuid.New()}
|
||||
cursor := EncodeCursor("messages:a", pos)
|
||||
|
||||
q, err := NewPageQuery(nil, &cursor, "messages:a")
|
||||
if err != nil || q.After == nil || *q.After != pos || q.Limit != DefaultPageLimit {
|
||||
t.Fatalf("round trip failed: %+v, %v", q, err)
|
||||
}
|
||||
if _, err := NewPageQuery(nil, &cursor, "messages:b"); !isValidationError(err) {
|
||||
t.Fatalf("cursor of another resource must be rejected, got %v", err)
|
||||
}
|
||||
for _, bad := range []string{"", "!!!", EncodeCursor("x", pos)[:5]} {
|
||||
if _, err := NewPageQuery(nil, &bad, "messages:a"); !isValidationError(err) {
|
||||
t.Fatalf("garbage cursor %q must be rejected, got %v", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageLimitBounds(t *testing.T) {
|
||||
t.Parallel()
|
||||
for limit, ok := range map[int]bool{0: false, 1: true, 100: true, 101: false, -1: false} {
|
||||
_, err := NewPageQuery(&limit, nil, "chats")
|
||||
if ok != (err == nil) {
|
||||
t.Errorf("limit=%d: ok=%v, err=%v", limit, ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPositionOrderTiesBrokenByID(t *testing.T) {
|
||||
t.Parallel()
|
||||
at := time.Now()
|
||||
low := Position{CreatedAt: at, ID: uuid.MustParse("00000000-0000-4000-8000-000000000001")}
|
||||
high := Position{CreatedAt: at, ID: uuid.MustParse("ffffffff-0000-4000-8000-000000000000")}
|
||||
later := Position{CreatedAt: at.Add(time.Microsecond), ID: low.ID}
|
||||
if !high.After(low) || low.After(high) || !later.After(high) || low.After(low) {
|
||||
t.Fatal("order must be (created_at, id) ascending")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultPageLimit = 50
|
||||
MaxPageLimit = 100
|
||||
)
|
||||
|
||||
// Position — ключ keyset-пагинации: история упорядочена по (created_at, id).
|
||||
type Position struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// After сообщает, стоит ли p строго после other в порядке (created_at, id).
|
||||
func (p Position) After(other Position) bool {
|
||||
if !p.CreatedAt.Equal(other.CreatedAt) {
|
||||
return p.CreatedAt.After(other.CreatedAt)
|
||||
}
|
||||
return bytes.Compare(p.ID[:], other.ID[:]) > 0
|
||||
}
|
||||
|
||||
// PageQuery — проверенный запрос страницы: limit 1–100 и позиция после
|
||||
// последнего элемента предыдущей страницы (nil — с начала).
|
||||
type PageQuery struct {
|
||||
Limit int
|
||||
After *Position
|
||||
}
|
||||
|
||||
// NewPageQuery проверяет limit и курсор. scope привязывает курсор к ресурсу:
|
||||
// курсор истории одного чата не подходит к другому чату или к списку чатов.
|
||||
func NewPageQuery(limit *int, cursor *string, scope string) (PageQuery, error) {
|
||||
q := PageQuery{Limit: DefaultPageLimit}
|
||||
if limit != nil {
|
||||
if *limit < 1 || *limit > MaxPageLimit {
|
||||
return PageQuery{}, invalidf("limit: от 1 до %d", MaxPageLimit)
|
||||
}
|
||||
q.Limit = *limit
|
||||
}
|
||||
if cursor != nil {
|
||||
pos, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return PageQuery{}, err
|
||||
}
|
||||
q.After = &pos
|
||||
}
|
||||
return q, nil
|
||||
}
|
||||
|
||||
// EncodeCursor делает непрозрачную для клиента строку из позиции и scope.
|
||||
func EncodeCursor(scope string, p Position) string {
|
||||
raw := scope + "|" + strconv.FormatInt(p.CreatedAt.UnixMicro(), 10) + "|" + p.ID.String()
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, scope string) (Position, error) {
|
||||
errBad := invalidf("cursor: некорректное значение")
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return Position{}, errBad
|
||||
}
|
||||
parts := strings.Split(string(raw), "|")
|
||||
if len(parts) != 3 || parts[0] != scope {
|
||||
return Position{}, errBad
|
||||
}
|
||||
micros, err := strconv.ParseInt(parts[1], 10, 64)
|
||||
if err != nil {
|
||||
return Position{}, errBad
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return Position{}, errBad
|
||||
}
|
||||
return Position{CreatedAt: time.UnixMicro(micros).UTC(), ID: id}, nil
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package model
|
||||
import "testing"
|
||||
func TestRejectsNULInPersistedText(t *testing.T){
|
||||
for _,field:=range []string{"display_name","title","text"}{t.Run(field,func(t *testing.T){if err:=requireText(field,"a\x00b",1,4000);err==nil{t.Fatal("PostgreSQL text must reject NUL as a validation error")}})}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// requireText проверяет обязательную строку: длина в Unicode code points
|
||||
// (не в байтах) и запрет строк только из пробельных символов.
|
||||
func requireText(field, value string, minLen, maxLen int) error {
|
||||
if strings.ContainsRune(value,0){return invalidf("%s: NUL недопустим в PostgreSQL text",field)}
|
||||
if !utf8.ValidString(value) {
|
||||
return invalidf("%s: некорректный UTF-8", field)
|
||||
}
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return invalidf("%s: пустая строка", field)
|
||||
}
|
||||
if n := utf8.RuneCountInString(value); n < minLen || n > maxLen {
|
||||
return invalidf("%s: длина должна быть от %d до %d символов", field, minLen, maxLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// UserDraft — проверенные данные нового пользователя; ID и время назначает хранилище.
|
||||
type UserDraft struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func NewUserDraft(username, displayName string) (UserDraft, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return UserDraft{}, invalidf("username: допустимо [a-z0-9_], от 3 до 32 символов")
|
||||
}
|
||||
if err := requireText("display_name", displayName, 1, 100); err != nil {
|
||||
return UserDraft{}, err
|
||||
}
|
||||
return UserDraft{Username: username, DisplayName: displayName}, nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package port
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Passwords interface {
|
||||
Hash(string) (string, error)
|
||||
Verify(string, string) bool
|
||||
}
|
||||
type Sessions interface {
|
||||
Credentials(context.Context, string) (uuid.UUID, string, error)
|
||||
CreateSession(context.Context, string, uuid.UUID, time.Time) error
|
||||
AuthenticateSession(context.Context, string) (uuid.UUID, error)
|
||||
RevokeSession(context.Context, string) error
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Package repository — порт персистентности. В lab1 его реализует хранилище
|
||||
// в памяти процесса, с lab2 — PostgreSQL; ядро от этой замены не меняется.
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Repository assigns IDs and database timestamps. Keyset order is (created_at, id);
|
||||
// concurrent commits do not provide insertion order or a traversal snapshot.
|
||||
// Каждый метод атомарен сам по себе.
|
||||
type Repository interface {
|
||||
UserRepository
|
||||
ChatRepository
|
||||
MessageRepository
|
||||
}
|
||||
|
||||
type Persistent interface {
|
||||
Repository
|
||||
port.Sessions
|
||||
}
|
||||
|
||||
type UserRepository interface {
|
||||
// CreateUser: model.ErrUsernameTaken, model.ErrStorageFull.
|
||||
CreateUser(ctx context.Context, draft model.UserDraft) (model.User, error)
|
||||
// GetUser: model.ErrNotFound.
|
||||
GetUser(ctx context.Context, id uuid.UUID) (model.User, error)
|
||||
}
|
||||
|
||||
type ChatRepository interface {
|
||||
// CreateChat: model.ErrUnknownMember, model.ErrStorageFull.
|
||||
CreateChat(ctx context.Context, draft model.ChatDraft) (model.Chat, error)
|
||||
// GetChat: model.ErrNotFound.
|
||||
GetChat(ctx context.Context, id uuid.UUID) (model.Chat, error)
|
||||
// ListChats возвращает чаты участника и признак, что есть следующая страница.
|
||||
ListChats(ctx context.Context, memberID uuid.UUID, q model.PageQuery) ([]model.Chat, bool, error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
// CreateMessage: model.ErrNotFound (нет чата), model.ErrStorageFull.
|
||||
CreateMessage(ctx context.Context, draft model.MessageDraft) (model.Message, error)
|
||||
// ListMessages возвращает страницу истории и признак следующей страницы.
|
||||
ListMessages(ctx context.Context, chatID uuid.UUID, q model.PageQuery) ([]model.Message, bool, error)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
// New — JSON-логи в stdout, их собирает docker logs.
|
||||
func New(level string) zerolog.Logger {
|
||||
lvl, err := zerolog.ParseLevel(level)
|
||||
if err != nil || level == "" {
|
||||
lvl = zerolog.InfoLevel
|
||||
}
|
||||
zerolog.TimeFieldFormat = time.RFC3339Nano
|
||||
return zerolog.New(os.Stdout).Level(lvl).With().Timestamp().Logger()
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
}
|
||||
|
||||
func New(addr string, handler http.Handler) *Server {
|
||||
return &Server{httpServer: &http.Server{
|
||||
Addr: addr,
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 16 << 10,
|
||||
}}
|
||||
}
|
||||
|
||||
func (s *Server) ListenAndServe() error { return s.httpServer.ListenAndServe() }
|
||||
|
||||
// Shutdown сразу закрывает слушающий сокет (новые соединения не принимаются)
|
||||
// и ждёт завершения начатых запросов, но не дольше ctx.
|
||||
func (s *Server) Shutdown(ctx context.Context) error { return s.httpServer.Shutdown(ctx) }
|
||||
@@ -0,0 +1,83 @@
|
||||
name: vp-lab2-medvedev
|
||||
x-api: &api
|
||||
image: vp-medvedev-lab2:local
|
||||
build: .
|
||||
cpus: 1
|
||||
mem_limit: 512m
|
||||
stop_grace_period: 10s
|
||||
environment:
|
||||
APP_PORT: 8080
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
PG_MAX_CONNS: ${PG_MAX_CONNS:-8}
|
||||
GOMEMLIMIT: 400MiB
|
||||
secrets: [database_url, cache_url]
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
valkey: {condition: service_started}
|
||||
networks: [private]
|
||||
services:
|
||||
restore:
|
||||
image: postgres:18.6@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336
|
||||
profiles: [tools]
|
||||
cpus: 1
|
||||
mem_limit: 512m
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: restore
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
|
||||
secrets: [pg_password]
|
||||
volumes: [restore:/var/lib/postgresql]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, pg_isready -U messenger -d restore]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
networks: [private]
|
||||
postgres:
|
||||
image: postgres:18.6@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336
|
||||
cpus: 2
|
||||
mem_limit: 768m
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
|
||||
secrets: [pg_password]
|
||||
volumes: [postgres:/var/lib/postgresql]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, pg_isready -U messenger -d messenger]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
networks: [private]
|
||||
valkey:
|
||||
image: valkey/valkey:9@sha256:418652cfb58ef879d4978c33553735d7147016032d5aefaa14c828e611eb9dfd
|
||||
cpus: 0.25
|
||||
mem_limit: 128m
|
||||
command: [valkey-server, /run/secrets/valkey_conf]
|
||||
secrets: [valkey_conf]
|
||||
volumes: [valkey:/data]
|
||||
networks: [private]
|
||||
migrate:
|
||||
image: vp-medvedev-lab2:local
|
||||
build: .
|
||||
command: [-migrate]
|
||||
cpus: 0.5
|
||||
mem_limit: 256m
|
||||
secrets: [database_url]
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
networks: [private]
|
||||
api:
|
||||
<<: *api
|
||||
ports: ['127.0.0.1:${PUBLIC_PORT:-28202}:8080']
|
||||
volumes:
|
||||
restore:
|
||||
postgres:
|
||||
valkey:
|
||||
networks:
|
||||
private:
|
||||
secrets:
|
||||
pg_password: {file: .local/pg_password}
|
||||
database_url: {file: .local/database_url}
|
||||
cache_url: {file: .local/cache_url}
|
||||
valkey_conf: {file: .local/valkey.conf}
|
||||
@@ -0,0 +1,15 @@
|
||||
# Implementation plan and boundaries
|
||||
|
||||
Archived: this inherited lab2 plan is retained as historical context only. The completed lab2 implementation, results and limitations are documented in ../../REPORT.md; startup instructions are in ../../RUN.md.
|
||||
|
||||
This repository carries our lab1 domain, pagination, HTTP/error handling, bounded queue and shutdown code into the original lab2 skeleton. The lab1 memory adapter and its obsolete HTTP identity tests are not carried forward.
|
||||
|
||||
PostgreSQL is authoritative for users, passwords, sessions, chats, membership and messages. Valkey caches immutable public profiles for 60 seconds; no chat/message/session cache is used. Authentication always reads the session from PostgreSQL, and cache failure falls back to PostgreSQL within an 80 ms budget. Logout deletes the persisted token hash. Cache contents contain no password or bearer token.
|
||||
|
||||
Transactions: chat allocation + chat row + membership; sender quota + message; session owner lock + expiry cleanup + session insertion. PostgreSQL constraints enforce username uniqueness and foreign keys. Maximums: 1000 created chats and 1,000,000 messages per owner; 100 unexpired sessions. No user data is silently deleted. The history index covers `(chat_id,created_at,id)` and queries fetch only `limit+1` rows. Keyset traversal is not a snapshot; writes whose wall-clock timestamps fall before a consumed cursor can be missed during concurrent traversal.
|
||||
|
||||
Argon2id uses a random 16-byte salt, 32 MiB, two iterations, one lane, 32-byte result. Tokens use 32 random bytes; PostgreSQL stores only SHA-256 of the token. SHA-256 is appropriate for high-entropy tokens, not passwords. The API gate bounds concurrent KDF calls to four. PostgreSQL pool: eight connections, statement timeout 2 s, lock timeout 1 s, connect timeout 1 s; request context 5 s.
|
||||
|
||||
Readiness checks PostgreSQL. Valkey is optional to safe operation; its absence is observable through cache hit statistics and failure tests, not an anonymous-authentication fallback. HTTP is bound to localhost and uses only generated synthetic data.
|
||||
|
||||
Research: compare history queries over at least 100,000 skewed messages; restore a backup into a new database, compare row counts and selected message bytes. See `REPORT.md` for actual results; planned experiments are not evidence.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Closure review: VP laboratories 2–4
|
||||
|
||||
Проверено независимым агентом 12.11.2026. Объём — закрытие ранее найденных P1/P2 в текущих исходниках и operational helpers; полного повторного аудита не проводилось.
|
||||
|
||||
**Подтверждённых оставшихся ошибок в проверенном объёме не обнаружено.**
|
||||
|
||||
- Compose wrappers закрепляют файл и проект через явные `-f`/`-p`; research lab3 и reconciliation используют отдельные случайные проекты.
|
||||
- Reconciliation runner создаёт отдельные volumes, а destructive integration дополнительно требует пустые DB/bucket. Штатный профиль включает reconciliation, S3 metadata и foreign-membership regression.
|
||||
- Fixture cleanup проверяет чужое членство и подтверждает SQL COMMIT до удаления S3-оригиналов. Отказ SQL сохраняет байты.
|
||||
- Game guards разрешают измерения только при exit status `1`; активная игра и неизвестное состояние блокируют запуск.
|
||||
- Evidence сохраняется в отдельных каталогах запуска; итоговый PASS появляется после cleanup. Основная ошибка и ошибки уборки учитываются отдельно.
|
||||
- Monitor имеет немедленный rejection handler и завершается до cleanup. Rolling workload joined при отказе; замены проверяют readiness, продолжающиеся успешные записи и незавершённость нагрузки.
|
||||
- JSON middleware отвергает некорректный UTF-8 до декодирования; regression присутствует во всех трёх лабораторных.
|
||||
- В прочитанных acceptance2/3 уже используются `$fixture$` и PASS после cleanup. Их новое выполнение в это ревью не входило.
|
||||
|
||||
Проверка выполнена чтением кода, текущего плана и diff. Стенды, тесты, сборки и измерительные helpers не запускались; результаты автора повторно не подтверждались. Секреты и `.local` не читались. Единственное изменение ревьюера — этот файл.
|
||||
@@ -0,0 +1,69 @@
|
||||
14b7f3ced177639c80c8c9b113bef7d4783940b628f14d8bb6fc634eaa3d19e0 .dockerignore
|
||||
a45d7932ef14130aff8020bce79f043cccaf9692d697088a754d309a03f7d3e8 .github/workflows/contracts.yml
|
||||
b85d1e62d1f6d9c478cd1ce31c123c31c09a9c8b0565cf236f39a928a20a640b .gitignore
|
||||
314ecc42f648282ee0f8b758027f3bf8c1860679e388a1574ed88b07b70c400b Dockerfile
|
||||
668b2449e19b364092611561a28ca2cc83b6c8b35fde1c52ecfd2072795e6ca0 Makefile
|
||||
215578dee14bcef1b66759a68543083e0a624611efcdb785197307b50cb7725d backend/.golangci.yaml
|
||||
94e1e1caa8bcd1243b2ff16db3498a672b1e0202088812dc2839785a34d47794 backend/cmd/app/main.go
|
||||
90459ce1de93d68af72228f24601279d33fe2384bebe5ada57a5bd15b28dd7dd backend/codegen.yaml
|
||||
2063990a62d8b5eb00a88375eea46821e5ca197e8eaa016e70468fbc5e296bd2 backend/db/migrate.go
|
||||
057db27dac8043c3142c9530f2e699f312161813dfe829f043915ee7c7e0f08e backend/db/migrations/00001_core.sql
|
||||
bd945de5a2ad6d762e959888be4907d0927df524d535c9b5f4a80672f9e921fb backend/db/sqlc/queries/core.sql
|
||||
803b161e063692398c93152b11a08f9e42e1bf3c72a1e64553b82c494545fd10 backend/db/sqlc/sqlc.yaml
|
||||
62e951c7ddec4b5d1a4b643522ac4ecc25baba71ac71c8d3c3c65c9fd5bb47f5 backend/go.mod
|
||||
c80befc84323b33479f9ea9116d68ab1e3874597642ce0359c9dfe4733a568d9 backend/go.sum
|
||||
419dea68c3ac7b23b03bc1f5308516c21db04ec971451854ec1bdb71a64f0051 backend/internal/adapter/handler/api.gen.go
|
||||
5fdab8ab19080c0b8662b1bbae561fa00c5c1971dc3dd352419dba23f0920242 backend/internal/adapter/handler/api.go
|
||||
183217c9d66dcfb08d3da92fda01df509484bd3146b36587d84e37fbda5f3b4b backend/internal/adapter/handler/auth.go
|
||||
343035190d2e13beaeafd904a54e6f62226dc7d92bd6ae78c1b8bd39d42f60b0 backend/internal/adapter/handler/errors.go
|
||||
b662058ebc59010f30d21da12404837aa2329fe5e5590761efdd9140c1d24e9c backend/internal/adapter/handler/gate.go
|
||||
f7938bdeb5617ed3611303c54818000de9861dde5915fa2c6fa0f74e1fa33268 backend/internal/adapter/handler/gate_test.go
|
||||
f1961eebd1c3b21cdcf4af67be7882da47c85aaba969cc0d8eca73844a26a342 backend/internal/adapter/handler/handler.go
|
||||
964aee4c74d75f1249d2e15d10a4fcbfe0b8b7e4a02a41474911d12ec163bd0c backend/internal/adapter/handler/json.go
|
||||
64665f4273b7d676de8a3c17b20e71022a6295d16d89c3596aa24a005e26c227 backend/internal/adapter/handler/middleware.go
|
||||
5cd375e5a0db8cc3596293d323e635b86fef22d8ec680f310ab5a460f8176f64 backend/internal/adapter/handler/stats.go
|
||||
90a9e5400916860efb247b075bcd44aa2180f52aa753387ad6eb492d7a94aa0d backend/internal/adapter/handler/utf8_test.go
|
||||
94643bf4b61ca390f8dd56a241e02e1325a994fc40887ffa0e2b8f8e5aebb4c7 backend/internal/adapter/password/argon.go
|
||||
513a218e594616b5c594cca27bf1652d5321b0d567402303e1e103a19bbb63d8 backend/internal/adapter/repository/postgres/queries/core.sql.go
|
||||
4863732830879d4162be215ff245375b953359de23bcd821ed7abc5c32a36c0f backend/internal/adapter/repository/postgres/queries/db.go
|
||||
6db96a40a3db0f00e3d6adcc4c70d244261b4ee9c9db314f8b1b38b39987feb9 backend/internal/adapter/repository/postgres/queries/models.go
|
||||
d7be13d3654ea9bbcb93540d0b5015e291277284bd97894045b36ab6f9dfa25f backend/internal/adapter/repository/postgres/repository.go
|
||||
93802954db2c8eda3782acc71bca817947fd556986d3f6552c78c4b346d988ca backend/internal/application/usecase/auth.go
|
||||
c82c05555673b4bf831ad910652ef4c184419f1927e38a5d5fb586f184a4e481 backend/internal/application/usecase/messenger.go
|
||||
2a29236ab57ad3f56974709f870a1daa9040a097beda0bebe48d2b7698145cad backend/internal/config/config.go
|
||||
d6f02d9b4ab2dfa2ac92d85197142b39f7410d36ab66aa2388b6140c14379eff backend/internal/config/config_test.go
|
||||
3f7454f48ef442c277fd2741ce5aeeccf03d590bd2d31b9b89fa39f0ba05de7f backend/internal/domain/model/chat.go
|
||||
bd55666ad90ecaba3b0a1496ba5499580c0c67446284ce0b83e4dd7633cecbae backend/internal/domain/model/errors.go
|
||||
68d4bd9556a6f8b6704845bd68b8ed93b88c8a6f91cdcb75e5dd298f0e5d24ae backend/internal/domain/model/message.go
|
||||
77bb8767ac1352bd3551e724eaaeaad4fe93eae248cc8c3008ee8b1c08adddca backend/internal/domain/model/model_test.go
|
||||
cd6a07579bff01aa0d8a11b34fd000a804142b321cef302d386bdb95e9c7f953 backend/internal/domain/model/page.go
|
||||
834042a6cefa3cd5c04c778b69ac7289676fbb2cec097196d236c547f4c3cd2c backend/internal/domain/model/postgres_text_test.go
|
||||
5e548c33092d220408ce060fc498e3ef4f84358d7503fd679984f649bea46792 backend/internal/domain/model/text.go
|
||||
c20c8b8d8a9c0327a3a24afd74f3051d78caed1d2f0851baf340ef61ac502a92 backend/internal/domain/model/user.go
|
||||
465c1a1f19075b6f8301eef8dbd7fd9a8d20255716d72c97e946db04c2850dda backend/internal/domain/port/auth.go
|
||||
4402ef91f87910199103f059b654d362106059a4f0ee89e9cadfe7e6d49fa0ee backend/internal/domain/repository/repository.go
|
||||
d839f31015eee692065c31d2538a4cb4c841b0d89e690f0ab8baf80168510556 backend/pkg/logger/logger.go
|
||||
3ce957e4e45a94453610217007a9dbf0e8b9723346ff9cc8a3e5aa8ff3676527 backend/pkg/server/server.go
|
||||
bce35d0c70a825914ad0ff3a0bcdf6e7fbf520b399c576f0d75361068efd2e25 compose.example.yaml
|
||||
09eafa3bf3b4be0e2a40a619391d9e99cbf077b7167bc05efe5282fd43d3de64 compose.yaml
|
||||
0a71cec72903af556df85f939c7e347fc73a86a1a4ffc39fb9c8ded169b7df45 contracts/examples.json
|
||||
7efd8b1e6023ddc3ff9747d4f663ee772c1293b782bb9e74bd1c3fbcca9c68d8 contracts/infrastructure.json
|
||||
cff3aa6b34855b573401b0ac393fdfe327b6a12da51f315fbbd67168ce3762c4 contracts/openapi.json
|
||||
633c7b0f881173920b61a67c029e9bb4b59a385e5e34ab1b3d3254556602d554 examples/requests.http
|
||||
d63eac8df585a63153cff0c632e6b81b2088316b53d531eecc856ec1da7855e4 lab.json
|
||||
4cefdb67007caf026d1613be7c519c01b4c8343db7c4f4b618677e01cf113525 requirements-dev.txt
|
||||
01ea196f3a6db22c501209d7496bc774b4b04687fd5f30850acd863545852466 scripts/bootstrap.ts
|
||||
7c4402c2a6ab80d3b4676e1866d6ecc87b6daea14c080bcb9be9a7e8b959d671 scripts/check_contract.py
|
||||
cf202f8e11de3a0c32b99f6308086e3e334f7e7ee42175259104b9afef24a36e scripts/compose.sh
|
||||
0328246ba75defbced992104e986fde973f63e3830d83251eced5953263e944b scripts/restart.example.sh
|
||||
a5c632259396bcbc027c1e449dcd8f056aee098a2a861d4455b4e01ac167df62 scripts/restart.sh
|
||||
4e981acbfc10dac58817bf922d5896e996798551fedc1b2385130e1cddb13d54 scripts/validate_openapi.py
|
||||
cd56ac8b07663f72ba5b97a30ea9ecf35b2625cf6c218259d4465ac7ce0c8a4b student-tests/acceptance.ts
|
||||
1a69e392a1b0fc28869cc45c564225fe5e8cb8a784cf0a6ac1cbf3335c521205 student-tests/plot_research.py
|
||||
de950d3b75e4ad1a760c121533e06390c84574f7dd0b53c0eaa742ab6d5c2f38 student-tests/requirements-plots.txt
|
||||
29d44ba17c7fc65470d9893b3e2f4b03152670dae771e82d161535a54d301e14 student-tests/research.ts
|
||||
9dff91ee5a9876d5c4758d66a65b3b42c29a6d3071c7e510babae561a84cf35b student-tests/wait.ts
|
||||
8d50976fc7c7bbb81e88a152f613c61ab25eaf53dba33c6a9dfab19f868d546d tests/client.py
|
||||
6d3511ea719c7a7e841083e73d435c86dcbfd9f4e5c2a07d62eb9614b01d9933 tests/load.py
|
||||
1f96663a174b3978d24eff66f2741f5f8c9b788d3242261d37a972720c52788b tests/resilience.py
|
||||
52ac38eb343ff7d43e7543588e1da58ca06c9fce74b2b0d0bf0e4982bc23c1db tests/smoke.py
|
||||
@@ -0,0 +1 @@
|
||||
PASS lab2: 336 HTTP assertions, registration race, rollback, pagination, authentication; fixture cleanup completed
|
||||
@@ -0,0 +1,117 @@
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 1.04kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [api internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 1.78kB 0.0s done
|
||||
#2 transferring dockerfile: 1.78kB 0.0s done
|
||||
#2 DONE 0.2s
|
||||
|
||||
#3 [migrate] resolve image config for docker-image://docker.io/docker/dockerfile:1
|
||||
#3 DONE 1.1s
|
||||
|
||||
#4 [migrate] docker-image://docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e
|
||||
#4 resolve docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e
|
||||
#4 resolve docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e 0.3s done
|
||||
#4 resolve docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e 0.3s done
|
||||
#4 CACHED
|
||||
|
||||
#5 [migrate internal] load metadata for docker.io/library/golang:1.27.2-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d
|
||||
#5 DONE 1.2s
|
||||
|
||||
#6 [api internal] load metadata for gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#6 DONE 1.7s
|
||||
|
||||
#7 [api internal] load .dockerignore
|
||||
#7 transferring context: 226B 0.0s done
|
||||
#7 transferring context: 226B 0.0s done
|
||||
#7 DONE 0.2s
|
||||
|
||||
#8 [api internal] load build context
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [api stage-1 1/2] FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 resolve gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 ...
|
||||
|
||||
#8 [migrate internal] load build context
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [migrate stage-1 1/2] FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 resolve gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3 0.5s done
|
||||
#9 resolve gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3 0.5s done
|
||||
#9 DONE 0.6s
|
||||
|
||||
#10 [migrate build 1/4] FROM docker.io/library/golang:1.27.2-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d
|
||||
#10 resolve docker.io/library/golang:1.27.2-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d 0.5s done
|
||||
#10 DONE 0.7s
|
||||
|
||||
#8 [api internal] load build context
|
||||
#8 transferring context: 112.68kB 0.1s done
|
||||
#8 transferring context: 112.68kB 0.1s done
|
||||
#8 DONE 0.2s
|
||||
|
||||
#11 [api build 2/4] WORKDIR /src
|
||||
#11 CACHED
|
||||
|
||||
#12 [api build 3/4] COPY backend/ ./
|
||||
#12 DONE 0.8s
|
||||
|
||||
#13 [api build 4/4] RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build go build -trimpath -ldflags='-s -w' -o /out/messenger ./cmd/app
|
||||
#13 DONE 16.2s
|
||||
|
||||
#9 [migrate stage-1 1/2] FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
|
||||
#9 CACHED
|
||||
|
||||
#14 [api stage-1 2/2] COPY --from=build /out/messenger /messenger
|
||||
#14 DONE 0.8s
|
||||
|
||||
#15 [api] exporting to image
|
||||
#15 exporting layers
|
||||
#15 exporting layers 1.5s done
|
||||
#15 exporting manifest sha256:420d8986fe42013b348ce01966dcbc7423d8a3f886ba44061e8b0da274562a13
|
||||
#15 exporting manifest sha256:420d8986fe42013b348ce01966dcbc7423d8a3f886ba44061e8b0da274562a13 0.5s done
|
||||
#15 exporting config sha256:a5eaf732ed83ff935474f01ae795b3a399dd39d6900a9dbab4e93835b046c08c
|
||||
#15 exporting config sha256:a5eaf732ed83ff935474f01ae795b3a399dd39d6900a9dbab4e93835b046c08c 0.4s done
|
||||
#15 exporting attestation manifest sha256:28f4f8ef7b08bcced8fb5c84607544d308361905b34930e8e46d062abc2ebb65
|
||||
#15 exporting attestation manifest sha256:28f4f8ef7b08bcced8fb5c84607544d308361905b34930e8e46d062abc2ebb65 0.5s done
|
||||
#15 exporting manifest list sha256:d580b7aada585a3aa02767e4bf83fd399a066d1900678bc39754933ccb6b2d35
|
||||
#15 exporting manifest list sha256:d580b7aada585a3aa02767e4bf83fd399a066d1900678bc39754933ccb6b2d35 0.4s done
|
||||
#15 naming to docker.io/library/vp-medvedev-lab2:local 0.1s done
|
||||
#15 unpacking to docker.io/library/vp-medvedev-lab2:local
|
||||
#15 unpacking to docker.io/library/vp-medvedev-lab2:local 0.5s done
|
||||
#15 DONE 4.5s
|
||||
|
||||
#16 [migrate] exporting to image
|
||||
#16 exporting layers 1.5s done
|
||||
#16 exporting manifest sha256:aa34773f09faf99cb400ff24f73cab2f91966b0ad5e2c1a2d9dd6af5470a3e8e 0.4s done
|
||||
#16 exporting config sha256:7cec2ad23b8284ded9176f3a19141018829c073415ed867a6f1572b5b6d7a7b9 0.4s done
|
||||
#16 exporting attestation manifest sha256:b88219ef4264efc86f38e0a22aa73c6bfa543915b10b1a4d739f108f66c031fe 0.6s done
|
||||
#16 exporting manifest list sha256:008fd5996ed6259d260e67b09beb4089a2752931818a60cc5a4a9ef69269f90d 0.4s done
|
||||
#16 naming to docker.io/library/vp-medvedev-lab2:local 0.1s done
|
||||
#16 unpacking to docker.io/library/vp-medvedev-lab2:local 0.5s done
|
||||
#16 DONE 4.5s
|
||||
|
||||
#17 [migrate] resolving provenance for metadata file
|
||||
#17 DONE 0.0s
|
||||
|
||||
#18 [api] resolving provenance for metadata file
|
||||
#18 DONE 0.0s
|
||||
Image vp-medvedev-lab2:local Building
|
||||
Image vp-medvedev-lab2:local Building
|
||||
Image vp-medvedev-lab2:local Built
|
||||
Image vp-medvedev-lab2:local Built
|
||||
Container vp-lab2-medvedev-postgres-1 Running
|
||||
Container vp-lab2-medvedev-valkey-1 Running
|
||||
Container vp-lab2-medvedev-migrate-1 Recreate
|
||||
Container vp-lab2-medvedev-migrate-1 Recreated
|
||||
Container vp-lab2-medvedev-api-1 Recreate
|
||||
Container vp-lab2-medvedev-api-1 Recreated
|
||||
Container vp-lab2-medvedev-postgres-1 Waiting
|
||||
Container vp-lab2-medvedev-postgres-1 Healthy
|
||||
Container vp-lab2-medvedev-migrate-1 Starting
|
||||
Container vp-lab2-medvedev-migrate-1 Started
|
||||
Container vp-lab2-medvedev-migrate-1 Waiting
|
||||
Container vp-lab2-medvedev-migrate-1 Exited
|
||||
Container vp-lab2-medvedev-api-1 Starting
|
||||
Container vp-lab2-medvedev-api-1 Started
|
||||
@@ -0,0 +1,2 @@
|
||||
/mnt/data/home/bench-saves/vp-labs-vuIKezo9/lab2/.venv/bin/python scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,60 @@
|
||||
Collecting openapi-spec-validator==0.7.2 (from -r requirements-dev.txt (line 2))
|
||||
Downloading openapi_spec_validator-0.7.2-py3-none-any.whl.metadata (5.7 kB)
|
||||
Collecting jsonschema<5.0.0,>=4.18.0 (from openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading jsonschema-4.26.0-py3-none-any.whl.metadata (7.6 kB)
|
||||
Collecting jsonschema-path<0.4.0,>=0.3.1 (from openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading jsonschema_path-0.3.4-py3-none-any.whl.metadata (4.3 kB)
|
||||
Collecting lazy-object-proxy<2.0.0,>=1.7.1 (from openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading lazy_object_proxy-1.13.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl.metadata (5.1 kB)
|
||||
Collecting openapi-schema-validator<0.7.0,>=0.6.0 (from openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading openapi_schema_validator-0.6.3-py3-none-any.whl.metadata (5.4 kB)
|
||||
Collecting attrs>=22.2.0 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading attrs-26.1.0-py3-none-any.whl.metadata (8.8 kB)
|
||||
Collecting jsonschema-specifications>=2023.03.6 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading jsonschema_specifications-2025.9.1-py3-none-any.whl.metadata (2.9 kB)
|
||||
Collecting referencing>=0.28.4 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading referencing-0.37.0-py3-none-any.whl.metadata (2.8 kB)
|
||||
Collecting rpds-py>=0.25.0 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.1 kB)
|
||||
Collecting PyYAML>=5.1 (from jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (2.4 kB)
|
||||
Collecting pathable<0.5.0,>=0.4.1 (from jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading pathable-0.4.4-py3-none-any.whl.metadata (1.8 kB)
|
||||
Collecting referencing>=0.28.4 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading referencing-0.36.2-py3-none-any.whl.metadata (2.8 kB)
|
||||
Collecting requests<3.0.0,>=2.31.0 (from jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading requests-2.34.2-py3-none-any.whl.metadata (4.8 kB)
|
||||
Collecting rfc3339-validator (from openapi-schema-validator<0.7.0,>=0.6.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading rfc3339_validator-0.1.4-py2.py3-none-any.whl.metadata (1.5 kB)
|
||||
Collecting charset_normalizer<4,>=2 (from requests<3.0.0,>=2.31.0->jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading charset_normalizer-3.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (46 kB)
|
||||
Collecting idna<4,>=2.5 (from requests<3.0.0,>=2.31.0->jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading idna-3.20-py3-none-any.whl.metadata (7.2 kB)
|
||||
Collecting urllib3<3,>=1.26 (from requests<3.0.0,>=2.31.0->jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading urllib3-2.8.0-py3-none-any.whl.metadata (7.4 kB)
|
||||
Collecting certifi>=2023.5.7 (from requests<3.0.0,>=2.31.0->jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading certifi-2026.10.23-py3-none-any.whl.metadata (2.5 kB)
|
||||
Collecting six (from rfc3339-validator->openapi-schema-validator<0.7.0,>=0.6.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2))
|
||||
Downloading six-1.17.0-py2.py3-none-any.whl.metadata (1.7 kB)
|
||||
Downloading openapi_spec_validator-0.7.2-py3-none-any.whl (39 kB)
|
||||
Downloading jsonschema-4.26.0-py3-none-any.whl (90 kB)
|
||||
Downloading jsonschema_path-0.3.4-py3-none-any.whl (14 kB)
|
||||
Downloading lazy_object_proxy-1.13.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl (70 kB)
|
||||
Downloading openapi_schema_validator-0.6.3-py3-none-any.whl (8.8 kB)
|
||||
Downloading pathable-0.4.4-py3-none-any.whl (9.6 kB)
|
||||
Downloading referencing-0.36.2-py3-none-any.whl (26 kB)
|
||||
Downloading requests-2.34.2-py3-none-any.whl (73 kB)
|
||||
Downloading charset_normalizer-3.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (255 kB)
|
||||
Downloading idna-3.20-py3-none-any.whl (69 kB)
|
||||
Downloading urllib3-2.8.0-py3-none-any.whl (135 kB)
|
||||
Downloading attrs-26.1.0-py3-none-any.whl (67 kB)
|
||||
Downloading certifi-2026.10.23-py3-none-any.whl (135 kB)
|
||||
Downloading jsonschema_specifications-2025.9.1-py3-none-any.whl (18 kB)
|
||||
Downloading pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (794 kB)
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 794.2/794.2 kB 5.9 MB/s 0:00:00
|
||||
Downloading rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (371 kB)
|
||||
Downloading rfc3339_validator-0.1.4-py2.py3-none-any.whl (3.5 kB)
|
||||
Downloading six-1.17.0-py2.py3-none-any.whl (11 kB)
|
||||
Installing collected packages: urllib3, six, rpds-py, PyYAML, pathable, lazy-object-proxy, idna, charset_normalizer, certifi, attrs, rfc3339-validator, requests, referencing, jsonschema-specifications, jsonschema-path, jsonschema, openapi-schema-validator, openapi-spec-validator
|
||||
|
||||
Successfully installed PyYAML-6.0.3 attrs-26.1.0 certifi-2026.10.23 charset_normalizer-3.5.2 idna-3.20 jsonschema-4.26.0 jsonschema-path-0.3.4 jsonschema-specifications-2025.9.1 lazy-object-proxy-1.13.0 openapi-schema-validator-0.6.3 openapi-spec-validator-0.7.2 pathable-0.4.4 referencing-0.36.2 requests-2.34.2 rfc3339-validator-0.1.4 rpds-py-2026.9.1 six-1.17.0 urllib3-2.8.0
|
||||
@@ -0,0 +1 @@
|
||||
PASS lab2: 368 HTTP assertions, registration race, rollback, pagination, authentication; fixture cleanup completed
|
||||
@@ -0,0 +1,13 @@
|
||||
? backend/cmd/app [no test files]
|
||||
? backend/db [no test files]
|
||||
ok backend/internal/adapter/handler 1.039s
|
||||
? backend/internal/adapter/password [no test files]
|
||||
? backend/internal/adapter/repository/postgres [no test files]
|
||||
? backend/internal/adapter/repository/postgres/queries [no test files]
|
||||
? backend/internal/application/usecase [no test files]
|
||||
ok backend/internal/config 1.020s
|
||||
ok backend/internal/domain/model 1.016s
|
||||
? backend/internal/domain/port [no test files]
|
||||
? backend/internal/domain/repository [no test files]
|
||||
? backend/pkg/logger [no test files]
|
||||
? backend/pkg/server [no test files]
|
||||
@@ -0,0 +1 @@
|
||||
0 issues.
|
||||
@@ -0,0 +1,3 @@
|
||||
/mnt/data/home/bench-saves/vp-labs-vuIKezo9/lab2/.venv/bin/python tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:28202"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,41 @@
|
||||
Collecting matplotlib
|
||||
Downloading matplotlib-3.11.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (80 kB)
|
||||
Collecting contourpy>=1.0.1 (from matplotlib)
|
||||
Downloading contourpy-1.4.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (3.8 kB)
|
||||
Collecting cycler>=0.10 (from matplotlib)
|
||||
Downloading cycler-0.12.1-py3-none-any.whl.metadata (3.8 kB)
|
||||
Collecting fonttools>=4.28.2 (from matplotlib)
|
||||
Downloading fonttools-4.68.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (139 kB)
|
||||
Collecting kiwisolver>=1.3.1 (from matplotlib)
|
||||
Downloading kiwisolver-1.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (5.2 kB)
|
||||
Collecting numpy>=1.25 (from matplotlib)
|
||||
Downloading numpy-2.5.4-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (6.6 kB)
|
||||
Collecting packaging>=20.0 (from matplotlib)
|
||||
Downloading packaging-26.3-py3-none-any.whl.metadata (3.5 kB)
|
||||
Collecting pillow>=9 (from matplotlib)
|
||||
Downloading pillow-13.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (9.1 kB)
|
||||
Collecting pyparsing>=3 (from matplotlib)
|
||||
Downloading pyparsing-3.3.3-py3-none-any.whl.metadata (5.9 kB)
|
||||
Collecting python-dateutil>=2.7 (from matplotlib)
|
||||
Downloading python_dateutil-4.0.0-py3-none-any.whl.metadata (7.3 kB)
|
||||
Collecting tzdata (from python-dateutil>=2.7->matplotlib)
|
||||
Downloading tzdata-2026.6-py2.py3-none-any.whl.metadata (1.4 kB)
|
||||
Downloading matplotlib-3.11.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (11.0 MB)
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 11.0/11.0 MB 7.9 MB/s 0:00:01
|
||||
Downloading contourpy-1.4.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (384 kB)
|
||||
Downloading cycler-0.12.1-py3-none-any.whl (8.3 kB)
|
||||
Downloading fonttools-4.68.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (5.4 MB)
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.4/5.4 MB 8.3 MB/s 0:00:00
|
||||
Downloading kiwisolver-1.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (1.5 MB)
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.5/1.5 MB 7.9 MB/s 0:00:00
|
||||
Downloading numpy-2.5.4-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (16.7 MB)
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 16.7/16.7 MB 9.2 MB/s 0:00:01
|
||||
Downloading packaging-26.3-py3-none-any.whl (129 kB)
|
||||
Downloading pillow-13.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (7.1 MB)
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 7.1/7.1 MB 7.8 MB/s 0:00:00
|
||||
Downloading pyparsing-3.3.3-py3-none-any.whl (126 kB)
|
||||
Downloading python_dateutil-4.0.0-py3-none-any.whl (92 kB)
|
||||
Downloading tzdata-2026.6-py2.py3-none-any.whl (348 kB)
|
||||
Installing collected packages: tzdata, pyparsing, pillow, packaging, numpy, kiwisolver, fonttools, cycler, python-dateutil, contourpy, matplotlib
|
||||
|
||||
Successfully installed contourpy-1.4.0 cycler-0.12.1 fonttools-4.68.0 kiwisolver-1.5.1 matplotlib-3.11.2 numpy-2.5.4 packaging-26.3 pillow-13.0.0 pyparsing-3.3.3 python-dateutil-4.0.0 tzdata-2026.6
|
||||
@@ -0,0 +1 @@
|
||||
Ready: 1 API process(es)
|
||||
@@ -0,0 +1 @@
|
||||
Ready: 1 API process(es)
|
||||
@@ -0,0 +1 @@
|
||||
FAIL: POST /api/v1/users: expected [201], received 400
|
||||
@@ -0,0 +1,145 @@
|
||||
[
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 3795.18,
|
||||
"Total Cost": 3800.99,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 5.380,
|
||||
"Actual Total Time": 6.963,
|
||||
"Actual Rows": 51.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 1250,
|
||||
"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": "Gather Merge",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 3795.18,
|
||||
"Total Cost": 6877.40,
|
||||
"Plan Rows": 27044,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 5.378,
|
||||
"Actual Total Time": 6.959,
|
||||
"Actual Rows": 51.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Workers Planned": 1,
|
||||
"Workers Launched": 1,
|
||||
"Shared Hit Blocks": 1250,
|
||||
"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": "Sort",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 2795.17,
|
||||
"Total Cost": 2834.94,
|
||||
"Plan Rows": 15908,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 4.036,
|
||||
"Actual Total Time": 4.038,
|
||||
"Actual Rows": 51.00,
|
||||
"Actual Loops": 2,
|
||||
"Disabled": false,
|
||||
"Sort Key": ["created_at", "id"],
|
||||
"Sort Method": "top-N heapsort",
|
||||
"Sort Space Used": 31,
|
||||
"Sort Space Type": "Memory",
|
||||
"Shared Hit Blocks": 1250,
|
||||
"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,
|
||||
"Workers": [
|
||||
{
|
||||
"Worker Number": 0,
|
||||
"Sort Method": "top-N heapsort",
|
||||
"Sort Space Used": 31,
|
||||
"Sort Space Type": "Memory"
|
||||
}
|
||||
],
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Seq Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": true,
|
||||
"Async Capable": false,
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.00,
|
||||
"Total Cost": 2264.44,
|
||||
"Plan Rows": 15908,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 2.269,
|
||||
"Actual Total Time": 3.504,
|
||||
"Actual Rows": 10000.50,
|
||||
"Actual Loops": 2,
|
||||
"Disabled": false,
|
||||
"Filter": "((chat_id = 'd5f6496b-22d2-4d83-9840-843c175d2196'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.07+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))",
|
||||
"Rows Removed by Filter": 40001,
|
||||
"Shared Hit Blocks": 1235,
|
||||
"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,
|
||||
"Workers": [
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 99,
|
||||
"Shared Read Blocks": 1,
|
||||
"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.246,
|
||||
"Triggers": [
|
||||
],
|
||||
"Execution Time": 7.009
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,125 @@
|
||||
[
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "ModifyTable",
|
||||
"Operation": "Insert",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.00,
|
||||
"Total Cost": 32.50,
|
||||
"Plan Rows": 0,
|
||||
"Plan Width": 0,
|
||||
"Actual Startup Time": 5.310,
|
||||
"Actual Total Time": 5.310,
|
||||
"Actual Rows": 0.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 6083,
|
||||
"Shared Read Blocks": 2,
|
||||
"Shared Dirtied Blocks": 18,
|
||||
"Shared Written Blocks": 16,
|
||||
"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": "Subquery Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Alias": "*SELECT*",
|
||||
"Startup Cost": 0.00,
|
||||
"Total Cost": 32.50,
|
||||
"Plan Rows": 1000,
|
||||
"Plan Width": 88,
|
||||
"Actual Startup Time": 0.077,
|
||||
"Actual Total Time": 1.233,
|
||||
"Actual Rows": 1000.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 0,
|
||||
"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": "Function Scan",
|
||||
"Parent Relationship": "Subquery",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Function Name": "generate_series",
|
||||
"Alias": "i",
|
||||
"Startup Cost": 0.00,
|
||||
"Total Cost": 20.00,
|
||||
"Plan Rows": 1000,
|
||||
"Plan Width": 112,
|
||||
"Actual Startup Time": 0.076,
|
||||
"Actual Total Time": 1.121,
|
||||
"Actual Rows": 1000.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 0,
|
||||
"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": 24,
|
||||
"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.102,
|
||||
"Triggers": [
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16467",
|
||||
"Constraint Name": "messages_chat_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.453,
|
||||
"Calls": 1000
|
||||
},
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16472",
|
||||
"Constraint Name": "messages_sender_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.728,
|
||||
"Calls": 1000
|
||||
},
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16477",
|
||||
"Constraint Name": "messages_chat_id_sender_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.594,
|
||||
"Calls": 1000
|
||||
}
|
||||
],
|
||||
"Execution Time": 16.243
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,480 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
|
||||
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="648pt" height="252pt" viewBox="0 0 648 252" xmlns="http://www.w3.org/2000/svg" version="1.1">
|
||||
<metadata>
|
||||
<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<cc:Work>
|
||||
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
|
||||
<dc:date>2026-11-12T16:36:05.047255</dc:date>
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:creator>
|
||||
<cc:Agent>
|
||||
<dc:title>Matplotlib v3.11.2, https://matplotlib.org/</dc:title>
|
||||
</cc:Agent>
|
||||
</dc:creator>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<defs>
|
||||
<style type="text/css">*{stroke-linejoin: round; stroke-linecap: butt}</style>
|
||||
</defs>
|
||||
<g id="figure_1">
|
||||
<g id="patch_1">
|
||||
<path d="M 0 252
|
||||
L 648 252
|
||||
L 648 0
|
||||
L 0 0
|
||||
z
|
||||
" style="fill: #ffffff"/>
|
||||
</g>
|
||||
<g id="axes_1">
|
||||
<g id="patch_2">
|
||||
<path d="M 47.501021 231.998979
|
||||
L 326.1475 231.998979
|
||||
L 326.1475 36.119782
|
||||
L 47.501021 36.119782
|
||||
z
|
||||
" style="fill: #ffffff"/>
|
||||
</g>
|
||||
<g id="patch_3">
|
||||
<path d="M 60.16677 89679.621856
|
||||
L 172.751206 89679.621856
|
||||
L 172.751206 45.023382
|
||||
L 60.16677 45.023382
|
||||
z
|
||||
" clip-path="url(#p6814e01ebe)" style="fill: #6b7280"/>
|
||||
</g>
|
||||
<g id="patch_4">
|
||||
<path d="M 200.897315 89679.621856
|
||||
L 313.481751 89679.621856
|
||||
L 313.481751 223.095379
|
||||
L 200.897315 223.095379
|
||||
z
|
||||
" clip-path="url(#p6814e01ebe)" style="fill: #2563eb"/>
|
||||
</g>
|
||||
<g id="matplotlib.axis_1">
|
||||
<g id="xtick_1">
|
||||
<g id="line2d_1">
|
||||
<defs>
|
||||
<path id="ma83e7220dd" d="M 0 0
|
||||
L 0 3.5
|
||||
" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</defs>
|
||||
<g>
|
||||
<use xlink:href="#ma83e7220dd" x="116.458988" y="231.998979" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_1">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="116.458988" y="246.597416" transform="rotate(-0 116.458988 246.597416)">chat_id</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="xtick_2">
|
||||
<g id="line2d_2">
|
||||
<g>
|
||||
<use xlink:href="#ma83e7220dd" x="257.189533" y="231.998979" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_2">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="257.189533" y="246.597416" transform="rotate(-0 257.189533 246.597416)">chat_id + time + id</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="matplotlib.axis_2">
|
||||
<g id="ytick_1">
|
||||
<g id="line2d_3">
|
||||
<defs>
|
||||
<path id="meafe312f9a" d="M 0 0
|
||||
L -3.5 0
|
||||
" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</defs>
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="47.501021" y="210.31824" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_3">
|
||||
<!-- $\mathdefault{10^{-1}}$ -->
|
||||
<g transform="translate(17.001021 214.96824)">
|
||||
<text>
|
||||
<tspan x="0" y="-0.762187" style="font-size: 10px; font-family: 'DejaVu Sans'">1</tspan>
|
||||
<tspan x="6.362305" y="-0.762187" style="font-size: 10px; font-family: 'DejaVu Sans'">0</tspan>
|
||||
<tspan x="12.820312" y="-4.892187" style="font-size: 7px; font-family: 'DejaVu Sans'">−</tspan>
|
||||
<tspan x="18.685547" y="-4.892187" style="font-size: 7px; font-family: 'DejaVu Sans'">1</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_2">
|
||||
<g id="line2d_4">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="47.501021" y="120.759377" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_4">
|
||||
<!-- $\mathdefault{10^{0}}$ -->
|
||||
<g transform="translate(22.901021 125.459377)">
|
||||
<text>
|
||||
<tspan x="0" y="-0.674688" style="font-size: 10px; font-family: 'DejaVu Sans'">1</tspan>
|
||||
<tspan x="6.362305" y="-0.674688" style="font-size: 10px; font-family: 'DejaVu Sans'">0</tspan>
|
||||
<tspan x="12.820312" y="-4.804688" style="font-size: 7px; font-family: 'DejaVu Sans'">0</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_3">
|
||||
<g id="line2d_5">
|
||||
<defs>
|
||||
<path id="mea213b5217" d="M 0 0
|
||||
L -2 0
|
||||
" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</defs>
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="230.186761" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_4">
|
||||
<g id="line2d_6">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="224.191083" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_5">
|
||||
<g id="line2d_7">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="218.99739" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_6">
|
||||
<g id="line2d_8">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="214.416228" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_7">
|
||||
<g id="line2d_9">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="183.358336" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_8">
|
||||
<g id="line2d_10">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="167.587803" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_9">
|
||||
<g id="line2d_11">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="156.398432" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_10">
|
||||
<g id="line2d_12">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="147.719281" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_11">
|
||||
<g id="line2d_13">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="140.627899" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_12">
|
||||
<g id="line2d_14">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="134.63222" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_13">
|
||||
<g id="line2d_15">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="129.438528" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_14">
|
||||
<g id="line2d_16">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="124.857366" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_15">
|
||||
<g id="line2d_17">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="93.799473" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_16">
|
||||
<g id="line2d_18">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="78.02894" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_17">
|
||||
<g id="line2d_19">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="66.839569" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_18">
|
||||
<g id="line2d_20">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="58.160419" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_19">
|
||||
<g id="line2d_21">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="51.069036" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_20">
|
||||
<g id="line2d_22">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="45.073358" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_21">
|
||||
<g id="line2d_23">
|
||||
<g>
|
||||
<use xlink:href="#mea213b5217" x="47.501021" y="39.879665" style="stroke: #000000; stroke-width: 0.6"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_5">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="10.598678" y="134.059381" transform="rotate(-90 10.598678 134.059381)">Execution time, ms</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="patch_5">
|
||||
<path d="M 47.501021 231.998979
|
||||
L 47.501021 36.119782
|
||||
" style="fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square"/>
|
||||
</g>
|
||||
<g id="patch_6">
|
||||
<path d="M 326.1475 231.998979
|
||||
L 326.1475 36.119782
|
||||
" style="fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square"/>
|
||||
</g>
|
||||
<g id="patch_7">
|
||||
<path d="M 47.501021 231.998979
|
||||
L 326.1475 231.998979
|
||||
" style="fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square"/>
|
||||
</g>
|
||||
<g id="patch_8">
|
||||
<path d="M 47.501021 36.119782
|
||||
L 326.1475 36.119782
|
||||
" style="fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square"/>
|
||||
</g>
|
||||
<g id="text_6">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="116.458988" y="41.023382" transform="rotate(-0 116.458988 41.023382)">7.009</text>
|
||||
</g>
|
||||
<g id="text_7">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="257.189533" y="219.095379" transform="rotate(-0 257.189533 219.095379)">0.072</text>
|
||||
</g>
|
||||
<g id="text_8">
|
||||
<text style="font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="186.824261" y="30.119782" transform="rotate(-0 186.824261 30.119782)">Deep history page (51 rows)</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="axes_2">
|
||||
<g id="patch_9">
|
||||
<path d="M 366.353281 231.998979
|
||||
L 644.99976 231.998979
|
||||
L 644.99976 36.119782
|
||||
L 366.353281 36.119782
|
||||
z
|
||||
" style="fill: #ffffff"/>
|
||||
</g>
|
||||
<g id="patch_10">
|
||||
<path d="M 379.01903 231.998979
|
||||
L 491.603466 231.998979
|
||||
L 491.603466 49.569244
|
||||
L 379.01903 49.569244
|
||||
z
|
||||
" clip-path="url(#p34ed0a19f5)" style="fill: #6b7280"/>
|
||||
</g>
|
||||
<g id="patch_11">
|
||||
<path d="M 519.749575 231.998979
|
||||
L 632.334011 231.998979
|
||||
L 632.334011 45.447363
|
||||
L 519.749575 45.447363
|
||||
z
|
||||
" clip-path="url(#p34ed0a19f5)" style="fill: #2563eb"/>
|
||||
</g>
|
||||
<g id="matplotlib.axis_3">
|
||||
<g id="xtick_3">
|
||||
<g id="line2d_24">
|
||||
<g>
|
||||
<use xlink:href="#ma83e7220dd" x="435.311248" y="231.998979" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_9">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="435.311248" y="246.597416" transform="rotate(-0 435.311248 246.597416)">chat_id</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="xtick_4">
|
||||
<g id="line2d_25">
|
||||
<g>
|
||||
<use xlink:href="#ma83e7220dd" x="576.041793" y="231.998979" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_10">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="576.041793" y="246.597416" transform="rotate(-0 576.041793 246.597416)">chat_id + time + id</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
<g id="matplotlib.axis_4">
|
||||
<g id="ytick_22">
|
||||
<g id="line2d_26">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="231.998979" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_11">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="235.797807" transform="rotate(-0 359.353281 235.797807)">0</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_23">
|
||||
<g id="line2d_27">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="209.536412" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_12">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="213.33524" transform="rotate(-0 359.353281 213.33524)">2</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_24">
|
||||
<g id="line2d_28">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="187.073846" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_13">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="190.872674" transform="rotate(-0 359.353281 190.872674)">4</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_25">
|
||||
<g id="line2d_29">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="164.611279" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_14">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="168.410107" transform="rotate(-0 359.353281 168.410107)">6</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_26">
|
||||
<g id="line2d_30">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="142.148712" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_15">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="145.947541" transform="rotate(-0 359.353281 145.947541)">8</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_27">
|
||||
<g id="line2d_31">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="119.686146" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_16">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="123.484974" transform="rotate(-0 359.353281 123.484974)">10</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_28">
|
||||
<g id="line2d_32">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="97.223579" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_17">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="101.022407" transform="rotate(-0 359.353281 101.022407)">12</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_29">
|
||||
<g id="line2d_33">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="74.761013" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_18">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="78.559841" transform="rotate(-0 359.353281 78.559841)">14</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="ytick_30">
|
||||
<g id="line2d_34">
|
||||
<g>
|
||||
<use xlink:href="#meafe312f9a" x="366.353281" y="52.298446" style="stroke: #000000; stroke-width: 0.8"/>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_19">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end" x="359.353281" y="56.097274" transform="rotate(-0 359.353281 56.097274)">16</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_20">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="340.225938" y="134.059381" transform="rotate(-90 340.225938 134.059381)">Execution time, ms</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="patch_12">
|
||||
<path d="M 366.353281 231.998979
|
||||
L 366.353281 36.119782
|
||||
" style="fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square"/>
|
||||
</g>
|
||||
<g id="patch_13">
|
||||
<path d="M 644.99976 231.998979
|
||||
L 644.99976 36.119782
|
||||
" style="fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square"/>
|
||||
</g>
|
||||
<g id="patch_14">
|
||||
<path d="M 366.353281 231.998979
|
||||
L 644.99976 231.998979
|
||||
" style="fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square"/>
|
||||
</g>
|
||||
<g id="patch_15">
|
||||
<path d="M 366.353281 36.119782
|
||||
L 644.99976 36.119782
|
||||
" style="fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square"/>
|
||||
</g>
|
||||
<g id="text_21">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="435.311248" y="45.569244" transform="rotate(-0 435.311248 45.569244)">16.243</text>
|
||||
</g>
|
||||
<g id="text_22">
|
||||
<text style="font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="576.041793" y="41.447363" transform="rotate(-0 576.041793 41.447363)">16.610</text>
|
||||
</g>
|
||||
<g id="text_23">
|
||||
<text style="font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="505.676521" y="30.119782" transform="rotate(-0 505.676521 30.119782)">Insert 1,000 messages</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="text_24">
|
||||
<text style="font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle" x="324" y="12.118365" transform="rotate(-0 324 12.118365)">100,000 skewed messages; one EXPLAIN ANALYZE per index</text>
|
||||
</g>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="p6814e01ebe">
|
||||
<rect x="47.501021" y="36.119782" width="278.646479" height="195.879196"/>
|
||||
</clipPath>
|
||||
<clipPath id="p34ed0a19f5">
|
||||
<rect x="366.353281" y="36.119782" width="278.646479" height="195.879196"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,78 @@
|
||||
[
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.42,
|
||||
"Total Cost": 10.93,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 0.031,
|
||||
"Actual Total Time": 0.037,
|
||||
"Actual Rows": 51.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 1,
|
||||
"Shared Read Blocks": 3,
|
||||
"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_history",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.42,
|
||||
"Total Cost": 5761.96,
|
||||
"Plan Rows": 27952,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 0.030,
|
||||
"Actual Total Time": 0.034,
|
||||
"Actual Rows": 51.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Index Cond": "((chat_id = 'd5f6496b-22d2-4d83-9840-843c175d2196'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.07+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Index Searches": 1,
|
||||
"Shared Hit Blocks": 1,
|
||||
"Shared Read Blocks": 3,
|
||||
"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": 1,
|
||||
"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.276,
|
||||
"Triggers": [
|
||||
],
|
||||
"Execution Time": 0.072
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,125 @@
|
||||
[
|
||||
{
|
||||
"Plan": {
|
||||
"Node Type": "ModifyTable",
|
||||
"Operation": "Insert",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.00,
|
||||
"Total Cost": 32.50,
|
||||
"Plan Rows": 0,
|
||||
"Plan Width": 0,
|
||||
"Actual Startup Time": 5.299,
|
||||
"Actual Total Time": 5.299,
|
||||
"Actual Rows": 0.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 5142,
|
||||
"Shared Read Blocks": 2,
|
||||
"Shared Dirtied Blocks": 26,
|
||||
"Shared Written Blocks": 24,
|
||||
"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": "Subquery Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Alias": "*SELECT*",
|
||||
"Startup Cost": 0.00,
|
||||
"Total Cost": 32.50,
|
||||
"Plan Rows": 1000,
|
||||
"Plan Width": 88,
|
||||
"Actual Startup Time": 0.054,
|
||||
"Actual Total Time": 1.217,
|
||||
"Actual Rows": 1000.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 0,
|
||||
"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": "Function Scan",
|
||||
"Parent Relationship": "Subquery",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Function Name": "generate_series",
|
||||
"Alias": "i",
|
||||
"Startup Cost": 0.00,
|
||||
"Total Cost": 20.00,
|
||||
"Plan Rows": 1000,
|
||||
"Plan Width": 112,
|
||||
"Actual Startup Time": 0.054,
|
||||
"Actual Total Time": 1.104,
|
||||
"Actual Rows": 1000.00,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 0,
|
||||
"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": 24,
|
||||
"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.098,
|
||||
"Triggers": [
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16467",
|
||||
"Constraint Name": "messages_chat_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.547,
|
||||
"Calls": 1000
|
||||
},
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16472",
|
||||
"Constraint Name": "messages_sender_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.867,
|
||||
"Calls": 1000
|
||||
},
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16477",
|
||||
"Constraint Name": "messages_chat_id_sender_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.739,
|
||||
"Calls": 1000
|
||||
}
|
||||
],
|
||||
"Execution Time": 16.610
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
{"run_id":"8a1784b7aac7","started_at":"2026-11-12T13:13:44.368Z","state":"started"}
|
||||
@@ -0,0 +1,513 @@
|
||||
{
|
||||
"run_id": "8a1784b7aac7",
|
||||
"complete": true,
|
||||
"dataset": {
|
||||
"messages": 100000,
|
||||
"distribution": [
|
||||
90000,
|
||||
9000,
|
||||
1000
|
||||
]
|
||||
},
|
||||
"plans": {
|
||||
"chat_only": {
|
||||
"read": {
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 3795.18,
|
||||
"Total Cost": 3800.99,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 5.38,
|
||||
"Actual Total Time": 6.963,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 1250,
|
||||
"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": "Gather Merge",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 3795.18,
|
||||
"Total Cost": 6877.4,
|
||||
"Plan Rows": 27044,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 5.378,
|
||||
"Actual Total Time": 6.959,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Workers Planned": 1,
|
||||
"Workers Launched": 1,
|
||||
"Shared Hit Blocks": 1250,
|
||||
"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": "Sort",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 2795.17,
|
||||
"Total Cost": 2834.94,
|
||||
"Plan Rows": 15908,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 4.036,
|
||||
"Actual Total Time": 4.038,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 2,
|
||||
"Disabled": false,
|
||||
"Sort Key": [
|
||||
"created_at",
|
||||
"id"
|
||||
],
|
||||
"Sort Method": "top-N heapsort",
|
||||
"Sort Space Used": 31,
|
||||
"Sort Space Type": "Memory",
|
||||
"Shared Hit Blocks": 1250,
|
||||
"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,
|
||||
"Workers": [
|
||||
{
|
||||
"Worker Number": 0,
|
||||
"Sort Method": "top-N heapsort",
|
||||
"Sort Space Used": 31,
|
||||
"Sort Space Type": "Memory"
|
||||
}
|
||||
],
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Seq Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": true,
|
||||
"Async Capable": false,
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0,
|
||||
"Total Cost": 2264.44,
|
||||
"Plan Rows": 15908,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 2.269,
|
||||
"Actual Total Time": 3.504,
|
||||
"Actual Rows": 10000.5,
|
||||
"Actual Loops": 2,
|
||||
"Disabled": false,
|
||||
"Filter": "((chat_id = 'd5f6496b-22d2-4d83-9840-843c175d2196'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.07+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))",
|
||||
"Rows Removed by Filter": 40001,
|
||||
"Shared Hit Blocks": 1235,
|
||||
"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,
|
||||
"Workers": []
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 99,
|
||||
"Shared Read Blocks": 1,
|
||||
"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.246,
|
||||
"Triggers": [],
|
||||
"Execution Time": 7.009
|
||||
},
|
||||
"write": {
|
||||
"Plan": {
|
||||
"Node Type": "ModifyTable",
|
||||
"Operation": "Insert",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0,
|
||||
"Total Cost": 32.5,
|
||||
"Plan Rows": 0,
|
||||
"Plan Width": 0,
|
||||
"Actual Startup Time": 5.31,
|
||||
"Actual Total Time": 5.31,
|
||||
"Actual Rows": 0,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 6083,
|
||||
"Shared Read Blocks": 2,
|
||||
"Shared Dirtied Blocks": 18,
|
||||
"Shared Written Blocks": 16,
|
||||
"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": "Subquery Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Alias": "*SELECT*",
|
||||
"Startup Cost": 0,
|
||||
"Total Cost": 32.5,
|
||||
"Plan Rows": 1000,
|
||||
"Plan Width": 88,
|
||||
"Actual Startup Time": 0.077,
|
||||
"Actual Total Time": 1.233,
|
||||
"Actual Rows": 1000,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 0,
|
||||
"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": "Function Scan",
|
||||
"Parent Relationship": "Subquery",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Function Name": "generate_series",
|
||||
"Alias": "i",
|
||||
"Startup Cost": 0,
|
||||
"Total Cost": 20,
|
||||
"Plan Rows": 1000,
|
||||
"Plan Width": 112,
|
||||
"Actual Startup Time": 0.076,
|
||||
"Actual Total Time": 1.121,
|
||||
"Actual Rows": 1000,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 0,
|
||||
"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": 24,
|
||||
"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.102,
|
||||
"Triggers": [
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16467",
|
||||
"Constraint Name": "messages_chat_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.453,
|
||||
"Calls": 1000
|
||||
},
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16472",
|
||||
"Constraint Name": "messages_sender_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.728,
|
||||
"Calls": 1000
|
||||
},
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16477",
|
||||
"Constraint Name": "messages_chat_id_sender_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.594,
|
||||
"Calls": 1000
|
||||
}
|
||||
],
|
||||
"Execution Time": 16.243
|
||||
}
|
||||
},
|
||||
"history": {
|
||||
"read": {
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.42,
|
||||
"Total Cost": 10.93,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 0.031,
|
||||
"Actual Total Time": 0.037,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 1,
|
||||
"Shared Read Blocks": 3,
|
||||
"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_history",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.42,
|
||||
"Total Cost": 5761.96,
|
||||
"Plan Rows": 27952,
|
||||
"Plan Width": 71,
|
||||
"Actual Startup Time": 0.03,
|
||||
"Actual Total Time": 0.034,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Index Cond": "((chat_id = 'd5f6496b-22d2-4d83-9840-843c175d2196'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.07+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Index Searches": 1,
|
||||
"Shared Hit Blocks": 1,
|
||||
"Shared Read Blocks": 3,
|
||||
"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": 1,
|
||||
"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.276,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.072
|
||||
},
|
||||
"write": {
|
||||
"Plan": {
|
||||
"Node Type": "ModifyTable",
|
||||
"Operation": "Insert",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0,
|
||||
"Total Cost": 32.5,
|
||||
"Plan Rows": 0,
|
||||
"Plan Width": 0,
|
||||
"Actual Startup Time": 5.299,
|
||||
"Actual Total Time": 5.299,
|
||||
"Actual Rows": 0,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 5142,
|
||||
"Shared Read Blocks": 2,
|
||||
"Shared Dirtied Blocks": 26,
|
||||
"Shared Written Blocks": 24,
|
||||
"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": "Subquery Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Alias": "*SELECT*",
|
||||
"Startup Cost": 0,
|
||||
"Total Cost": 32.5,
|
||||
"Plan Rows": 1000,
|
||||
"Plan Width": 88,
|
||||
"Actual Startup Time": 0.054,
|
||||
"Actual Total Time": 1.217,
|
||||
"Actual Rows": 1000,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 0,
|
||||
"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": "Function Scan",
|
||||
"Parent Relationship": "Subquery",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Function Name": "generate_series",
|
||||
"Alias": "i",
|
||||
"Startup Cost": 0,
|
||||
"Total Cost": 20,
|
||||
"Plan Rows": 1000,
|
||||
"Plan Width": 112,
|
||||
"Actual Startup Time": 0.054,
|
||||
"Actual Total Time": 1.104,
|
||||
"Actual Rows": 1000,
|
||||
"Actual Loops": 1,
|
||||
"Disabled": false,
|
||||
"Shared Hit Blocks": 0,
|
||||
"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": 24,
|
||||
"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.098,
|
||||
"Triggers": [
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16467",
|
||||
"Constraint Name": "messages_chat_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.547,
|
||||
"Calls": 1000
|
||||
},
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16472",
|
||||
"Constraint Name": "messages_sender_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.867,
|
||||
"Calls": 1000
|
||||
},
|
||||
{
|
||||
"Trigger Name": "RI_ConstraintTrigger_c_16477",
|
||||
"Constraint Name": "messages_chat_id_sender_id_fkey",
|
||||
"Relation": "messages",
|
||||
"Time": 3.739,
|
||||
"Calls": 1000
|
||||
}
|
||||
],
|
||||
"Execution Time": 16.61
|
||||
}
|
||||
}
|
||||
},
|
||||
"backup": {
|
||||
"dump_seconds": 0.4851582589999998,
|
||||
"bytes": 3034766,
|
||||
"restore_seconds": 1.509961217,
|
||||
"verified": {
|
||||
"users": 7,
|
||||
"chats": 5,
|
||||
"members": 7,
|
||||
"messages": 102003,
|
||||
"research_messages": 102000,
|
||||
"samples": [
|
||||
{
|
||||
"id": "8d10e913-b6a3-4ea4-a61a-42b38ad0c01c",
|
||||
"text": "synthetic-1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00"
|
||||
},
|
||||
{
|
||||
"id": "49398fa6-3afb-4f81-90c8-8c5c8a2342bf",
|
||||
"text": "synthetic-2",
|
||||
"created_at": "2026-01-01T00:00:00.000002+00:00"
|
||||
},
|
||||
{
|
||||
"id": "790effa7-630f-4267-a52d-63b6064a46e5",
|
||||
"text": "synthetic-3",
|
||||
"created_at": "2026-01-01T00:00:00.000003+00:00"
|
||||
}
|
||||
]
|
||||
},
|
||||
"target": "separate PostgreSQL container and persistent volume"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/vp-lab2-medvedev-api-1 06afbbee0d3d75fda9d8bf9cd758def600bb6f262ffbb88e6aef9ccb581994bf 2026-11-12T13:54:34.77510721Z
|
||||
/vp-lab2-medvedev-postgres-1 a815eb658f9574c1f6dc47abdcedc2f787d482b6eeeccafa34c87df7eba85f2f 2026-11-12T13:54:35.92974373Z
|
||||
/vp-lab2-medvedev-valkey-1 61b640ca1ecb35d30407958b3879319b2f3bb09042ef601964a76fd822c3850c 2026-11-12T13:54:35.121257658Z
|
||||
@@ -0,0 +1,3 @@
|
||||
/vp-lab2-medvedev-api-1 06afbbee0d3d75fda9d8bf9cd758def600bb6f262ffbb88e6aef9ccb581994bf 2026-11-12T13:54:29.846552448Z
|
||||
/vp-lab2-medvedev-postgres-1 a815eb658f9574c1f6dc47abdcedc2f787d482b6eeeccafa34c87df7eba85f2f 2026-11-12T13:54:20.396967218Z
|
||||
/vp-lab2-medvedev-valkey-1 61b640ca1ecb35d30407958b3879319b2f3bb09042ef601964a76fd822c3850c 2026-11-12T13:54:17.113781258Z
|
||||
@@ -0,0 +1,2 @@
|
||||
/mnt/data/home/bench-saves/vp-labs-vuIKezo9/lab2/.venv/bin/python tests/smoke.py --base-url "http://127.0.0.1:28202"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,2 @@
|
||||
/mnt/data/home/bench-saves/vp-labs-vuIKezo9/lab2/.venv/bin/python scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
@@ -0,0 +1,18 @@
|
||||
Requirement already satisfied: openapi-spec-validator==0.7.2 in ./.venv/lib/python3.14/site-packages (from -r requirements-dev.txt (line 2)) (0.7.2)
|
||||
Requirement already satisfied: jsonschema<5.0.0,>=4.18.0 in ./.venv/lib/python3.14/site-packages (from openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (4.26.0)
|
||||
Requirement already satisfied: jsonschema-path<0.4.0,>=0.3.1 in ./.venv/lib/python3.14/site-packages (from openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (0.3.4)
|
||||
Requirement already satisfied: lazy-object-proxy<2.0.0,>=1.7.1 in ./.venv/lib/python3.14/site-packages (from openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (1.13.0)
|
||||
Requirement already satisfied: openapi-schema-validator<0.7.0,>=0.6.0 in ./.venv/lib/python3.14/site-packages (from openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (0.6.3)
|
||||
Requirement already satisfied: attrs>=22.2.0 in ./.venv/lib/python3.14/site-packages (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (26.1.0)
|
||||
Requirement already satisfied: jsonschema-specifications>=2023.03.6 in ./.venv/lib/python3.14/site-packages (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (2025.9.1)
|
||||
Requirement already satisfied: referencing>=0.28.4 in ./.venv/lib/python3.14/site-packages (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (0.36.2)
|
||||
Requirement already satisfied: rpds-py>=0.25.0 in ./.venv/lib/python3.14/site-packages (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (2026.9.1)
|
||||
Requirement already satisfied: PyYAML>=5.1 in ./.venv/lib/python3.14/site-packages (from jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (6.0.3)
|
||||
Requirement already satisfied: pathable<0.5.0,>=0.4.1 in ./.venv/lib/python3.14/site-packages (from jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (0.4.4)
|
||||
Requirement already satisfied: requests<3.0.0,>=2.31.0 in ./.venv/lib/python3.14/site-packages (from jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (2.34.2)
|
||||
Requirement already satisfied: rfc3339-validator in ./.venv/lib/python3.14/site-packages (from openapi-schema-validator<0.7.0,>=0.6.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (0.1.4)
|
||||
Requirement already satisfied: charset_normalizer<4,>=2 in ./.venv/lib/python3.14/site-packages (from requests<3.0.0,>=2.31.0->jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (3.5.2)
|
||||
Requirement already satisfied: idna<4,>=2.5 in ./.venv/lib/python3.14/site-packages (from requests<3.0.0,>=2.31.0->jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (3.20)
|
||||
Requirement already satisfied: urllib3<3,>=1.26 in ./.venv/lib/python3.14/site-packages (from requests<3.0.0,>=2.31.0->jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (2.8.0)
|
||||
Requirement already satisfied: certifi>=2023.5.7 in ./.venv/lib/python3.14/site-packages (from requests<3.0.0,>=2.31.0->jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (2026.10.23)
|
||||
Requirement already satisfied: six in ./.venv/lib/python3.14/site-packages (from rfc3339-validator->openapi-schema-validator<0.7.0,>=0.6.0->openapi-spec-validator==0.7.2->-r requirements-dev.txt (line 2)) (1.17.0)
|
||||
@@ -0,0 +1,22 @@
|
||||
import { mkdir, writeFile, chmod, access } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const root = resolve(import.meta.dir, '..');
|
||||
const local = resolve(root, '.local');
|
||||
const files = ['pg_password', 'database_url', 'cache_url', 'valkey.conf'];
|
||||
const present = await Promise.all(files.map(async name => {try {await access(resolve(local, name));return true;} catch {return false;}}));
|
||||
if (present.some(Boolean)) {
|
||||
if (!present.every(Boolean)) throw new Error('Incomplete local configuration; preserve it and investigate before bootstrap');
|
||||
console.log('Local configuration exists');
|
||||
} else {
|
||||
await mkdir(local, { recursive: true, mode: 0o700 });
|
||||
const pg = crypto.randomUUID().replaceAll('-', '') + crypto.randomUUID().replaceAll('-', '');
|
||||
const cache = crypto.randomUUID().replaceAll('-', '');
|
||||
const values = [pg, `postgres://messenger:${pg}@postgres:5432/messenger?sslmode=disable`, `redis://:${cache}@valkey:6379/0`, `bind 0.0.0.0\nprotected-mode yes\nrequirepass ${cache}\nappendonly yes\nappendfsync always\ndir /data\n`];
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const destination = resolve(local, files[i]);
|
||||
await writeFile(destination, values[i] + '\n', { mode: 0o600, flag: 'wx' });
|
||||
await chmod(destination, 0o644); // Compose secrets must be readable by nonroot containers; parent is 0700.
|
||||
}
|
||||
console.log('Created local synthetic stand credentials');
|
||||
}
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
exec docker compose --project-directory "$ROOT" -f "$ROOT/compose.yaml" -p vp-lab2-medvedev "$@"
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
ids=(); while IFS= read -r id; do ids+=("$id"); done < <(./scripts/compose.sh ps -q postgres valkey api)
|
||||
test "${#ids[@]}" -eq 3
|
||||
docker inspect --format '{{.Name}} {{.Id}} {{.State.StartedAt}}' "${ids[@]}" >evidence/restart-before.txt
|
||||
./scripts/compose.sh restart postgres valkey api
|
||||
docker inspect --format '{{.Name}} {{.Id}} {{.State.StartedAt}}' "${ids[@]}" >evidence/restart-after.txt
|
||||
@@ -0,0 +1,126 @@
|
||||
import { resolve } from 'node:path';
|
||||
const root = resolve(import.meta.dir, '..');
|
||||
const lab = (await Bun.file(resolve(root, 'lab.json')).json()).number;
|
||||
const base = process.env.BASE_URL ?? 'http://127.0.0.1:28202';
|
||||
const prefix = `st_${crypto.randomUUID().replaceAll('-', '').slice(0, 16)}`;
|
||||
let assertions = 0;
|
||||
function check(value: unknown, message: string): asserts value { if (!value) throw new Error(message); assertions++; }
|
||||
async function call(method: string, path: string, status: number, token?: string, body?: unknown, headers: Record<string, string> = {}) {
|
||||
const response = await fetch(base + path, {method, headers: {...(token ? {Authorization: `Bearer ${token}`} : {}), ...(body !== undefined ? {'Content-Type': 'application/json'} : {}), ...headers}, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(8000)});
|
||||
const bytes = await response.arrayBuffer();
|
||||
let json: any; try {json = JSON.parse(new TextDecoder().decode(bytes));} catch {}
|
||||
check(response.status === status, `${method} ${path}: expected ${status}, got ${response.status}`);
|
||||
check(Boolean(response.headers.get('X-Request-Id')), 'Missing request ID');
|
||||
if (status >= 400) check(json?.error?.request_id === response.headers.get('X-Request-Id'), 'Error request ID mismatch');
|
||||
return {json, response, bytes};
|
||||
}
|
||||
const password = 'synthetic:пароль🙂123';
|
||||
async function user(suffix: string) {
|
||||
const registration = {username: prefix + suffix, display_name: 'Синтетический тест', password};
|
||||
const {json} = await call('POST', '/api/v1/users', 201, undefined, registration);
|
||||
const login = await call('POST', '/api/v1/auth/sessions', 201, undefined, undefined, {Authorization: 'Basic ' + Buffer.from(registration.username + ':' + password).toString('base64')});
|
||||
check(!JSON.stringify(json).includes('password'), 'Password leaked in User');
|
||||
check(typeof login.json.token === 'string' && login.json.token.length >= 43, 'Token entropy/shape');
|
||||
return {id: json.id, token: login.json.token, registration};
|
||||
}
|
||||
async function cleanup() {
|
||||
// No API delete exists. Scope every statement to this run's random username prefix.
|
||||
const sql = `BEGIN;
|
||||
CREATE TEMP TABLE own_users AS SELECT id FROM users WHERE left(username,${prefix.length})='${prefix}';
|
||||
DO $fixture$ BEGIN IF EXISTS(SELECT 1 FROM chat_members mine JOIN chat_members other ON other.chat_id=mine.chat_id WHERE mine.user_id IN(SELECT id FROM own_users) AND other.user_id NOT IN(SELECT id FROM own_users)) THEN RAISE EXCEPTION 'fixture has foreign memberships';END IF;END $fixture$;
|
||||
CREATE TEMP TABLE own_chats AS SELECT DISTINCT mine.chat_id AS id FROM chat_members mine WHERE mine.user_id IN (SELECT id FROM own_users) AND NOT EXISTS(SELECT 1 FROM chat_members other WHERE other.chat_id=mine.chat_id AND other.user_id NOT IN(SELECT id FROM own_users));
|
||||
DELETE FROM messages WHERE sender_id IN (SELECT id FROM own_users);
|
||||
DELETE FROM sessions WHERE user_id IN (SELECT id FROM own_users);
|
||||
DELETE FROM chat_members WHERE chat_id IN (SELECT id FROM own_chats);
|
||||
DELETE FROM chats WHERE id IN (SELECT id FROM own_chats);
|
||||
DELETE FROM users WHERE id IN (SELECT id FROM own_users);
|
||||
COMMIT;`;
|
||||
const p = Bun.spawn([resolve(root,'scripts/compose.sh'), 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1'], {cwd: root, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'});
|
||||
p.stdin.write(sql); p.stdin.end();
|
||||
await new Response(p.stdout).text();
|
||||
const err = await new Response(p.stderr).text();
|
||||
if (await p.exited !== 0) throw new Error('Fixture cleanup failed: ' + err.replace(/password|token/gi, '[redacted]'));
|
||||
}
|
||||
let primary: unknown;
|
||||
try {
|
||||
const alice = await user('a'), bob = await user('b'), eve = await user('e');
|
||||
await call('POST','/api/v1/users',400,undefined,{username:prefix+'x',display_name:'x'});
|
||||
await call('POST','/api/v1/users',400,undefined,{...alice.registration,password:'short'});
|
||||
await call('POST','/api/v1/users',400,undefined,{...alice.registration,extra:1});
|
||||
const race = await Promise.all([0,1].map(async () => {
|
||||
const r = await fetch(base+'/api/v1/users',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...alice.registration,username:prefix+'race'})});
|
||||
await r.arrayBuffer(); return r.status;
|
||||
}));
|
||||
check(race.sort().join(',') === '201,409','Registration race must create exactly one user');
|
||||
const denied = await call('GET','/api/v1/users/me',401,undefined,undefined,{'X-User-Id':alice.id});
|
||||
check(denied.response.headers.get('WWW-Authenticate') === 'Bearer realm="messenger"','Bearer challenge');
|
||||
const wrong = await call('POST','/api/v1/auth/sessions',401,undefined,undefined,{Authorization:'Basic '+Buffer.from(alice.registration.username+':wrong-password').toString('base64')});
|
||||
check(wrong.response.headers.get('WWW-Authenticate') === 'Basic realm="messenger", charset="UTF-8"','Basic challenge');
|
||||
const invalidChat={title:'rollback',member_ids:[alice.id,crypto.randomUUID()]};
|
||||
await call('POST','/api/v1/chats',400,alice.token,invalidChat);
|
||||
let page = (await call('GET','/api/v1/chats',200,alice.token)).json;
|
||||
check(page.items.length === 0 && page.next_cursor === null,'Failed composite create left a chat');
|
||||
const chat = (await call('POST','/api/v1/chats',201,alice.token,{title:'Пагинация',member_ids:[bob.id,alice.id]})).json;
|
||||
const path='/api/v1/chats/'+chat.id+'/messages';
|
||||
check((await call('GET',path,200,alice.token)).json.items.length===0,'Empty page');
|
||||
for (const limit of ['0','-1','101','1.2','abc']) await call('GET',path+'?limit='+limit,400,alice.token);
|
||||
await call('GET',path+'?cursor=%%%',400,alice.token);
|
||||
await call('GET',path,404,eve.token);
|
||||
const sent=[];
|
||||
for(let i=0;i<102;i++) {
|
||||
const h=lab>=3?{'Idempotency-Key':crypto.randomUUID()}:{};
|
||||
sent.push((await call('POST',path,201,alice.token,{text:`Сообщение ${i}`},h)).json);
|
||||
}
|
||||
check((await call('GET',path,200,bob.token)).json.items.length===50,'Default bound');
|
||||
check((await call('GET',path+'?limit=100',200,bob.token)).json.items.length===100,'Maximum bound');
|
||||
const seen=[];let cursor: string|null=null;
|
||||
do {
|
||||
page=(await call('GET',path+'?limit=7'+(cursor?'&cursor='+encodeURIComponent(cursor):''),200,bob.token)).json;
|
||||
check(page.items.length<=7,'Page bound');seen.push(...page.items);cursor=page.next_cursor;
|
||||
}while(cursor);
|
||||
check(JSON.stringify(seen)===JSON.stringify(sent),'Traversal must preserve every item exactly once');
|
||||
const other=(await call('POST','/api/v1/chats',201,alice.token,{title:'Другой',member_ids:[alice.id]})).json;
|
||||
const first=(await call('GET',path+'?limit=1',200,alice.token)).json;
|
||||
await call('GET','/api/v1/chats/'+other.id+'/messages?cursor='+encodeURIComponent(first.next_cursor),400,alice.token);
|
||||
if(lab>=3){
|
||||
const key=crypto.randomUUID(),headers={'Idempotency-Key':key},body={text:'один конкурентный результат'};
|
||||
const results=await Promise.all(Array.from({length:12},()=>call('POST',path,201,alice.token,body,headers)));
|
||||
check(new Set(results.map(r=>r.json.id)).size===1,'Concurrent retries duplicated a message');
|
||||
await call('POST',path,409,alice.token,{text:'другой'},headers);
|
||||
await call('POST',path,400,alice.token,{text:'без ключа'});
|
||||
const ids=new Set<string>();for(let i=0;i<20;i++)ids.add((await call('GET','/api/v1/users/me',200,alice.token)).response.headers.get('X-Instance-Id')!);
|
||||
check(ids.size>=2&&!ids.has(null as any),'One session must reach multiple actual replicas');
|
||||
}
|
||||
await call('DELETE','/api/v1/auth/sessions/current',204,alice.token);
|
||||
await call('GET','/api/v1/users/me',401,alice.token);
|
||||
if(process.env.FAILURES==='1') {
|
||||
async function compose(args:string[], ttl?:string) {
|
||||
const p=Bun.spawn([resolve(root,'scripts/compose.sh'),...args],{cwd:root,env:{...process.env,...(ttl?{SESSION_TTL_SECONDS:ttl}:{})},stdout:'pipe',stderr:'pipe'});
|
||||
await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text()]);
|
||||
check(await p.exited===0,'Compose failure action failed');
|
||||
}
|
||||
async function ready() {for(let i=0;i<150;i++){try{const r=await fetch(base+'/health/ready',{signal:AbortSignal.timeout(1500)});await r.arrayBuffer();if(r.status===200)return;}catch{}await Bun.sleep(100);}throw new Error('Readiness did not recover');}
|
||||
try {
|
||||
await compose(['stop','valkey']);
|
||||
await call('GET','/api/v1/users/me',200,bob.token);
|
||||
await call('GET','/api/v1/users/me',401,undefined,undefined,{'X-User-Id':bob.id});
|
||||
}finally{await compose(['start','valkey']);}
|
||||
try {
|
||||
await compose(['stop','postgres']);
|
||||
await call('GET','/api/v1/users/me',503,bob.token);
|
||||
await call('GET','/health/ready',503);
|
||||
await call('GET','/health/live',200);
|
||||
}finally{await compose(['start','postgres']);await ready();}
|
||||
await call('GET','/api/v1/users/me',200,bob.token);
|
||||
if(lab===2){try {
|
||||
await compose(['up','-d','--no-deps','--force-recreate','api'],'2');await ready();
|
||||
const short=await user('ttl');
|
||||
await call('GET','/api/v1/users/me',200,short.token);
|
||||
await Bun.sleep(2200);
|
||||
await call('GET','/api/v1/users/me',401,short.token);
|
||||
}finally{await compose(['up','-d','--no-deps','--force-recreate','api'],'3600');await ready();}}
|
||||
}
|
||||
} catch(error) { primary=error; }
|
||||
try {await cleanup();} catch(error) {console.error(String(error));if(!primary)primary=error;}
|
||||
if(primary)throw primary;
|
||||
console.log(`PASS lab${lab}: ${assertions} HTTP assertions, registration race, rollback, pagination, authentication${lab>=3?', concurrent idempotency and replica sharing':''}; fixture cleanup completed`);
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Plot measured coursework results; this is data analysis, not application code."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from statistics import mean
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('summary', type=Path)
|
||||
parser.add_argument('--pool-summary', type=Path)
|
||||
args = parser.parse_args()
|
||||
data = json.loads(args.summary.read_text())
|
||||
if data.get('complete') is not True:
|
||||
raise SystemExit('Only a completed, cleaned-up run can be plotted')
|
||||
plt.rcParams.update({'svg.fonttype': 'none', 'font.size': 10})
|
||||
|
||||
if 'dataset' in data:
|
||||
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5), constrained_layout=True)
|
||||
modes = ['chat_only', 'history']
|
||||
for axis, key, title in zip(axes, ['read', 'write'], ['Deep history page (51 rows)', 'Insert 1,000 messages']):
|
||||
values = [data['plans'][mode][key]['Execution Time'] for mode in modes]
|
||||
axis.bar(['chat_id', 'chat_id + time + id'], values, color=['#6b7280', '#2563eb'])
|
||||
axis.set_ylabel('Execution time, ms')
|
||||
axis.set_title(title)
|
||||
if key == 'read':
|
||||
axis.set_yscale('log')
|
||||
for index, value in enumerate(values):
|
||||
axis.annotate(f'{value:.3f}', (index, value), xytext=(0, 4), textcoords='offset points', ha='center')
|
||||
fig.suptitle('100,000 skewed messages; one EXPLAIN ANALYZE per index')
|
||||
fig.savefig(args.summary.parent / 'comparison.svg')
|
||||
plt.close(fig)
|
||||
else:
|
||||
if data.get('valid') is not True:
|
||||
raise SystemExit('Invalid measurements')
|
||||
rows = data['samples']
|
||||
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), constrained_layout=True)
|
||||
for phase, label, color in [('fixed', 'Fixed total API CPU/RAM', '#2563eb'), ('growing', 'Resources grow with replicas', '#c2410c')]:
|
||||
groups = [[r for r in rows if r['phase'] == phase and r['replicas'] == count] for count in [1, 2, 4]]
|
||||
if not all(groups):
|
||||
continue
|
||||
for axis, metric in zip(axes, ['rps', 'p95']):
|
||||
values = [[r['metrics']['successful_rps'] if metric == 'rps' else r['metrics']['successful_latency_ms']['p95'] for r in group] for group in groups]
|
||||
centers = [mean(value) for value in values]
|
||||
errors = [[center - min(value) for center, value in zip(centers, values)], [max(value) - center for center, value in zip(centers, values)]]
|
||||
axis.errorbar([1, 2, 4], centers, yerr=errors, marker='o', capsize=4, label=label, color=color)
|
||||
for axis, title in zip(axes, ['Successful requests / second', 'p95 of successful requests, ms']):
|
||||
axis.set_title(title)
|
||||
axis.set_xlabel('API replicas')
|
||||
axis.set_xticks([1, 2, 4])
|
||||
axis.grid(alpha=.2)
|
||||
axis.legend(fontsize=8)
|
||||
fig.suptitle('Closed loop, concurrency 16, 5 seconds; mean and range of two runs')
|
||||
fig.savefig(args.summary.parent / 'scaling.svg')
|
||||
plt.close(fig)
|
||||
pool_data = json.loads(args.pool_summary.read_text()) if args.pool_summary else data
|
||||
if pool_data.get('complete') is not True:
|
||||
raise SystemExit('Incomplete pool experiment')
|
||||
pools = [[r for r in pool_data['samples'] if r['phase'] == 'pool' and r['pool'] == size] for size in [8, 1]]
|
||||
fig, axes = plt.subplots(1, 2, figsize=(8, 3.5), constrained_layout=True)
|
||||
for axis, metric in zip(axes, ['rps', 'p95']):
|
||||
values = [[r['metrics']['successful_rps'] if metric == 'rps' else r['metrics']['successful_latency_ms']['p95'] for r in group] for group in pools]
|
||||
centers = [mean(value) for value in values]
|
||||
axis.bar(['pool = 8', 'pool = 1'], centers, color=['#6b7280', '#2563eb'])
|
||||
axis.set_ylabel('Successful req/s' if metric == 'rps' else 'p95, ms')
|
||||
axis.set_ylim(bottom=0)
|
||||
for index, center in enumerate(centers):
|
||||
axis.annotate(f'{center:.2f}', (index, center), xytext=(0, 4), textcoords='offset points', ha='center')
|
||||
fig.suptitle('One hot sender; same single-replica CPU/RAM budget')
|
||||
fig.savefig(args.summary.parent / 'pool.svg')
|
||||
plt.close(fig)
|
||||
print('Saved standalone SVG research figures')
|
||||
@@ -0,0 +1 @@
|
||||
matplotlib==3.11.2
|
||||
@@ -0,0 +1,77 @@
|
||||
import {resolve} from 'node:path';
|
||||
import {mkdir,mkdtemp,writeFile,chmod} from 'node:fs/promises';
|
||||
const root=resolve(import.meta.dir,'..');
|
||||
if(process.argv.includes('--check')){console.log('Research script parsed without accessing the stand');process.exit(0);}
|
||||
let stage='preflight';
|
||||
async function command(args:string[],input?:string|Uint8Array){
|
||||
const p=Bun.spawn(args,{cwd:root,stdin:input===undefined?'ignore':'pipe',stdout:'pipe',stderr:'pipe',signal:AbortSignal.timeout(120000)});
|
||||
if(input!==undefined){p.stdin.write(input);p.stdin.end();}
|
||||
const [out,err]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text()]);
|
||||
if(await p.exited!==0)throw new Error(`${stage}: command rejected (${args[0]})`);
|
||||
return out;
|
||||
}
|
||||
async function guard(){const p=Bun.spawn(['game-running'],{stdout:'ignore',stderr:'pipe'});await new Response(p.stderr).text();if(await p.exited!==1)throw new Error('Research requires a verified inactive game');}
|
||||
async function sql(query:string,service='postgres',database='messenger'){return await command([resolve(root,'scripts/compose.sh'),'exec','-T',service,'psql','-X','-qAt','-U','messenger','-d',database,'-v','ON_ERROR_STOP=1'],query);}
|
||||
const nonce=crypto.randomUUID().replaceAll('-','').slice(0,12),user=crypto.randomUUID(),chats=[crypto.randomUUID(),crypto.randomUUID(),crypto.randomUUID()];
|
||||
const parent=resolve(root,'evidence/research');await mkdir(parent,{recursive:true});
|
||||
const evidence=await mkdtemp(resolve(parent,'run-'));
|
||||
await writeFile(resolve(evidence,'run.json'),JSON.stringify({run_id:nonce,started_at:new Date().toISOString(),state:'started'})+'\n',{flag:'wx'});
|
||||
const local=resolve(root,'.local');
|
||||
const results:any={dataset:{messages:100000,distribution:[90000,9000,1000]},plans:{},backup:{}};
|
||||
let apiStopped=false,restoreTouched=false,primary:unknown;const cleanupErrors:string[]=[];
|
||||
try{
|
||||
await guard();
|
||||
if(!(await command([resolve(root,'scripts/compose.sh'),'ps','--status','running','-q','api'])).trim())throw new Error('Expected coursework API is not running');
|
||||
stage='stop_api';apiStopped=true;await command([resolve(root,'scripts/compose.sh'),'stop','api']);
|
||||
if((await command([resolve(root,'scripts/compose.sh'),'ps','--status','running','-q','api'])).trim())throw new Error('API did not stop');
|
||||
stage='seed';
|
||||
await sql(`BEGIN;
|
||||
INSERT INTO users(id,username,display_name,password_hash) VALUES('${user}','research_${nonce}','Synthetic research','disabled-no-login');
|
||||
INSERT INTO chats(id,title) VALUES ${chats.map((id,i)=>`('${id}','Synthetic ${i}')`).join(',')};
|
||||
INSERT INTO chat_members(chat_id,user_id) VALUES ${chats.map(id=>`('${id}','${user}')`).join(',')};
|
||||
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT gen_random_uuid(),CASE WHEN i<=90000 THEN '${chats[0]}'::uuid WHEN i<=99000 THEN '${chats[1]}'::uuid ELSE '${chats[2]}'::uuid END,'${user}','synthetic-'||i,
|
||||
'2026-01-01T00:00:00Z'::timestamptz+i*interval '1 microsecond' FROM generate_series(1,100000) AS i;
|
||||
UPDATE users SET message_count=100000 WHERE id='${user}'; COMMIT; ANALYZE messages;`);
|
||||
const read=`SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id='${chats[0]}' AND (created_at,id)>('2026-01-01T00:00:00.070000Z'::timestamptz,'00000000-0000-0000-0000-000000000000'::uuid) ORDER BY created_at,id LIMIT 51`;
|
||||
for(const mode of ['chat_only','history']){
|
||||
await guard();stage='index_'+mode;
|
||||
if(mode==='chat_only')await sql('DROP INDEX messages_history;CREATE INDEX research_chat_only ON messages(chat_id);ANALYZE messages;');
|
||||
else await sql('DROP INDEX research_chat_only;CREATE INDEX messages_history ON messages(chat_id,created_at,id);ANALYZE messages;');
|
||||
stage='read_plan_'+mode;
|
||||
const raw=await sql('EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) '+read+';');
|
||||
await writeFile(resolve(evidence,mode+'-read.json'),raw);results.plans[mode]={read:JSON.parse(raw)[0]};
|
||||
stage='write_plan_'+mode;
|
||||
const rawWrite=await sql(`EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) INSERT INTO messages(id,chat_id,sender_id,text) SELECT gen_random_uuid(),'${chats[0]}','${user}','write-cost-'||i FROM generate_series(1,1000) i;`);
|
||||
await writeFile(resolve(evidence,mode+'-write.json'),rawWrite);results.plans[mode].write=JSON.parse(rawWrite)[0];
|
||||
}
|
||||
stage='fingerprint';
|
||||
const fingerprint=`SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'members',(SELECT count(*) FROM chat_members),'messages',(SELECT count(*) FROM messages),'research_messages',(SELECT count(*) FROM messages WHERE sender_id='${user}'),'samples',(SELECT json_agg(t) FROM (SELECT id,text,created_at FROM messages WHERE sender_id='${user}' ORDER BY created_at,id LIMIT 3) t))::text;`;
|
||||
const before=JSON.parse(await sql(fingerprint));
|
||||
stage='backup';await guard();const dumpStart=performance.now();
|
||||
const dump=Bun.spawn([resolve(root,'scripts/compose.sh'),'exec','-T','postgres','pg_dump','-U','messenger','-d','messenger','-Fc','--no-owner','--no-acl'],{cwd:root,stdout:'pipe',stderr:'pipe'});
|
||||
const dumpFile=resolve(local,'research-backup-'+nonce+'.dump');await Bun.write(dumpFile,new Response(dump.stdout));await new Response(dump.stderr).text();if(await dump.exited!==0)throw new Error('Backup rejected');await chmod(dumpFile,0o600);
|
||||
results.backup.dump_seconds=(performance.now()-dumpStart)/1000;results.backup.bytes=Bun.file(dumpFile).size;
|
||||
stage='restore_start';restoreTouched=true;await command([resolve(root,'scripts/compose.sh'),'up','-d','--wait','restore']);
|
||||
const database='recovery_'+nonce;await sql('CREATE DATABASE '+database,'restore','restore');
|
||||
stage='restore';const restoreStart=performance.now();
|
||||
const restore=Bun.spawn([resolve(root,'scripts/compose.sh'),'exec','-T','restore','pg_restore','-U','messenger','-d',database,'--no-owner','--no-acl','--exit-on-error'],{cwd:root,stdin:Bun.file(dumpFile),stdout:'pipe',stderr:'pipe'});
|
||||
await Promise.all([new Response(restore.stdout).text(),new Response(restore.stderr).text()]);if(await restore.exited!==0)throw new Error('Restore rejected');
|
||||
results.backup.restore_seconds=(performance.now()-restoreStart)/1000;
|
||||
const after=JSON.parse(await sql(fingerprint,'restore',database));
|
||||
if(JSON.stringify(before)!==JSON.stringify(after))throw new Error('Restored row counts or sampled messages differ');
|
||||
results.backup.verified=before;results.backup.target='separate PostgreSQL container and persistent volume';
|
||||
await sql('DROP DATABASE '+database,'restore','restore');
|
||||
await guard();stage='measured';
|
||||
}catch(error){primary=error;}
|
||||
finally{
|
||||
if(apiStopped)try{
|
||||
await sql('DROP INDEX IF EXISTS research_chat_only;CREATE INDEX IF NOT EXISTS messages_history ON messages(chat_id,created_at,id);');
|
||||
await sql(`BEGIN;DELETE FROM messages WHERE sender_id='${user}';DELETE FROM chat_members WHERE user_id='${user}';DELETE FROM chats WHERE id=ANY(ARRAY[${chats.map(id=>`'${id}'::uuid`).join(',')}]);DELETE FROM users WHERE id='${user}';COMMIT;`);
|
||||
}catch{cleanupErrors.push('source_data_or_index');}
|
||||
if(restoreTouched)try{await sql('DROP DATABASE IF EXISTS recovery_'+nonce,'restore','restore');await command([resolve(root,'scripts/compose.sh'),'stop','restore']);}catch{cleanupErrors.push('restore_database');}
|
||||
if(apiStopped)try{await command([resolve(root,'scripts/compose.sh'),'start','api']);await command([process.execPath,'--no-env-file','student-tests/wait.ts']);}catch{cleanupErrors.push('api_recovery');}
|
||||
}
|
||||
if(primary||cleanupErrors.length){await writeFile(resolve(evidence,'failure.json'),JSON.stringify({run_id:nonce,stage,primary:primary instanceof Error?primary.name:primary?'unknown':null,cleanup_errors:cleanupErrors})+'\n');throw new Error('Research failed; inspect this run failure summary');}
|
||||
await writeFile(resolve(evidence,'summary.json'),JSON.stringify({run_id:nonce,complete:true,...results},null,2)+'\n',{flag:'wx'});
|
||||
console.log('PASS lab2 research: '+evidence);
|
||||
@@ -0,0 +1,14 @@
|
||||
import {resolve} from 'node:path';
|
||||
const root=resolve(import.meta.dir,'..');
|
||||
const lab=(await Bun.file(resolve(root,'lab.json')).json()).number;
|
||||
const base=process.env.BASE_URL??`http://127.0.0.1:${28200+lab}`;
|
||||
const needed=lab>=3?Number(process.env.API_REPLICAS??2):1;
|
||||
const instances=new Set<string>();
|
||||
for(let attempt=0;attempt<600;attempt++){
|
||||
try{
|
||||
const r=await fetch(base+'/health/ready',{signal:AbortSignal.timeout(1000)});await r.arrayBuffer();
|
||||
if(r.status===200){instances.add(r.headers.get('X-Instance-Id')??'single');if(instances.size>=needed){console.log(`Ready: ${instances.size} API process(es)`);process.exit(0);}}
|
||||
}catch{}
|
||||
await Bun.sleep(150);
|
||||
}
|
||||
throw new Error('Stand readiness deadline expired');
|
||||
Reference in New Issue
Block a user