From 1503b5db819eaa1cdd24fcc91dc38265d8cd1098 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D1=83=D1=80=D0=BB=D1=8B=D0=B3=D0=B0=D1=8F=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=20=D0=95=D0=BA=D0=B0=D1=82=D0=B5=D1=80=D0=B8?= =?UTF-8?q?=D0=BD=D0=B0?= Date: Thu, 29 Oct 2026 11:29:38 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=A0=202:=20PostgreSQL,=20=D1=81=D0=B5?= =?UTF-8?q?=D1=81=D1=81=D0=B8=D0=B8=20=D0=B2=20Valkey,=20=D0=BA=D1=8D?= =?UTF-8?q?=D1=88=20=D0=B8=D1=81=D1=82=D0=BE=D1=80=D0=B8=D0=B8=20(=D1=82?= =?UTF-8?q?=D1=80=D0=B5=D0=BA=201)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 1 + .env.example | 14 +- .gitignore | 3 +- Dockerfile | 53 ++ REPORT.md | 150 ++++- app/cmd/cachebench/main.go | 595 ++++++++++++++++++ app/cmd/messenger/main.go | 132 ++++ app/e2e/failures_test.go | 329 ++++++++++ app/go.mod | 28 + app/go.sum | 56 ++ app/internal/api/http/access_test.go | 115 ++++ app/internal/api/http/auth.go | 70 +++ app/internal/api/http/auth_test.go | 217 +++++++ app/internal/api/http/chats.go | 103 +++ app/internal/api/http/concurrency_test.go | 84 +++ app/internal/api/http/dto/chat.go | 20 + app/internal/api/http/dto/message.go | 20 + app/internal/api/http/dto/user.go | 23 + app/internal/api/http/errors.go | 76 +++ app/internal/api/http/health.go | 24 + app/internal/api/http/helpers_test.go | 328 ++++++++++ app/internal/api/http/limits_test.go | 312 +++++++++ app/internal/api/http/messages.go | 71 +++ app/internal/api/http/middleware/auth.go | 62 ++ .../api/http/middleware/content_type.go | 42 ++ app/internal/api/http/middleware/limits.go | 110 ++++ app/internal/api/http/middleware/logger.go | 48 ++ app/internal/api/http/middleware/recover.go | 32 + .../api/http/middleware/request_id.go | 22 + app/internal/api/http/pagination_test.go | 89 +++ app/internal/api/http/router.go | 32 + app/internal/api/http/server.go | 165 +++++ app/internal/api/http/users.go | 114 ++++ app/internal/api/http/validation_test.go | 225 +++++++ app/internal/cache/history.go | 396 ++++++++++++ app/internal/cache/history_test.go | 266 ++++++++ app/internal/config/config.go | 146 +++++ app/internal/config/database.go | 9 + app/internal/config/env.go | 121 ++++ app/internal/config/env_test.go | 63 ++ app/internal/config/history_cache.go | 11 + app/internal/config/http.go | 9 + app/internal/config/limits.go | 8 + app/internal/config/logger.go | 5 + app/internal/config/session.go | 13 + app/internal/domain/chat.go | 10 + app/internal/domain/errors.go | 19 + app/internal/domain/message.go | 11 + app/internal/domain/page.go | 55 ++ app/internal/domain/session.go | 9 + app/internal/domain/user.go | 10 + app/internal/logging/logging.go | 51 ++ app/internal/password/password.go | 113 ++++ app/internal/password/password_test.go | 76 +++ app/internal/service/auth.go | 101 +++ app/internal/service/chats.go | 47 ++ app/internal/service/messages.go | 43 ++ app/internal/service/service.go | 29 + app/internal/service/users.go | 44 ++ app/internal/session/memory.go | 49 ++ app/internal/session/session.go | 21 + app/internal/session/valkey.go | 120 ++++ app/internal/store/db/chats.go | 163 +++++ app/internal/store/db/db.go | 132 ++++ app/internal/store/db/db_test.go | 46 ++ app/internal/store/db/integration_test.go | 130 ++++ app/internal/store/db/messages.go | 129 ++++ app/internal/store/db/users.go | 87 +++ app/internal/store/memory.go | 311 +++++++++ app/internal/store/store.go | 32 + app/internal/token/token.go | 43 ++ app/internal/token/token_test.go | 65 ++ app/internal/validate/chat.go | 42 ++ app/internal/validate/message.go | 13 + app/internal/validate/rules.go | 87 +++ app/internal/validate/user.go | 30 + compose.yaml | 148 +++++ evidence/checks.txt | 17 + evidence/explain.txt | 131 ++++ evidence/failures.txt | 38 ++ evidence/integration-tests.txt | 34 + evidence/migrations.txt | 34 + evidence/persistence.txt | 17 + evidence/track1/env.txt | 11 + evidence/track1/naive-d0-r1.json | 351 +++++++++++ evidence/track1/naive-d0-r1.stats.txt | 64 ++ evidence/track1/naive-d0-r2.json | 351 +++++++++++ evidence/track1/naive-d0-r2.stats.txt | 63 ++ evidence/track1/naive-d0-r3.json | 351 +++++++++++ evidence/track1/naive-d0-r3.stats.txt | 59 ++ evidence/track1/naive-d20-r1.json | 341 ++++++++++ evidence/track1/naive-d20-r1.stats.txt | 59 ++ evidence/track1/naive-d20-r2.json | 351 +++++++++++ evidence/track1/naive-d20-r2.stats.txt | 90 +++ evidence/track1/naive-d20-r3.json | 341 ++++++++++ evidence/track1/naive-d20-r3.stats.txt | 83 +++ evidence/track1/off-d0-r1.json | 351 +++++++++++ evidence/track1/off-d0-r1.stats.txt | 59 ++ evidence/track1/off-d0-r2.json | 341 ++++++++++ evidence/track1/off-d0-r2.stats.txt | 59 ++ evidence/track1/off-d0-r3.json | 341 ++++++++++ evidence/track1/off-d0-r3.stats.txt | 59 ++ evidence/track1/safe-d0-r1.json | 341 ++++++++++ evidence/track1/safe-d0-r1.stats.txt | 84 +++ evidence/track1/safe-d0-r2.json | 341 ++++++++++ evidence/track1/safe-d0-r2.stats.txt | 90 +++ evidence/track1/safe-d0-r3.json | 341 ++++++++++ evidence/track1/safe-d0-r3.stats.txt | 84 +++ evidence/track1/safe-d20-r1.json | 341 ++++++++++ evidence/track1/safe-d20-r1.stats.txt | 89 +++ evidence/track1/safe-d20-r2.json | 341 ++++++++++ evidence/track1/safe-d20-r2.stats.txt | 84 +++ evidence/track1/safe-d20-r3.json | 351 +++++++++++ evidence/track1/safe-d20-r3.stats.txt | 83 +++ evidence/track1/safe-pause.json | 341 ++++++++++ evidence/track1/safe-pause.stats.txt | 84 +++ evidence/track1/safe-restart.json | 351 +++++++++++ evidence/track1/safe-restart.stats.txt | 81 +++ evidence/track1/summary.md | 112 ++++ migrations/00001_create_users_table.sql | 22 + migrations/00002_create_chats_table.sql | 16 + .../00003_create_chat_members_table.sql | 16 + migrations/00004_create_messages_table.sql | 25 + scripts/explain.sh | 106 ++++ scripts/failures-tests.sh | 8 + scripts/init-secrets.sh | 48 ++ scripts/integration-tests.sh | 14 + scripts/migrations-check.sh | 31 + scripts/persistence-evidence.sh | 34 + scripts/restart.sh | 10 + scripts/track1.sh | 87 +++ scripts/track1_summary.py | 104 +++ 132 files changed, 15114 insertions(+), 20 deletions(-) create mode 100644 Dockerfile create mode 100644 app/cmd/cachebench/main.go create mode 100644 app/cmd/messenger/main.go create mode 100644 app/e2e/failures_test.go create mode 100644 app/go.mod create mode 100644 app/go.sum create mode 100644 app/internal/api/http/access_test.go create mode 100644 app/internal/api/http/auth.go create mode 100644 app/internal/api/http/auth_test.go create mode 100644 app/internal/api/http/chats.go create mode 100644 app/internal/api/http/concurrency_test.go create mode 100644 app/internal/api/http/dto/chat.go create mode 100644 app/internal/api/http/dto/message.go create mode 100644 app/internal/api/http/dto/user.go create mode 100644 app/internal/api/http/errors.go create mode 100644 app/internal/api/http/health.go create mode 100644 app/internal/api/http/helpers_test.go create mode 100644 app/internal/api/http/limits_test.go create mode 100644 app/internal/api/http/messages.go create mode 100644 app/internal/api/http/middleware/auth.go create mode 100644 app/internal/api/http/middleware/content_type.go create mode 100644 app/internal/api/http/middleware/limits.go create mode 100644 app/internal/api/http/middleware/logger.go create mode 100644 app/internal/api/http/middleware/recover.go create mode 100644 app/internal/api/http/middleware/request_id.go create mode 100644 app/internal/api/http/pagination_test.go create mode 100644 app/internal/api/http/router.go create mode 100644 app/internal/api/http/server.go create mode 100644 app/internal/api/http/users.go create mode 100644 app/internal/api/http/validation_test.go create mode 100644 app/internal/cache/history.go create mode 100644 app/internal/cache/history_test.go create mode 100644 app/internal/config/config.go create mode 100644 app/internal/config/database.go create mode 100644 app/internal/config/env.go create mode 100644 app/internal/config/env_test.go create mode 100644 app/internal/config/history_cache.go create mode 100644 app/internal/config/http.go create mode 100644 app/internal/config/limits.go create mode 100644 app/internal/config/logger.go create mode 100644 app/internal/config/session.go create mode 100644 app/internal/domain/chat.go create mode 100644 app/internal/domain/errors.go create mode 100644 app/internal/domain/message.go create mode 100644 app/internal/domain/page.go create mode 100644 app/internal/domain/session.go create mode 100644 app/internal/domain/user.go create mode 100644 app/internal/logging/logging.go create mode 100644 app/internal/password/password.go create mode 100644 app/internal/password/password_test.go create mode 100644 app/internal/service/auth.go create mode 100644 app/internal/service/chats.go create mode 100644 app/internal/service/messages.go create mode 100644 app/internal/service/service.go create mode 100644 app/internal/service/users.go create mode 100644 app/internal/session/memory.go create mode 100644 app/internal/session/session.go create mode 100644 app/internal/session/valkey.go create mode 100644 app/internal/store/db/chats.go create mode 100644 app/internal/store/db/db.go create mode 100644 app/internal/store/db/db_test.go create mode 100644 app/internal/store/db/integration_test.go create mode 100644 app/internal/store/db/messages.go create mode 100644 app/internal/store/db/users.go create mode 100644 app/internal/store/memory.go create mode 100644 app/internal/store/store.go create mode 100644 app/internal/token/token.go create mode 100644 app/internal/token/token_test.go create mode 100644 app/internal/validate/chat.go create mode 100644 app/internal/validate/message.go create mode 100644 app/internal/validate/rules.go create mode 100644 app/internal/validate/user.go create mode 100644 compose.yaml create mode 100644 evidence/checks.txt create mode 100644 evidence/explain.txt create mode 100644 evidence/failures.txt create mode 100644 evidence/integration-tests.txt create mode 100644 evidence/migrations.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/track1/env.txt create mode 100644 evidence/track1/naive-d0-r1.json create mode 100644 evidence/track1/naive-d0-r1.stats.txt create mode 100644 evidence/track1/naive-d0-r2.json create mode 100644 evidence/track1/naive-d0-r2.stats.txt create mode 100644 evidence/track1/naive-d0-r3.json create mode 100644 evidence/track1/naive-d0-r3.stats.txt create mode 100644 evidence/track1/naive-d20-r1.json create mode 100644 evidence/track1/naive-d20-r1.stats.txt create mode 100644 evidence/track1/naive-d20-r2.json create mode 100644 evidence/track1/naive-d20-r2.stats.txt create mode 100644 evidence/track1/naive-d20-r3.json create mode 100644 evidence/track1/naive-d20-r3.stats.txt create mode 100644 evidence/track1/off-d0-r1.json create mode 100644 evidence/track1/off-d0-r1.stats.txt create mode 100644 evidence/track1/off-d0-r2.json create mode 100644 evidence/track1/off-d0-r2.stats.txt create mode 100644 evidence/track1/off-d0-r3.json create mode 100644 evidence/track1/off-d0-r3.stats.txt create mode 100644 evidence/track1/safe-d0-r1.json create mode 100644 evidence/track1/safe-d0-r1.stats.txt create mode 100644 evidence/track1/safe-d0-r2.json create mode 100644 evidence/track1/safe-d0-r2.stats.txt create mode 100644 evidence/track1/safe-d0-r3.json create mode 100644 evidence/track1/safe-d0-r3.stats.txt create mode 100644 evidence/track1/safe-d20-r1.json create mode 100644 evidence/track1/safe-d20-r1.stats.txt create mode 100644 evidence/track1/safe-d20-r2.json create mode 100644 evidence/track1/safe-d20-r2.stats.txt create mode 100644 evidence/track1/safe-d20-r3.json create mode 100644 evidence/track1/safe-d20-r3.stats.txt create mode 100644 evidence/track1/safe-pause.json create mode 100644 evidence/track1/safe-pause.stats.txt create mode 100644 evidence/track1/safe-restart.json create mode 100644 evidence/track1/safe-restart.stats.txt create mode 100644 evidence/track1/summary.md create mode 100644 migrations/00001_create_users_table.sql create mode 100644 migrations/00002_create_chats_table.sql create mode 100644 migrations/00003_create_chat_members_table.sql create mode 100644 migrations/00004_create_messages_table.sql create mode 100644 scripts/explain.sh create mode 100644 scripts/failures-tests.sh create mode 100644 scripts/init-secrets.sh create mode 100644 scripts/integration-tests.sh create mode 100644 scripts/migrations-check.sh create mode 100644 scripts/persistence-evidence.sh create mode 100755 scripts/restart.sh create mode 100644 scripts/track1.sh create mode 100644 scripts/track1_summary.py diff --git a/.dockerignore b/.dockerignore index bc16e55..2b710ee 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,4 @@ __pycache__ node_modules evidence .DS_Store +app/messenger diff --git a/.env.example b/.env.example index 714c807..2b0f93b 100644 --- a/.env.example +++ b/.env.example @@ -7,5 +7,17 @@ SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url # Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres +SESSION_STORE=valkey CACHE_URL_FILE=/run/secrets/cache_url +# Host port for the API (inside the container it is always APP_PORT=8080). +API_PUBLISH_PORT=8080 +# Secrets live in ./secrets (gitignored); create them with ./scripts/init-secrets.sh +# Хост-порты только на 127.0.0.1 (psql/EXPLAIN и интеграционные тесты); по умолчанию 5432/6379/6380. +#POSTGRES_PORT=5432 +#VALKEY_PORT=6379 +#VALKEY_CACHE_PORT=6380 +# Кэш истории (трек 1), отдельный Valkey valkey-cache: off | naive | safe (naive — только для эксперимента). +HISTORY_CACHE=safe +HISTORY_CACHE_TTL_SECONDS=30 +# Fault injection для эксперимента: пауза между чтением БД и записью в кэш. В работе 0. +HISTORY_CACHE_FILL_DELAY_MS=0 diff --git a/.gitignore b/.gitignore index b5a7189..2b7b04b 100644 --- a/.gitignore +++ b/.gitignore @@ -28,5 +28,4 @@ coverage/ .DS_Store .idea/ .vscode/ -# Keep small, sanitized evidence summaries in evidence/ under version control. -# Inspect git diff --cached: ignore rules are not a secret scanner. +/app/messenger diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5b157a8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,53 @@ +# syntax=docker/dockerfile:1.7 + +FROM golang:1.26.10-alpine3.24 AS builder +WORKDIR /src + +COPY app/go.mod app/go.sum ./ +RUN go mod download + +COPY app/ ./ + +RUN CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w" \ + -trimpath \ + -o /out/messenger ./cmd/messenger + +RUN CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w" \ + -trimpath \ + -o /out/cachebench ./cmd/cachebench + +FROM golang:1.26.10-alpine3.24 AS goose-builder +RUN CGO_ENABLED=0 go install -trimpath -ldflags="-s -w" \ + -tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb' \ + github.com/pressly/goose/v3/cmd/goose@v3.26.0 + +FROM alpine:3.24.3 AS migrate +COPY --from=goose-builder /go/bin/goose /usr/local/bin/goose +COPY migrations /migrations +ENTRYPOINT ["/bin/sh", "-c", "exec goose -dir /migrations postgres \"$(cat \"$DATABASE_URL_FILE\")\" up"] + +FROM alpine:3.24.3 AS cachebench +COPY --from=builder /out/cachebench /usr/local/bin/cachebench +ENTRYPOINT ["/usr/local/bin/cachebench"] + +FROM alpine:3.24.3 + +RUN apk add --no-cache ca-certificates && \ + addgroup -S app && \ + adduser -S -G app -H app + +WORKDIR /app + +COPY --from=builder /out/messenger /app/messenger + +USER app + +EXPOSE 8080 +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD wget --quiet --spider "http://127.0.0.1:${APP_PORT:-8080}/health/ready" || exit 1 + +ENTRYPOINT ["/app/messenger"] diff --git a/REPORT.md b/REPORT.md index e42f2b0..2a0a7e2 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,153 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Нурлыгаянова Екатерина, БП2302 +- Целевая оценка: 5, трек 1 «Согласованность кэша» +- Commit/PR: ветка `solution/bpi2302-nurlygayanova`, базовый commit `65003b6`; хеш итогового commit и ссылка на PR — после публикации +- Библиотеки: `echo/v4` 4.16.2, `pgx/v5` 5.7.6, `go-redis/v9` 9.7.3, `x/crypto/argon2` 0.57.0, `x/sync/singleflight` 0.23.0, `google/uuid` 1.6.0, миграции — `goose` 3.26.0. +- Источники: документация PostgreSQL ([transactions](https://www.postgresql.org/docs/current/tutorial-transactions.html), [EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html), [PREPARE](https://www.postgresql.org/docs/current/sql-prepare.html), [pg_stat_statements](https://www.postgresql.org/docs/current/pgstatstatements.html)), [Valkey persistence](https://valkey.io/topics/persistence/), [Valkey eviction](https://valkey.io/topics/lru-cache/), [RFC 7617](https://www.rfc-editor.org/info/rfc7617/), OWASP Password Storage Cheat Sheet. +- Помощь ИИ: Claude Code (Anthropic) — проверка по рубрике, кэш истории и эксперимент трека 1 (`internal/cache`, `cmd/cachebench`, `scripts/track1*`), тесты, скрипты доказательств, черновик отчёта. Результаты получены реальными прогонами. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Образы: сборка `golang:1.26.10-alpine3.24`, runtime `alpine:3.24.3`, `postgres:17.6-alpine`, `valkey/valkey:8.1.3-alpine` (×2). Нужны Docker + Compose v2.20+, POSIX `sh`, Python 3.9+ (публичные тесты), Go 1.26 (собственные тесты). Лимиты CPU/RAM контейнерам не заданы. + +```sh +sh scripts/init-secrets.sh # secrets/* (в .gitignore); существующие файлы не перезаписывает +cp .env.example .env # при занятом 5432: POSTGRES_PORT=55432 в .env +docker compose --env-file .env up -d --build --wait # migrate (goose) отрабатывает до api +until curl -fsS http://localhost:8080/health/ready >/dev/null; do sleep 1; done + +make check && make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh + +# собственные проверки (против запущенного стенда, данные синтетические) +cd app && go test ./... # unit/HTTP; интеграционные и e2e пропускаются +sh scripts/integration-tests.sh # гонка username, rollback, кэш (PostgreSQL + valkey-cache) +sh scripts/failures-tests.sh # уровень 4: пароль, logout, expiry, отказы → evidence/failures.txt +sh scripts/explain.sh # EXPLAIN → evidence/explain.txt +sh scripts/migrations-check.sh # миграции с нуля и повторно → evidence/migrations.txt +sh scripts/persistence-evidence.sh # persistence + StartedAt до/после → evidence/persistence.txt +REPEATS=3 DURATION=30s sh scripts/track1.sh # трек 1 → evidence/track1/ +``` + + +**Остановка** без потери данных: `docker compose --env-file .env stop` (или `down` — volumes остаются). +**Удаление учебных данных** (необратимо): `docker compose --env-file .env down -v` (volumes `mtusi-lab2_pgdata`, `mtusi-lab2_valkeydata`), `rm -r secrets`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +``` +клиент ─HTTP─▶ api (Go) ─pgx pool≤10─▶ postgres источник истины: users, chats, chat_members, messages (volume pgdata) + ├──────pool≤20─────▶ valkey сессии: AOF everysec, noeviction (volume valkeydata) + └──────pool≤20─────▶ valkey-cache кэш истории: без persistence, allkeys-lru, не критичен +migrate (goose, одноразовый) ─▶ postgres до старта api +``` + +| Service | Health | Volume | Порт | Credentials | +|---|---|---|---|---| +| `api` | `/health/ready` = ping PostgreSQL + Valkey сессий | — | `8080` | secrets `database_url`, `cache_url`, `history_cache_url` | +| `postgres` | `pg_isready` | `pgdata` | `127.0.0.1:5432` | `POSTGRES_PASSWORD_FILE` | +| `valkey` | `valkey-cli ping` | `valkeydata` | `127.0.0.1:6379` | `--requirepass` из secret | +| `valkey-cache` | `valkey-cli ping` (не в readiness) | нет | `127.0.0.1:6380` | `--requirepass` из secret | +| `migrate` | `service_completed_successfully` | — | — | secret `database_url` | + +**Из lab1** перенесены роутер, middleware (request id, recover, логи, лимиты), валидация, формат ошибок, keyset-курсоры. **Изменено:** хранилище — PostgreSQL; Basic только на `POST /auth/sessions`, далее opaque Bearer; `X-User-Id` не читается. + +**Схема** (`migrations/0000{1..4}`): `users` (UNIQUE username, CHECK формата), `chats`, `chat_members` (PK `(chat_id, user_id)`, индекс `(user_id, chat_id)`), `messages` (FK `(chat_id, sender_id) → chat_members` — отправитель обязан быть участником на уровне БД; индекс `(chat_id, created_at, id)` под keyset). + +**Транзакции.** Создание чата — одна транзакция `INSERT chats` + `INSERT chat_members SELECT unnest(...)`; неизвестный участник → FK → rollback → 400. Регистрация — один `INSERT`, гонку решает UNIQUE (→ 409). Сообщение — один `INSERT`, членство проверяет FK. COMMIT с `synchronous_commit=on` переживает падение процесса PostgreSQL, но не потерю диска. + +**Сессии.** Токен — 256 бит `crypto/rand`; в Valkey хранится только его SHA-256: `SET NX EXAT expires_at`. Срок абсолютный — рестарт его не продлевает; в коде срок проверяется повторно. Logout — `DEL`. Valkey — единственное хранилище сессий, поэтому AOF `everysec` (штатный рестарт — без потерь, падение — до ~1 с) и `noeviction`. + +**Пароли** — Argon2id (m=19 MiB, t=2, p=1), PHC-строка, ≤4 хеширования одновременно; для неизвестного username считается dummy-hash. Медленный солёный KDF защищает от перебора утёкших хешей; быстрый SHA-256 подходит токену, у которого полная энтропия. + +**Пул и таймауты:** PostgreSQL ≤10 соединений, запрос ≤3 с; Valkey сессий ≤20, 1 с; кэш ≤20, 200 мс, breaker 1 с; HTTP ≤64 запроса одновременно (429), тело ≤64 KiB (413). Все SQL параметризованы, ошибки БД → доменные без деталей; недоступность зависимостей → 503. + +**Конкурентные вставки.** `created_at = now()` начала транзакции; транзакции могут закоммититься не в порядке `created_at`, поэтому читатель, прошедший позицию курсора, может не увидеть более раннее по времени сообщение. Повторов при обходе неизменной истории нет. + +| Переменная `.env.example` | Назначение | +|---|---| +| `APP_HOST`, `APP_PORT`, `APP_ENV` | адрес HTTP `0.0.0.0:8080`; поле `env` в логах | +| `SESSION_TTL_SECONDS` | TTL сессии, 3600 (переопределяется из shell для теста expiry) | +| `DATABASE_URL_FILE`, `CACHE_URL_FILE` | DSN PostgreSQL и URL Valkey сессий из secrets | +| `SESSION_STORE` | только `valkey`, иное — ошибка конфигурации | +| `API_PUBLISH_PORT`, `POSTGRES_PORT`, `VALKEY_PORT`, `VALKEY_CACHE_PORT` | хост-порты compose | +| `HISTORY_CACHE`, `HISTORY_CACHE_TTL_SECONDS` | режим кэша `off`/`naive`/`safe` (по умолчанию `safe`), TTL страницы 30 с | +| `HISTORY_CACHE_FILL_DELAY_MS` | fault injection эксперимента, в работе 0 | +| необязательные `DB_*`, `CACHE_*`, `APP_*` | значения по умолчанию в `config/config.go` | ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Критерий | Команда | Результат | Файл | +| --- | --- | --- | --- | +| **Уровень 3** | | | | +| Публичный smoke | `make test` | `PASS: lab2 public API scenario` | `evidence/checks.txt` | +| Данные и сессии переживают рестарт API и всех хранилищ | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS; `StartedAt` всех 4 контейнеров новый, volumes те же | `evidence/persistence.txt` | +| PK/FK, UNIQUE username, миграции с нуля и повторно | `scripts/migrations-check.sh` | 4 миграции на пустом volume; повтор — `no migrations to run`, строк столько же | `evidence/migrations.txt` | +| Атомарное создание чата | `TestCreateChatRollback` | неизвестный участник → 400, таблицы без изменений | `evidence/integration-tests.txt` | +| Basic только на вход, Bearer на остальном, `X-User-Id` не даёт доступ | `TestFailures`, `TestAuth_BearerRequired` | X-User-Id → 401; Basic на `/users/me` → 401 | `evidence/failures.txt` | +| Expiry и logout | `TestFailures` | TTL=2: 200 → 401; logout 204 → 401 | `evidence/failures.txt` | +| Password KDF | `TestHashVerify` | `$argon2id$v=19$m=19456,t=2,p=1$…` | `evidence/checks.txt` | +| Secrets/volumes вне Git | `git check-ignore -v .env secrets/x` | игнорируются; `.dockerignore` исключает их из build context | `evidence/checks.txt` | +| **Уровень 4** | | | | +| Valkey для сессий с TTL и persistence | `compose.yaml`, persistence-тест, `TestFailures` | токен валиден после рестарта и stop/start Valkey | `evidence/persistence.txt`, `evidence/failures.txt` | +| Параметризованные запросы, пул, таймауты | `internal/store/db`, `config` | только `$n`; `MaxConns=10`; запрос ≤3 с | исходники | +| Гонка регистрации username | `TestUsernameRace` | 20 параллельных: 1 created, 19 conflict, 1 строка | `evidence/integration-tests.txt` | +| Индекс истории, EXPLAIN на ≥10 000 | `scripts/explain.sh` | 54 682 сообщения; страница после 10 000 — Index Scan, 5 буферов, ~0,2 мс; OFFSET — 135 буферов; без индекса — Seq Scan + Sort, 986 буферов, ~10 мс | `evidence/explain.txt` | +| Неверный пароль | `TestFailures` | одинаковый 401 + `WWW-Authenticate: Basic` для пароля и username | `evidence/failures.txt` | +| Valkey недоступен | `TestFailures`: `stop valkey` | Bearer → 503, без токена → 401, вход → 503, ready → 503 | `evidence/failures.txt` | +| PostgreSQL недоступен | `TestFailures`: `stop postgres` | запись → 503 без деталей, ready → 503 | `evidence/failures.txt` | +| Кэш недоступен — обход | `TestFailures`, `TestCacheDown_Bypass` | ready 200, запись 201, чтение из PostgreSQL | `evidence/failures.txt` | +| **Уровень 5, трек 1** | | | | +| Stale read и stampede воспроизведены | `scripts/track1.sh`, `TestReadAfterWrite_FillRace`, `TestStampede_SQLCount` | `naive`: stale reads во всех 6 прогонах; stampede 50 промахов → 50 SQL (`safe` — 1) | `evidence/track1/summary.md`, `evidence/integration-tests.txt` | +| SQL и latency до/после | `scripts/track1.sh` | SQL на чтение 2,014 → 0,0034; p95 28,5 → 14,4 мс | `evidence/track1/summary.md` | +| Read-after-write | `cachebench` | `safe`: 0 нарушений на 826 552 проверках | `evidence/track1/*.json` | +| Восстановление после рестарта кэша | `track1.sh`: stop/start и pause/unpause под нагрузкой | 0 ошибок, 0 stale | `evidence/track1/summary.md` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +### Трек 1. Согласованность кэша истории -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +**Гипотеза.** Классический cache-aside (`naive`: прочитать БД → положить в кэш; после COMMIT удалить ключи) на горячем чате (1) нарушает read-after-write — читатель кладёт в кэш снимок, прочитанный до COMMIT, уже после удаления ключей; (2) даёт stampede. Версионные ключи + singleflight + lock (`safe`) устраняют оба эффекта. + +**Защита** (`app/internal/cache/history.go`). Страница лежит под `hc:page:{chat}:{ver}:…`, `ver` — случайные 64 бита. Запись: COMMIT → `DEL hc:ver:{chat}` → 201. Снимок, прочитанный до COMMIT, попадает только под старую версию, которую никто не прочитает. Версия случайная, поэтому её потеря (LRU, рестарт) — только промах. Stampede: `singleflight` в процессе + `SET NX PX 500` lock между репликами. Доступ проверяется до выдачи страницы. При отказе кэша — breaker и чтение из PostgreSQL; несработавший `DEL` повторяется каждые 200 мс, чат до этого читается мимо кэша. Ошибка кэша не превращает подтверждённую запись в 503. + +**Методика.** `REPEATS=3 DURATION=30s sh scripts/track1.sh`: для каждого режима API пересоздаётся с нужным `HISTORY_CACHE` и `FILL_DELAY` (0 или 20 мс — расширенное окно гонки), кэш очищается. `cachebench` в той же Docker-сети создаёт чат со 150 сообщениями; 3 с прогрева, 30 с замера. 32 читателя в closed loop опрашивают хвост истории; 2 писателя раз в 100 мс пишут и сразу читают (RAW). Каждое полное чтение хвоста сверяется со всеми сообщениями, получившими 201 до его начала (stale read). SQL — `pg_stat_statements`, hit/miss — `INFO stats`, CPU/RAM — `docker stats`. + +**Стенд.** Windows 10 Pro, Docker Desktop 27.2.0 / WSL2, 12 vCPU / 1.9 GiB, генератор на том же host. В БД ~69 000 сообщений. + +**Результаты** (медианы трёх 30-секундных прогонов; нарушения — сумма): + +| Режим | Чтений/с | p50 / p95 / p99, мс | SQL на чтение | Hit | RAW нарушений | Stale reads | Ошибки | +|---|---|---|---|---|---|---|---| +| off | 2 267 | 12,0 / 28,5 / 39,6 | 2,014 | — | 0 / 1 358 | 0 / 204 418 | 0 | +| naive | 2 712 | 9,9 / 25,5 / 36,0 | 0,010 | 99,2 % | **712 / 1 379** | **128 731 / 248 013** | 0 | +| safe | 4 631 | 5,9 / 14,4 / 20,2 | 0,0034 | 97,8 % | 0 / 1 417 | 0 / 428 275 | 0 | +| naive + 20 мс | 4 813 | 4,7 / 23,3 / 30,0 | 0,053 | 97,3 % | **3 / 1 282** | **13 484 / 361 325** | 0 | +| safe + 20 мс | 4 456 | 5,3 / 23,5 / 29,8 | 0,0030 | 97,5 % | 0 / 1 344 | 0 / 398 277 | 0 | + +CPU postgres: off 175 % → naive 8 % → safe 3 %; RAM api ≤74 MiB, postgres ≤71 MiB (подробно — `evidence/track1/summary.md`). + +**Выводы.** Stale read воспроизведён во всех 6 прогонах `naive`, в том числе без fault injection; в `safe` — 0 на 826 552 проверках. В `safe` SQL страницы ≈ числу записей (одно заполнение на инвалидацию при 32 читателях); в `naive` при окне 20 мс — в 19 раз больше. Относительно `off` кэш снимает ~99,8 % SQL чтения, пропускная способность ×2, p95 почти вдвое ниже. Цена — +1 обращение к Valkey на чтение и +1 `DEL` на запись. + +**Ограничения.** Один host, closed-loop генератор (coordinated omission): абсолютные RPS не переносимы, устойчивы SQL на чтение и наличие/отсутствие нарушений. Доказана одна реплика API. Не закрыто окно: `DEL` не удался, а другая реплика (lab3) видит кэш — устаревание ≤ TTL страницы 30 с. + +### Отказы + +| Воздействие | Ожидаем | Наблюдали | Восстановление / потери | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| `scripts/restart.sh` | данные и токен на месте | persistence PASS, все 4 контейнера перезапущены | потерь нет | +| `stop valkey` | 503, не анонимный доступ | Bearer 503, без токена 401, вход 503, ready 503 | ready через 0,1–0,5 с; сессии сохранены (AOF) | +| `stop postgres` | ограниченный 503 | запись 503, ready 503, без деталей БД | ready через 0,5–0,7 с; запись 201 тем же токеном | +| `stop valkey-cache` | обход кэша | ready 200, запись 201, чтение из PostgreSQL | без ошибок; кэш холодный | +| stop/start кэша под нагрузкой | 0 ошибок, 0 stale | 153 522 чтения, 0 ошибок, 0 stale | без потерь | +| pause/unpause кэша под нагрузкой | 0 stale при сохранённых старых страницах | 160 911 чтений, 0 ошибок, 0 stale; p95 записи 211 мс (таймаут `DEL`) | отложенные инвалидации выполнены до первого чтения из кэша | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Один Docker-host, без реплик PostgreSQL/Valkey: потеря host или volume — потеря данных и сессий. +- `appendfsync everysec`: при аварии теряется до ~1 с входов/logout; отозванная сессия может «воскреснуть» до `expires_at`. `always` убирает окно ценой задержки. +- Кэш: окно ≤30 с при неудачном `DEL` и нескольких репликах или падении API до повтора. Полностью закрыла бы его версия в PostgreSQL в той же транзакции — не реализовано. +- `ListChats` использует `$2 IS NULL OR …`; при большом числе чатов на пользователя запрос стоит разделить, как для истории. +- `valkey-cache` получает анонимный volume из образа, но с `--save "" --appendonly no` он пуст. diff --git a/app/cmd/cachebench/main.go b/app/cmd/cachebench/main.go new file mode 100644 index 0000000..62e662a --- /dev/null +++ b/app/cmd/cachebench/main.go @@ -0,0 +1,595 @@ +package main + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "encoding/json" + "flag" + "fmt" + "io" + "net/http" + "net/url" + "os" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/jackc/pgx/v5" + "github.com/redis/go-redis/v9" +) + +type message struct { + ID string `json:"id"` + CreatedAt string `json:"created_at"` +} + +type pos struct { + t time.Time + id string +} + +func posOf(m message) pos { + t, _ := time.Parse(time.RFC3339Nano, m.CreatedAt) + return pos{t, m.ID} +} + +func (a pos) after(b pos) bool { + return a.t.After(b.t) || (a.t.Equal(b.t) && a.id > b.id) +} + +type ackedMsg struct { + p pos + ack time.Time +} + +type acked struct { + mu sync.Mutex + msgs []ackedMsg +} + +func (a *acked) add(m message, at time.Time) { + a.mu.Lock() + a.msgs = append(a.msgs, ackedMsg{posOf(m), at}) + a.mu.Unlock() +} + +func (a *acked) missing(start time.Time, after *pos, items []message) int { + seen := make(map[string]bool, len(items)) + for _, m := range items { + seen[m.ID] = true + } + a.mu.Lock() + defer a.mu.Unlock() + n := 0 + for _, m := range a.msgs { + if !m.ack.Before(start) || (after != nil && !m.p.after(*after)) { + continue + } + if !seen[m.p.id] { + n++ + } + } + return n +} + +type page struct { + Items []message `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type client struct { + base string + token string + http *http.Client +} + +func (c *client) do(method, path string, body any, out any) (int, error) { + var rd io.Reader + if body != nil { + b, _ := json.Marshal(body) + rd = bytes.NewReader(b) + } + req, err := http.NewRequest(method, c.base+path, rd) + if err != nil { + return 0, err + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + resp, err := c.http.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + data, _ := io.ReadAll(resp.Body) + if out != nil && resp.StatusCode < 300 { + if err := json.Unmarshal(data, out); err != nil { + return resp.StatusCode, err + } + } + return resp.StatusCode, nil +} + +func randHex(n int) string { + b := make([]byte, n) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func mustOK(code int, err error, want int, what string) { + if err != nil || code != want { + fmt.Fprintf(os.Stderr, "setup %s: status %d err %v\n", what, code, err) + os.Exit(1) + } +} + +// register создаёт синтетического пользователя и входит через Basic. +func register(base string, hc *http.Client, name string) (*client, string) { + c := &client{base: base, http: hc} + pw := "bench-" + randHex(12) + var u struct { + ID string `json:"id"` + } + code, err := c.do("POST", "/api/v1/users", map[string]string{ + "username": name, "display_name": name, "password": pw, + }, &u) + mustOK(code, err, 201, "register") + + req, _ := http.NewRequest("POST", base+"/api/v1/auth/sessions", nil) + req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(name+":"+pw))) + resp, err := hc.Do(req) + if err != nil { + mustOK(0, err, 201, "login") + } + defer resp.Body.Close() + var s struct { + Token string `json:"token"` + } + _ = json.NewDecoder(resp.Body).Decode(&s) + mustOK(resp.StatusCode, nil, 201, "login") + c.token = s.Token + return c, u.ID +} + +type second struct { + reads, readErr, writes, writeErr, rawChecks, rawViolations int + staleChecks, staleReads int + readLat []float64 +} + +type recorder struct { + mu sync.Mutex + start time.Time + secs map[int]*second + status map[string]int + reads []float64 + writes []float64 +} + +func (r *recorder) at(t time.Time) *second { + i := int(t.Sub(r.start) / time.Second) + s, ok := r.secs[i] + if !ok { + s = &second{} + r.secs[i] = s + } + return s +} + +func (r *recorder) read(t time.Time, lat time.Duration, code int, err error) { + r.mu.Lock() + defer r.mu.Unlock() + s := r.at(t) + if err != nil || code != 200 { + s.readErr++ + r.status[statusKey("read", code, err)]++ + return + } + ms := float64(lat.Microseconds()) / 1000 + s.reads++ + s.readLat = append(s.readLat, ms) + r.reads = append(r.reads, ms) +} + +func (r *recorder) write(t time.Time, lat time.Duration, code int, err error) { + r.mu.Lock() + defer r.mu.Unlock() + s := r.at(t) + if err != nil || code != 201 { + s.writeErr++ + r.status[statusKey("write", code, err)]++ + return + } + s.writes++ + r.writes = append(r.writes, float64(lat.Microseconds())/1000) +} + +func (r *recorder) stale(t time.Time, violated bool) { + r.mu.Lock() + defer r.mu.Unlock() + s := r.at(t) + s.staleChecks++ + if violated { + s.staleReads++ + } +} + +func (r *recorder) raw(t time.Time, violated bool) { + r.mu.Lock() + defer r.mu.Unlock() + s := r.at(t) + s.rawChecks++ + if violated { + s.rawViolations++ + } +} + +func statusKey(kind string, code int, err error) string { + if err != nil { + return kind + "_net_error" + } + return fmt.Sprintf("%s_%d", kind, code) +} + +func pct(xs []float64, p float64) float64 { + if len(xs) == 0 { + return 0 + } + s := append([]float64(nil), xs...) + sort.Float64s(s) + i := int(p*float64(len(s))+0.5) - 1 + if i < 0 { + i = 0 + } + if i >= len(s) { + i = len(s) - 1 + } + return s[i] +} + +func tail(c *client, chat, cursor string) (ids map[string]bool, last string, code int, err error) { + ids = map[string]bool{} + last = cursor + for i := 0; i < 50; i++ { + path := "/api/v1/chats/" + chat + "/messages?limit=100" + if last != "" { + path += "&cursor=" + url.QueryEscape(last) + } + var p page + code, err = c.do("GET", path, nil, &p) + if err != nil || code != 200 { + return ids, last, code, err + } + for _, m := range p.Items { + ids[m.ID] = true + } + if p.NextCursor == nil { + return ids, last, code, nil + } + last = *p.NextCursor + } + return ids, last, code, nil +} + +func main() { + base := flag.String("base-url", "http://localhost:8080", "API base URL") + readers := flag.Int("readers", 32, "читателей горячего чата (closed loop)") + writers := flag.Int("writers", 2, "писателей с проверкой read-after-write") + duration := flag.Duration("duration", 30*time.Second, "длительность замера") + warmup := flag.Duration("warmup", 3*time.Second, "прогрев до замера (не входит в результат)") + interval := flag.Duration("write-interval", 100*time.Millisecond, "пауза между записями одного писателя") + seed := flag.Int("seed", 150, "сообщений в чате до начала") + label := flag.String("label", "", "метка прогона (режим кэша)") + out := flag.String("out", "", "куда записать JSON-результат") + dbFile := flag.String("db-url-file", "", "файл с DSN PostgreSQL для pg_stat_statements") + cacheFile := flag.String("cache-url-file", "", "файл с URL valkey-cache для INFO stats") + flag.Parse() + ctx := context.Background() + stats := openStats(ctx, *dbFile, *cacheFile) + + hc := &http.Client{ + Timeout: 5 * time.Second, + Transport: &http.Transport{MaxIdleConnsPerHost: *readers + *writers + 4}, + } + sfx := randHex(4) + owner, ownerID := register(*base, hc, "bench_o_"+sfx) + members := []string{ownerID} + clients := []*client{owner} + for i := 0; i < *writers; i++ { + c, id := register(*base, hc, fmt.Sprintf("bench_w%d_%s", i, sfx)) + clients = append(clients, c) + members = append(members, id) + } + var chat struct { + ID string `json:"id"` + } + code, err := owner.do("POST", "/api/v1/chats", map[string]any{"title": "bench " + sfx, "member_ids": members}, &chat) + mustOK(code, err, 201, "chat") + for i := 0; i < *seed; i++ { + code, err := owner.do("POST", "/api/v1/chats/"+chat.ID+"/messages", map[string]string{"text": fmt.Sprintf("seed %d", i)}, nil) + mustOK(code, err, 201, "seed") + } + + rec := &recorder{secs: map[int]*second{}, status: map[string]int{}} + stop := make(chan struct{}) + measuring := make(chan struct{}) + var wg sync.WaitGroup + ack := &acked{} + + for i := 0; i < *readers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + cursor := "" + var cursorPos *pos + for { + select { + case <-stop: + return + default: + } + path := "/api/v1/chats/" + chat.ID + "/messages?limit=100" + if cursor != "" { + path += "&cursor=" + url.QueryEscape(cursor) + } + var p page + t0 := time.Now() + code, err := owner.do("GET", path, nil, &p) + ok := err == nil && code == 200 + if closed(measuring) { + rec.read(t0, time.Since(t0), code, err) + if ok && p.NextCursor == nil { + rec.stale(t0, ack.missing(t0, cursorPos, p.Items) > 0) + } + } + if ok && p.NextCursor != nil && len(p.Items) > 0 { + cursor = *p.NextCursor + last := posOf(p.Items[len(p.Items)-1]) + cursorPos = &last + } + } + }() + } + for w := 0; w < *writers; w++ { + wg.Add(1) + c := clients[w+1] + go func() { + defer wg.Done() + cursor := "" + n := 0 + for { + select { + case <-stop: + return + case <-time.After(*interval): + } + var m message + t0 := time.Now() + code, err := c.do("POST", "/api/v1/chats/"+chat.ID+"/messages", map[string]string{"text": fmt.Sprintf("raw %s %d", sfx, n)}, &m) + n++ + isMeasuring := closed(measuring) + if isMeasuring { + rec.write(t0, time.Since(t0), code, err) + } + if err != nil || code != 201 { + continue + } + ack.add(m, time.Now()) + ids, last, rc, rerr := tail(c, chat.ID, cursor) + if rerr != nil || rc != 200 { + continue + } + cursor = last + if isMeasuring { + rec.raw(t0, !ids[m.ID]) + } + } + }() + } + + time.Sleep(*warmup) + stats.reset(ctx) + rec.mu.Lock() + rec.start = time.Now() + rec.mu.Unlock() + close(measuring) + time.Sleep(*duration) + close(stop) + wg.Wait() + sqlStats, cacheStats := stats.collect(ctx) + + type secOut struct { + S int `json:"s"` + Reads int `json:"reads"` + ReadErrors int `json:"read_errors"` + ReadP95Ms float64 `json:"read_p95_ms"` + Writes int `json:"writes"` + WriteErrors int `json:"write_errors"` + RAWViolations int `json:"raw_violations"` + StaleReads int `json:"stale_reads"` + } + var timeline []secOut + totals := second{} + for i := 0; i < int(*duration/time.Second)+1; i++ { + s, ok := rec.secs[i] + if !ok { + continue + } + timeline = append(timeline, secOut{i, s.reads, s.readErr, pct(s.readLat, 0.95), s.writes, s.writeErr, s.rawViolations, s.staleReads}) + totals.reads += s.reads + totals.readErr += s.readErr + totals.writes += s.writes + totals.writeErr += s.writeErr + totals.rawChecks += s.rawChecks + totals.rawViolations += s.rawViolations + totals.staleChecks += s.staleChecks + totals.staleReads += s.staleReads + } + secs := duration.Seconds() + result := map[string]any{ + "label": *label, + "date_utc": time.Now().UTC().Format(time.RFC3339), + "duration_s": secs, + "warmup_s": warmup.Seconds(), + "readers": *readers, + "writers": *writers, + "write_interval_ms": interval.Milliseconds(), + "seed_messages": *seed, + "reads_ok": totals.reads, + "read_errors": totals.readErr, + "read_rps": float64(totals.reads) / secs, + "read_p50_ms": pct(rec.reads, 0.50), + "read_p95_ms": pct(rec.reads, 0.95), + "read_p99_ms": pct(rec.reads, 0.99), + "writes_ok": totals.writes, + "write_errors": totals.writeErr, + "write_p50_ms": pct(rec.writes, 0.50), + "write_p95_ms": pct(rec.writes, 0.95), + "raw_checks": totals.rawChecks, + "raw_violations": totals.rawViolations, + "stale_checks": totals.staleChecks, + "stale_reads": totals.staleReads, + "error_statuses": rec.status, + "sql": sqlStats, + "cache": cacheStats, + "timeline": timeline, + } + if n, ok := sqlStats["history_page_calls"].(int64); ok && totals.reads > 0 { + m := sqlStats["membership_calls"].(int64) + result["sql_history_per_read"] = float64(n) / float64(totals.reads) + result["sql_read_path_per_read"] = float64(n+m) / float64(totals.reads) + } + b, _ := json.MarshalIndent(result, "", " ") + if *out != "" { + if err := os.WriteFile(*out, b, 0o644); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + } + short := map[string]any{} + for k, v := range result { + if k != "timeline" { + short[k] = v + } + } + sb, _ := json.Marshal(short) + fmt.Println(string(sb)) +} + +func closed(ch chan struct{}) bool { + select { + case <-ch: + return true + default: + return false + } +} + +type statsConn struct { + db *pgx.Conn + cache *redis.Client +} + +func readSecret(path string) string { + b, err := os.ReadFile(path) + if err != nil { + fmt.Fprintf(os.Stderr, "read %s: %v\n", path, err) + os.Exit(1) + } + return strings.TrimSpace(string(b)) +} + +func openStats(ctx context.Context, dbFile, cacheFile string) *statsConn { + s := &statsConn{} + if dbFile != "" { + conn, err := pgx.Connect(ctx, readSecret(dbFile)) + if err != nil { + fmt.Fprintln(os.Stderr, "stats db connect failed") + os.Exit(1) + } + if _, err := conn.Exec(ctx, `CREATE EXTENSION IF NOT EXISTS pg_stat_statements`); err != nil { + fmt.Fprintf(os.Stderr, "pg_stat_statements: %v\n", err) + os.Exit(1) + } + s.db = conn + } + if cacheFile != "" { + if opts, err := redis.ParseURL(readSecret(cacheFile)); err == nil { + s.cache = redis.NewClient(opts) + } + } + return s +} + +func (s *statsConn) reset(ctx context.Context) { + if s.db != nil { + if _, err := s.db.Exec(ctx, `SELECT pg_stat_statements_reset()`); err != nil { + fmt.Fprintf(os.Stderr, "pg_stat_statements_reset: %v\n", err) + } + } + if s.cache != nil { + _ = s.cache.ConfigResetStat(ctx).Err() + } +} + +func (s *statsConn) collect(ctx context.Context) (map[string]any, map[string]any) { + sqlOut := map[string]any{} + if s.db != nil { + rows, err := s.db.Query(ctx, ` + SELECT query, calls, total_exec_time + FROM pg_stat_statements + WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) + AND query NOT ILIKE '%pg_stat_statements%'`) + if err == nil { + var total, history, member, insert int64 + var historyMs float64 + for rows.Next() { + var q string + var calls int64 + var ms float64 + if rows.Scan(&q, &calls, &ms) != nil { + continue + } + total += calls + switch { + case strings.Contains(q, "FROM messages m"): + history += calls + historyMs += ms + case strings.Contains(q, "FROM chat_members WHERE chat_id"): + member += calls + case strings.Contains(q, "INSERT INTO messages"): + insert += calls + } + } + rows.Close() + sqlOut["total_calls"] = total + sqlOut["history_page_calls"] = history + sqlOut["history_page_total_ms"] = historyMs + sqlOut["membership_calls"] = member + sqlOut["insert_message_calls"] = insert + } + } + cacheOut := map[string]any{} + if s.cache != nil { + info, err := s.cache.Info(ctx, "stats").Result() + if err != nil { + cacheOut["error"] = "unavailable" + } + for _, line := range strings.Split(info, "\n") { + k, v, ok := strings.Cut(strings.TrimSpace(line), ":") + if ok && (k == "keyspace_hits" || k == "keyspace_misses" || k == "evicted_keys") { + n, _ := strconv.ParseInt(v, 10, 64) + cacheOut[k] = n + } + } + } + return sqlOut, cacheOut +} diff --git a/app/cmd/messenger/main.go b/app/cmd/messenger/main.go new file mode 100644 index 0000000..4670842 --- /dev/null +++ b/app/cmd/messenger/main.go @@ -0,0 +1,132 @@ +package main + +import ( + "context" + "fmt" + "log/slog" + "os" + "os/signal" + "runtime" + "syscall" + "time" + + httpapi "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/cache" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/logging" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db" +) + +func main() { + cfg, err := config.Load() + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + + logger, err := logging.New(cfg.Logger.Level, cfg.Env, cfg.Version) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + slog.SetDefault(logger) + + pool, err := db.Connect(context.Background(), cfg.Database) + if err != nil { + logger.Error("database connect failed", slog.Any("err", err)) + os.Exit(1) + } + storage := db.New(pool, time.Duration(cfg.Database.QueryTimeoutMs)*time.Millisecond) + defer storage.Close() + + sessClient, err := session.Connect(context.Background(), cfg.Cache) + if err != nil { + logger.Error("session store connect failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + defer sessClient.Close() + sessions := session.NewValkey(sessClient) + + hasher := password.NewHasher(password.Default, min(runtime.NumCPU(), 4)) + + auth, err := service.NewAuth(storage, sessions, hasher, time.Duration(cfg.Session.TTLSeconds)*time.Second) + if err != nil { + logger.Error("auth init failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + + var messages store.MessageStore = storage + if cfg.HistoryCache.Mode != cache.ModeOff { + hcClient, err := cache.Connect(cfg.HistoryCache) + if err != nil { + logger.Error("history cache config failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + defer hcClient.Close() + hc := cache.New(storage.Messages, hcClient, cache.Options{ + Mode: cfg.HistoryCache.Mode, + PageTTL: time.Duration(cfg.HistoryCache.PageTTLSeconds) * time.Second, + FillDelay: time.Duration(cfg.HistoryCache.FillDelayMs) * time.Millisecond, + Logger: logger, + }) + defer hc.Close() + messages = hc + } + logger.Info("history cache", slog.String("mode", cfg.HistoryCache.Mode)) + + srv := httpapi.NewServer(httpapi.Deps{ + Config: cfg, + Logger: logger, + Store: storage, + Auth: auth, + Users: service.NewUsers(storage, hasher), + Chats: service.NewChats(storage), + Messages: service.NewMessages(messages), + Ready: func(ctx context.Context) error { + if err := storage.Ping(ctx); err != nil { + return err + } + return sessions.Ping(ctx) + }, + }) + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + startErr := make(chan error, 1) + go func() { + startErr <- srv.Start() + }() + + select { + case err := <-startErr: + if err != nil { + logger.Error("server failed to start", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + case <-ctx.Done(): + logger.Info("shutdown signal received") + } + + shutdownCtx, cancel := context.WithTimeout( + context.Background(), + time.Duration(cfg.HTTP.ShutdownTimeoutMs)*time.Millisecond, + ) + defer cancel() + + if err := srv.Shutdown(shutdownCtx); err != nil { + logger.Error("shutdown failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + + logger.Info("server stopped cleanly") +} diff --git a/app/e2e/failures_test.go b/app/e2e/failures_test.go new file mode 100644 index 0000000..827b3f5 --- /dev/null +++ b/app/e2e/failures_test.go @@ -0,0 +1,329 @@ +// Package e2e — проверки уровня 4 против запущенного compose-стенда. +// +// Неверный пароль, X-User-Id/Basic вместо Bearer, logout, expiry при коротком +// SESSION_TTL_SECONDS, недоступность Valkey сессий, PostgreSQL и Valkey-кэша. +// Тест сам останавливает и запускает контейнеры (volumes не трогает) и в конце +// возвращает стенд в исходный режим. Токены и пароли не печатает. +// +// Запуск: scripts/failures-tests.sh; без E2E_BASE_URL тесты пропускаются, +// поэтому обычный go test ./... контейнеры не трогает. +package e2e + +import ( + "bytes" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +// root — корень репозитория: go test запускает пакет из app/e2e. +var root = filepath.Join("..", "..") + +type client struct { + base string + http *http.Client +} + +type response struct { + status int + header http.Header + body map[string]any + raw []byte +} + +func (r response) errorCode() string { + e, _ := r.body["error"].(map[string]any) + code, _ := e["code"].(string) + return code +} + +func (r response) errorMessage() string { + e, _ := r.body["error"].(map[string]any) + msg, _ := e["message"].(string) + return msg +} + +func (r response) str(key string) string { + s, _ := r.body[key].(string) + return s +} + +// itemIDs — id сообщений страницы истории. +func (r response) itemIDs() []string { + items, _ := r.body["items"].([]any) + ids := make([]string, 0, len(items)) + for _, it := range items { + m, _ := it.(map[string]any) + id, _ := m["id"].(string) + ids = append(ids, id) + } + return ids +} + +// call возвращает status 0, если соединиться не удалось (API перезапускается). +func (c *client) call(method, path, token string, body any, headers map[string]string) response { + var rd io.Reader + if body != nil { + b, _ := json.Marshal(body) + rd = bytes.NewReader(b) + } + req, _ := http.NewRequest(method, c.base+path, rd) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + for k, v := range headers { + req.Header.Set(k, v) + } + resp, err := c.http.Do(req) + if err != nil { + return response{} + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + out := response{status: resp.StatusCode, header: resp.Header, raw: raw} + _ = json.Unmarshal(raw, &out.body) + return out +} + +func basic(username, password string) map[string]string { + return map[string]string{"Authorization": "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))} +} + +func (c *client) login(username, password string) response { + return c.call(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic(username, password)) +} + +// waitReady ждёт /health/ready и возвращает момент готовности. +func (c *client) waitReady(t *testing.T) time.Time { + t.Helper() + deadline := time.Now().Add(90 * time.Second) + for time.Now().Before(deadline) { + if c.call(http.MethodGet, "/health/ready", "", nil, nil).status == http.StatusOK { + return time.Now() + } + time.Sleep(500 * time.Millisecond) + } + t.Fatal("стенд не готов за 90 с") + return time.Time{} +} + +// compose запускает docker compose из корня; env дополняет окружение процесса +// (compose.yaml берёт SESSION_TTL_SECONDS из окружения раньше, чем из .env). +func compose(t *testing.T, env map[string]string, args ...string) { + t.Helper() + cmd := exec.Command("docker", append([]string{"compose", "--env-file", ".env"}, args...)...) + cmd.Dir = root + cmd.Env = os.Environ() + for k, v := range env { + cmd.Env = append(cmd.Env, k+"="+v) + } + // Вывод compose не печатаем: в нём могут оказаться значения окружения. + if err := cmd.Run(); err != nil { + t.Fatalf("docker compose %s: %v", strings.Join(args, " "), err) + } +} + +func randHex(n int) string { + b := make([]byte, n) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func TestFailures(t *testing.T) { + base := os.Getenv("E2E_BASE_URL") + if base == "" { + t.Skip("E2E_BASE_URL не задан (scripts/failures-tests.sh)") + } + c := &client{base: strings.TrimRight(base, "/"), http: &http.Client{Timeout: 10 * time.Second}} + c.waitReady(t) + + // Что бы ни упало, стенд возвращается в рабочий режим: все сервисы запущены, + // API с обычным TTL. + t.Cleanup(func() { + compose(t, nil, "up", "-d", "--wait") + }) + + name, password := "f_"+randHex(4), "pw-"+randHex(8) + u := c.call(http.MethodPost, "/api/v1/users", "", map[string]string{ + "username": name, "display_name": "Отказ", "password": password, + }, nil) + if u.status != http.StatusCreated { + t.Fatalf("регистрация: status %d", u.status) + } + uid := u.str("id") + token := c.login(name, password).str("token") + chat := c.call(http.MethodPost, "/api/v1/chats", token, map[string]any{"title": "Отказы", "member_ids": []string{uid}}, nil) + if chat.status != http.StatusCreated { + t.Fatalf("создание чата: status %d", chat.status) + } + messagesPath := "/api/v1/chats/" + chat.str("id") + "/messages" + + // --- аутентификация --- + + t.Run("неверный пароль → 401 Basic, неотличим от неизвестного username", func(t *testing.T) { + wrong := c.login(name, password+"x") + unknown := c.login("no_such_"+randHex(3), password) + challenge := wrong.header.Get("WWW-Authenticate") + t.Logf("статусы %d/%d, challenge %q", wrong.status, unknown.status, challenge) + if wrong.status != 401 || unknown.status != 401 || !strings.HasPrefix(challenge, "Basic") { + t.Error("ожидали 401 с WWW-Authenticate: Basic для обоих случаев") + } + if wrong.errorCode() != "unauthorized" || wrong.errorCode() != unknown.errorCode() || + wrong.errorMessage() != unknown.errorMessage() { + t.Error("ответы на неверный пароль и неизвестный username различаются") + } + }) + + t.Run("X-User-Id без Bearer → 401", func(t *testing.T) { + r := c.call(http.MethodGet, "/api/v1/users/me", "", nil, map[string]string{"X-User-Id": uid}) + t.Logf("status %d", r.status) + if r.status != 401 || !strings.HasPrefix(r.header.Get("WWW-Authenticate"), "Bearer") { + t.Error("ожидали 401 с WWW-Authenticate: Bearer") + } + }) + + t.Run("Basic на бизнес-endpoint → 401", func(t *testing.T) { + r := c.call(http.MethodGet, "/api/v1/users/me", "", nil, basic(name, password)) + t.Logf("status %d", r.status) + if r.status != 401 { + t.Error("ожидали 401") + } + }) + + t.Run("logout → 204, тот же токен → 401, повторный logout → 401, другая сессия жива", func(t *testing.T) { + tmp := c.login(name, password).str("token") + got := []int{ + c.call(http.MethodDelete, "/api/v1/auth/sessions/current", tmp, nil, nil).status, + c.call(http.MethodGet, "/api/v1/users/me", tmp, nil, nil).status, + c.call(http.MethodDelete, "/api/v1/auth/sessions/current", tmp, nil, nil).status, + c.call(http.MethodGet, "/api/v1/users/me", token, nil, nil).status, + } + t.Logf("статусы %v", got) + if !slices.Equal(got, []int{204, 401, 401, 200}) { + t.Error("ожидали [204 401 401 200]") + } + }) + + + t.Run("expiry при SESSION_TTL_SECONDS=2: 200 сразу, 401 через 3 с", func(t *testing.T) { + compose(t, map[string]string{"SESSION_TTL_SECONDS": "2"}, "up", "-d", "--wait", "api") + defer func() { + compose(t, nil, "up", "-d", "--wait", "api") + c.waitReady(t) + }() + c.waitReady(t) + + s := c.login(name, password) + if s.status != http.StatusCreated { + t.Fatalf("вход: status %d", s.status) + } + expiresAt, err := time.Parse(time.RFC3339, s.str("expires_at")) + if err != nil { + t.Fatalf("expires_at: %v", err) + } + ttl := time.Until(expiresAt) + short := s.str("token") + before := c.call(http.MethodGet, "/api/v1/users/me", short, nil, nil).status + time.Sleep(3200 * time.Millisecond) + after := c.call(http.MethodGet, "/api/v1/users/me", short, nil, nil) + t.Logf("expires_at через %.1f с, статусы %d → %d", ttl.Seconds(), before, after.status) + if ttl > 2500*time.Millisecond || before != 200 || after.status != 401 || + !strings.HasPrefix(after.header.Get("WWW-Authenticate"), "Bearer") { + t.Error("ожидали TTL ≤ 2.5 с, 200 до и 401 Bearer после истечения") + } + }) + + + t.Run("Valkey сессий остановлен: Bearer → 503, без токена → 401, вход → 503, ready → 503", func(t *testing.T) { + compose(t, nil, "stop", "valkey") + me := c.call(http.MethodGet, "/api/v1/users/me", token, nil, nil) + anon := c.call(http.MethodGet, "/api/v1/users/me", "", nil, nil).status + login := c.login(name, password).status + ready := c.call(http.MethodGet, "/health/ready", "", nil, nil).status + t.Logf("me %d, anon %d, login %d, ready %d", me.status, anon, login, ready) + if me.status != 503 || me.errorCode() != "unavailable" || anon != 401 || login != 503 || ready != 503 { + t.Error("ожидали me 503 unavailable, anon 401, login 503, ready 503") + } + }) + + t.Run("Valkey сессий восстановлен: прежний токен снова действителен (AOF)", func(t *testing.T) { + t0 := time.Now() + compose(t, nil, "start", "valkey") + t1 := c.waitReady(t) + st := c.call(http.MethodGet, "/api/v1/users/me", token, nil, nil).status + t.Logf("ready через %.1f с после start, me %d", t1.Sub(t0).Seconds(), st) + if st != 200 { + t.Error("прежний токен не действителен после рестарта Valkey") + } + }) + + + t.Run("PostgreSQL остановлен: чтение/запись → 503 без деталей, ready → 503", func(t *testing.T) { + compose(t, nil, "stop", "postgres") + list := c.call(http.MethodGet, messagesPath, token, nil, nil) + send := c.call(http.MethodPost, messagesPath, token, map[string]string{"text": "при упавшей БД"}, nil) + ready := c.call(http.MethodGet, "/health/ready", "", nil, nil).status + lower := strings.ToLower(string(list.raw) + string(send.raw)) + leaked := false + for _, w := range []string{"sql", "pgx", "dial", "postgres"} { + leaked = leaked || strings.Contains(lower, w) + } + t.Logf("list %d (кэш может отдать страницу), send %d, ready %d, утечка деталей: %v", list.status, send.status, ready, leaked) + if send.status != 503 || ready != 503 || (list.status != 200 && list.status != 503) || leaked { + t.Error("ожидали send 503, ready 503, list 200/503 и никаких деталей БД в ответе") + } + }) + + var restoredID string + t.Run("PostgreSQL восстановлен: запись 201 тем же токеном", func(t *testing.T) { + t0 := time.Now() + compose(t, nil, "start", "postgres") + t1 := c.waitReady(t) + send := c.call(http.MethodPost, messagesPath, token, map[string]string{"text": "после восстановления БД"}, nil) + restoredID = send.str("id") + t.Logf("ready через %.1f с после start, send %d", t1.Sub(t0).Seconds(), send.status) + if send.status != 201 { + t.Error("ожидали 201") + } + }) + + var bypassID string + t.Run("Valkey-кэш остановлен: ready 200, запись 201, чтение 200 из PostgreSQL с новым сообщением", func(t *testing.T) { + compose(t, nil, "stop", "valkey-cache") + ready := c.call(http.MethodGet, "/health/ready", "", nil, nil).status + send := c.call(http.MethodPost, messagesPath, token, map[string]string{"text": "при упавшем кэше"}, nil) + bypassID = send.str("id") + list := c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil) + ids := list.itemIDs() + t.Logf("ready %d, send %d, list %d, сообщений %d", ready, send.status, list.status, len(ids)) + if ready != 200 || send.status != 201 || list.status != 200 || + !slices.Contains(ids, bypassID) || !slices.Contains(ids, restoredID) { + t.Error("ожидали ready 200, send 201, list 200 с обоими новыми сообщениями") + } + }) + + t.Run("Valkey-кэш восстановлен: история полная и одинаковая при промахе и попадании", func(t *testing.T) { + compose(t, nil, "up", "-d", "--wait", "valkey-cache") + time.Sleep(1500 * time.Millisecond) // breaker 1 с + повтор отложенной инвалидации 200 мс + miss := c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil) + hit := c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil) + ids := hit.itemIDs() + t.Logf("статусы %d/%d, сообщений %d", miss.status, hit.status, len(ids)) + if miss.status != 200 || hit.status != 200 || !bytes.Equal(miss.raw, hit.raw) || !slices.Contains(ids, bypassID) { + t.Error("ожидали две одинаковые полные страницы с сообщением, записанным при упавшем кэше") + } + }) +} diff --git a/app/go.mod b/app/go.mod new file mode 100644 index 0000000..1cde37a --- /dev/null +++ b/app/go.mod @@ -0,0 +1,28 @@ +module gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl + +go 1.26.0 + +require ( + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.7.6 + github.com/labstack/echo/v4 v4.16.2 + github.com/redis/go-redis/v9 v9.7.3 + golang.org/x/crypto v0.57.0 + golang.org/x/sync v0.23.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/labstack/gommon v0.5.0 // indirect + github.com/mattn/go-colorable v0.1.15 // indirect + github.com/mattn/go-isatty v0.0.22 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect + golang.org/x/net v0.60.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect +) diff --git a/app/go.sum b/app/go.sum new file mode 100644 index 0000000..511e7b8 --- /dev/null +++ b/app/go.sum @@ -0,0 +1,56 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk= +github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/labstack/echo/v4 v4.16.2 h1:WFPVqfogOZGH4dTr1UCIB1sqjFIQ/k7vIk5ByL6oWjY= +github.com/labstack/echo/v4 v4.16.2/go.mod h1:V/EQaTVHYJH92QhbQe7kFQ4mjgcjxLQQUQtAN87zZdw= +github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c= +github.com/labstack/gommon v0.5.0/go.mod h1:Rzlg7HHy1maLfzBYGg9NZcVuz1sA68HHhLjhcEllYE0= +github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= +github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4= +github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= +github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/app/internal/api/http/access_test.go b/app/internal/api/http/access_test.go new file mode 100644 index 0000000..a561051 --- /dev/null +++ b/app/internal/api/http/access_test.go @@ -0,0 +1,115 @@ +package http + +import ( + "bytes" + "io" + "net/http" + "strings" + "testing" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" +) + +func TestAccess_ForeignChat(t *testing.T) { + r := newTestRig(t) + _, _, eve, chat := bootstrap(r) + base := "/api/v1/chats/" + chat.ID + + cases := []struct { + method, path string + body any + }{ + {http.MethodGet, base, nil}, + {http.MethodGet, base + "/messages?limit=10", nil}, + {http.MethodPost, base + "/messages", dto.CreateMessageRequest{Text: "вторжение"}}, + } + for _, tc := range cases { + var resp *http.Response + if tc.body == nil { + resp = r.do(tc.method, tc.path, eve.ID, nil, nil) + } else { + resp = r.doJSON(tc.method, tc.path, eve.ID, tc.body) + } + if resp.StatusCode != http.StatusNotFound { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("%s %s expected 404, got %d; body=%s", tc.method, tc.path, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Code != CodeNotFound { + t.Fatalf("%s %s expected code %q, got %q", tc.method, tc.path, CodeNotFound, e.Error.Code) + } + } + + resp := r.do(http.MethodGet, "/api/v1/chats?limit=100", eve.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + var page dto.ChatsPageResponse + readJSON(t, resp, &page) + for _, item := range page.Items { + if item.ID == chat.ID { + t.Fatalf("чат утёк в список чужого пользователя") + } + } +} + +func TestAccess_AuthBeforeContentType(t *testing.T) { + r := newTestRig(t) + resp := r.do(http.MethodPost, "/api/v1/chats", "", + map[string]string{"Content-Type": "text/plain"}, strings.NewReader("x")) + expectStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + + resp = r.do(http.MethodPost, "/api/v1/nope", "", nil, strings.NewReader("x")) + expectStatus(t, resp, http.StatusNotFound) + if resp.Header.Get("X-Request-Id") == "" { + t.Fatal("404 without X-Request-Id") + } + resp.Body.Close() +} + +func TestAccess_RouterErrors(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + chatPath := "/api/v1/chats/" + chat.ID + + cases := []struct { + method, path, actor string + status int + code, message string + }{ + {http.MethodGet, "/nope", "", http.StatusNotFound, CodeNotFound, "Object not found"}, + {http.MethodGet, "/health/live/", "", http.StatusNotFound, CodeNotFound, "Object not found"}, + {http.MethodGet, "/api/v1/nope", alice.ID, http.StatusNotFound, CodeNotFound, "Object not found"}, + {http.MethodPost, "/health/live", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodGet, "/api/v1/users", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodPost, "/api/v1/users/me", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodDelete, "/api/v1/users/me", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodDelete, "/api/v1/chats", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodPut, chatPath, alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodPatch, chatPath + "/messages", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + } + for _, tc := range cases { + var body io.Reader + headers := map[string]string{} + if tc.method == http.MethodPost || tc.method == http.MethodPut || tc.method == http.MethodPatch { + body = bytes.NewReader([]byte(`{}`)) + headers["Content-Type"] = "application/json" + } + resp := r.do(tc.method, tc.path, tc.actor, headers, body) + if resp.StatusCode != tc.status { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("%s %s: expected %d, got %d; body=%s", tc.method, tc.path, tc.status, resp.StatusCode, string(data)) + } + if tc.status == http.StatusMethodNotAllowed && resp.Header.Get("Allow") == "" { + t.Fatalf("%s %s: 405 без заголовка Allow", tc.method, tc.path) + } + e := readError(t, resp) + if e.Error.Code != tc.code || e.Error.Message != tc.message { + t.Fatalf("%s %s: expected %q/%q, got %q/%q", tc.method, tc.path, tc.code, tc.message, e.Error.Code, e.Error.Message) + } + if e.Error.RequestID == "" || e.Error.RequestID != resp.Header.Get("X-Request-Id") { + t.Fatalf("%s %s: request_id %q не совпадает с заголовком %q", tc.method, tc.path, e.Error.RequestID, resp.Header.Get("X-Request-Id")) + } + } +} diff --git a/app/internal/api/http/auth.go b/app/internal/api/http/auth.go new file mode 100644 index 0000000..74dc376 --- /dev/null +++ b/app/internal/api/http/auth.go @@ -0,0 +1,70 @@ +package http + +import ( + "encoding/base64" + "errors" + "net/http" + "strings" + "unicode/utf8" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +type authHandler struct { + auth service.AuthService +} + +func (h *authHandler) createSession(c echo.Context) error { + if c.Request().ContentLength > 0 { + return WriteError(c, &validate.Error{Field: "body", Reason: "must be empty, credentials go in Authorization: Basic"}) + } + username, password, ok := parseBasic(c.Request().Header.Get(echo.HeaderAuthorization)) + if !ok { + return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials") + } + + s, err := h.auth.Login(c.Request().Context(), username, password) + if err != nil { + if errors.Is(err, domain.ErrUnauthorized) { + return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials") + } + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, dto.SessionResponse{ + Token: s.Token, + TokenType: "Bearer", + ExpiresAt: s.ExpiresAt, + User: toUserResponse(s.User), + }) +} + +func (h *authHandler) revokeSession(c echo.Context) error { + tok := c.Get(middleware.AuthTokenKey).(string) + if err := h.auth.Logout(c.Request().Context(), tok); err != nil { + return WriteError(c, err) + } + return c.NoContent(http.StatusNoContent) +} + + +func parseBasic(header string) (username, password string, ok bool) { + scheme, encoded, found := strings.Cut(header, " ") + if !found || !strings.EqualFold(scheme, "Basic") { + return "", "", false + } + raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded)) + if err != nil || !utf8.Valid(raw) { + return "", "", false + } + username, password, found = strings.Cut(string(raw), ":") + if !found || username == "" || password == "" { + return "", "", false + } + return username, password, true +} diff --git a/app/internal/api/http/auth_test.go b/app/internal/api/http/auth_test.go new file mode 100644 index 0000000..9f93c3b --- /dev/null +++ b/app/internal/api/http/auth_test.go @@ -0,0 +1,217 @@ +package http + +import ( + "context" + "encoding/base64" + "io" + "net/http" + "strings" + "testing" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" +) + +const ( + basicChallenge = `Basic realm="messenger", charset="UTF-8"` + bearerChallenge = `Bearer realm="messenger"` +) + +func expectUnauthorized(t *testing.T, resp *http.Response, challenge string) { + t.Helper() + defer resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + data, _ := io.ReadAll(resp.Body) + t.Fatalf("expected 401, got %d; body=%s", resp.StatusCode, string(data)) + } + if got := resp.Header.Get("WWW-Authenticate"); got != challenge { + t.Fatalf("WWW-Authenticate = %q, want %q", got, challenge) + } + e := readError(t, resp) + if e.Error.Code != CodeUnauthorized || e.Error.RequestID == "" { + t.Fatalf("unexpected error body: %+v", e) + } +} + +func (r *testRig) withHeaders(method, path string, headers map[string]string) *http.Response { + r.t.Helper() + return r.do(method, path, "", headers, nil) +} + +func TestAuth_LoginReturnsSession(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("login_"+randomSuffix(), "Алиса") + + before := time.Now() + s := r.login(alice.Username, testPassword) + if s.TokenType != "Bearer" || len(s.Token) < 32 { + t.Fatalf("bad session: type=%q len(token)=%d", s.TokenType, len(s.Token)) + } + if s.User.ID != alice.ID || s.User.Username != alice.Username { + t.Fatalf("session user = %+v, want %s", s.User, alice.ID) + } + if strings.Contains(s.Token, alice.ID) || strings.Contains(s.Token, alice.Username) { + t.Fatal("token is derived from user identity") + } + if !s.ExpiresAt.After(before.Add(59*time.Minute)) || s.ExpiresAt.After(before.Add(61*time.Minute)) { + t.Fatalf("expires_at = %s, want ~now+1h", s.ExpiresAt) + } + + if again := r.login(alice.Username, testPassword); again.Token == s.Token { + t.Fatal("second login returned the same token") + } +} + +func TestAuth_LoginRejectsBadCredentialsUniformly(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("bad_"+randomSuffix(), "Алиса") + + expectUnauthorized(t, r.basicLogin(alice.Username, "wrong-password-123"), basicChallenge) + expectUnauthorized(t, r.basicLogin("nobody_"+randomSuffix(), testPassword), basicChallenge) + + b64 := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } + for _, h := range []string{ + "", + "Bearer " + b64(alice.Username+":"+testPassword), + "Basic not-base64!!!", + "Basic " + b64(alice.Username), + "Basic " + b64(alice.Username+":"), + "Basic " + b64(":"+testPassword), + "Basic " + b64(alice.Username+":\xff\xfe"), + } { + headers := map[string]string{} + if h != "" { + headers["Authorization"] = h + } + expectUnauthorized(t, r.withHeaders(http.MethodPost, "/api/v1/auth/sessions", headers), basicChallenge) + } +} + +func TestAuth_PasswordWithColonAndUnicode(t *testing.T) { + r := newTestRig(t) + username := "colon_" + randomSuffix() + pw := "пароль:с:двоеточиями🙂" + resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, DisplayName: "Двоеточие", Password: pw, + }) + expectStatus(t, resp, http.StatusCreated) + resp.Body.Close() + + r.login(username, pw) + expectUnauthorized(t, r.basicLogin(username, "пароль"), basicChallenge) +} + +func TestAuth_LoginRejectsBody(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("body_"+randomSuffix(), "Алиса") + req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", + strings.NewReader(`{"username":"`+alice.Username+`"}`)) + req.Header.Set("Content-Type", "application/json") + req.SetBasicAuth(alice.Username, testPassword) + resp, err := r.client.Do(req) + if err != nil { + t.Fatal(err) + } + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() +} + +func TestAuth_BearerRequired(t *testing.T) { + r := newTestRig(t) + alice, _, eve, _ := bootstrap(r) + + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", nil), bearerChallenge) + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", + map[string]string{"X-User-Id": alice.ID}), bearerChallenge) + basic := base64.StdEncoding.EncodeToString([]byte(alice.Username + ":" + testPassword)) + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", + map[string]string{"Authorization": "Basic " + basic}), bearerChallenge) + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", + map[string]string{"Authorization": "Bearer " + strings.Repeat("A", 43)}), bearerChallenge) + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", + map[string]string{"Authorization": "Bearer " + alice.ID}), bearerChallenge) + + resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, map[string]string{"X-User-Id": eve.ID}, nil) + expectStatus(t, resp, http.StatusOK) + var me dto.UserResponse + readJSON(t, resp, &me) + if me.ID != alice.ID { + t.Fatalf("X-User-Id overrode bearer identity: got %s", me.ID) + } + + tok := r.tokens[alice.ID] + resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "bearer " + tok}) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() +} + +func TestAuth_Logout(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("logout_"+randomSuffix(), "Алиса") + other := r.login(alice.Username, testPassword) + + resp := r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusNoContent) + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if len(body) != 0 { + t.Fatalf("204 with body %q", body) + } + + expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge) + expectUnauthorized(t, r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil), bearerChallenge) + + resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + other.Token}) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() +} + +func TestAuth_SessionExpires(t *testing.T) { + r := newRig(t, defaultTestLimits, session.NewMemory(), 2*time.Second) + alice := r.createUser("ttl_"+randomSuffix(), "Алиса") + + resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() + + time.Sleep(2100 * time.Millisecond) + expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge) +} + +type brokenSessions struct { + *session.Memory + down bool +} + +func (b *brokenSessions) Get(ctx context.Context, h []byte) (session.Session, error) { + if b.down { + return session.Session{}, domain.ErrUnavailable + } + return b.Memory.Get(ctx, h) +} + +func (b *brokenSessions) Save(ctx context.Context, h []byte, s session.Session) error { + if b.down { + return domain.ErrUnavailable + } + return b.Memory.Save(ctx, h, s) +} + +func TestAuth_SessionStoreDownIs503NotAnonymous(t *testing.T) { + store := &brokenSessions{Memory: session.NewMemory()} + r := newRig(t, defaultTestLimits, store, time.Hour) + alice := r.createUser("down_"+randomSuffix(), "Алиса") + store.down = true + + resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusServiceUnavailable) + if e := readError(t, resp); e.Error.Code != CodeUnavailable { + t.Fatalf("code = %q, want %q", e.Error.Code, CodeUnavailable) + } + + resp = r.basicLogin(alice.Username, testPassword) + expectStatus(t, resp, http.StatusServiceUnavailable) + resp.Body.Close() +} diff --git a/app/internal/api/http/chats.go b/app/internal/api/http/chats.go new file mode 100644 index 0000000..5deb7c2 --- /dev/null +++ b/app/internal/api/http/chats.go @@ -0,0 +1,103 @@ +package http + +import ( + "net/http" + "strconv" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +type chatsHandler struct { + chats service.ChatsService +} + +func (h *chatsHandler) create(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + var req dto.CreateChatRequest + if err := decodeJSON(c.Request().Body, &req); err != nil { + return WriteError(c, err) + } + + chat, err := h.chats.Create(c.Request().Context(), callerID, req.Title, req.MemberIDs) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, toChatResponse(chat)) +} + +func (h *chatsHandler) get(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + chatID := c.Param("chat_id") + + chat, err := h.chats.Get(c.Request().Context(), callerID, chatID) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toChatResponse(chat)) +} + +func (h *chatsHandler) list(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + limit, cursor, err := parsePageParams(c) + if err != nil { + return WriteError(c, err) + } + + page, err := h.chats.List(c.Request().Context(), callerID, cursor, limit) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toChatsPage(page)) +} + +func toChatResponse(ch domain.Chat) dto.ChatResponse { + members := make([]string, len(ch.MemberIDs)) + copy(members, ch.MemberIDs) + return dto.ChatResponse{ + ID: ch.ID, + Title: ch.Title, + MemberIDs: members, + CreatedAt: ch.CreatedAt, + } +} + +func toChatsPage(p domain.Page[domain.Chat]) dto.ChatsPageResponse { + items := make([]dto.ChatResponse, 0, len(p.Items)) + for _, ch := range p.Items { + items = append(items, toChatResponse(ch)) + } + var next *string + if p.NextCursor != "" { + s := p.NextCursor + next = &s + } + return dto.ChatsPageResponse{Items: items, NextCursor: next} +} + +func parsePageParams(c echo.Context) (int, string, error) { + q := c.QueryParams() + + limit := validate.LimitDefault + if vals, ok := q["limit"]; ok { + n, err := strconv.Atoi(vals[0]) + if err != nil { + return 0, "", &validate.Error{Field: "limit", Reason: "must be an integer"} + } + limit = n + } + + cursor := "" + if vals, ok := q["cursor"]; ok { + if vals[0] == "" { + return 0, "", &validate.Error{Field: "cursor", Reason: "must not be empty"} + } + cursor = vals[0] + } + return limit, cursor, nil +} diff --git a/app/internal/api/http/concurrency_test.go b/app/internal/api/http/concurrency_test.go new file mode 100644 index 0000000..8d3f3d1 --- /dev/null +++ b/app/internal/api/http/concurrency_test.go @@ -0,0 +1,84 @@ +package http + +import ( + "fmt" + "net/http" + "sync" + "testing" +) + +func TestConcurrency_100MessagesFrom10Clients(t *testing.T) { + const clients = 10 + const perClient = 10 + const total = clients * perClient + + r := newTestRig(t) + users := make([]testUser, clients) + memberIDs := make([]string, clients) + for i := range users { + users[i] = r.createUser(fmt.Sprintf("race_%02d_%s", i, randomSuffix()), fmt.Sprintf("Клиент %d", i)) + memberIDs[i] = users[i].ID + } + chat := r.createChat(users[0], "Гонка", memberIDs...) + + type result struct { + id, text string + err error + } + results := make(chan result, total) + start := make(chan struct{}) + var wg sync.WaitGroup + for i, actor := range users { + wg.Add(1) + go func() { + defer wg.Done() + <-start + for j := 0; j < perClient; j++ { + text := fmt.Sprintf("race-c%02d-m%02d", i, j) + status, msg, body := r.sendRaw(actor, chat.ID, mustJSON(map[string]string{"text": text})) + if status != http.StatusCreated { + results <- result{err: fmt.Errorf("%s: status %d: %s", text, status, body)} + continue + } + results <- result{id: msg.ID, text: msg.Text} + } + }() + } + close(start) + wg.Wait() + close(results) + + sentIDs := make(map[string]string, total) + for res := range results { + if res.err != nil { + t.Fatal(res.err) + } + if _, dup := sentIDs[res.id]; dup { + t.Fatalf("сервер выдал один id %s двум сообщениям", res.id) + } + sentIDs[res.id] = res.text + } + if len(sentIDs) != total { + t.Fatalf("подтверждено %d сообщений, ожидалось %d", len(sentIDs), total) + } + + history, _ := r.listMessages(users[0], chat.ID, 100) + if len(history) != total { + t.Fatalf("в истории %d сообщений, ожидалось ровно %d", len(history), total) + } + seen := make(map[string]struct{}, total) + for i, m := range history { + if _, dup := seen[m.ID]; dup { + t.Fatalf("id %s встречается в истории дважды", m.ID) + } + seen[m.ID] = struct{}{} + if text, ok := sentIDs[m.ID]; !ok || text != m.Text { + t.Fatalf("сообщение %s (%q) в истории не совпадает с подтверждённым", m.ID, m.Text) + } + if i > 0 && !history[i-1].CreatedAt.Before(m.CreatedAt) { + t.Fatalf("порядок (created_at) нарушен на индексе %d", i) + } + } + t.Logf("%d клиентов × %d сообщений = %d уникальных сообщений в истории, 0 дубликатов", + clients, perClient, total) +} diff --git a/app/internal/api/http/dto/chat.go b/app/internal/api/http/dto/chat.go new file mode 100644 index 0000000..32bfeb3 --- /dev/null +++ b/app/internal/api/http/dto/chat.go @@ -0,0 +1,20 @@ +package dto + +import "time" + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +type ChatResponse struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type ChatsPageResponse struct { + Items []ChatResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} diff --git a/app/internal/api/http/dto/message.go b/app/internal/api/http/dto/message.go new file mode 100644 index 0000000..720e0ac --- /dev/null +++ b/app/internal/api/http/dto/message.go @@ -0,0 +1,20 @@ +package dto + +import "time" + +type CreateMessageRequest struct { + Text string `json:"text"` +} + +type MessageResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt time.Time `json:"created_at"` +} + +type MessagesPageResponse struct { + Items []MessageResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} diff --git a/app/internal/api/http/dto/user.go b/app/internal/api/http/dto/user.go new file mode 100644 index 0000000..3122ade --- /dev/null +++ b/app/internal/api/http/dto/user.go @@ -0,0 +1,23 @@ +package dto + +import "time" + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` +} + +type UserResponse struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +type SessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User UserResponse `json:"user"` +} diff --git a/app/internal/api/http/errors.go b/app/internal/api/http/errors.go new file mode 100644 index 0000000..753c1d1 --- /dev/null +++ b/app/internal/api/http/errors.go @@ -0,0 +1,76 @@ +package http + +import ( + "errors" + "net/http" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" + "github.com/labstack/echo/v4" +) + +const ( + CodeInvalidRequest = "invalid_request" + CodeUnauthorized = "unauthorized" + CodeNotFound = "not_found" + CodeConflict = "conflict" + CodePayloadTooLarge = "payload_too_large" + CodeUnsupportedMedia = "unsupported_media_type" + CodeRateLimited = "rate_limited" + CodeUnavailable = "unavailable" + CodeInternalError = "internal_error" +) + +type errorBody struct { + Error errorPayload `json:"error"` +} + +type errorPayload struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +var ( + ErrUnauthorized = errors.New("unauthorized") + ErrUnsupportedMedia = errors.New("unsupported media type") +) + +func Classify(err error) (status int, code, message string) { + switch { + case errors.Is(err, domain.ErrNotFound): + return http.StatusNotFound, CodeNotFound, "Object not found" + case errors.Is(err, domain.ErrConflict): + return http.StatusConflict, CodeConflict, "Resource already exists" + case errors.Is(err, domain.ErrInvalidArgument): + return http.StatusBadRequest, CodeInvalidRequest, "Invalid request arguments" + case errors.Is(err, domain.ErrUnavailable): + return http.StatusServiceUnavailable, CodeUnavailable, "Service temporarily unavailable" + case errors.Is(err, domain.ErrPayloadTooLarge): + return http.StatusRequestEntityTooLarge, CodePayloadTooLarge, "Request body too large" + case errors.Is(err, domain.ErrRateLimited): + return http.StatusTooManyRequests, CodeRateLimited, "Too many concurrent requests" + case errors.Is(err, ErrUnauthorized), errors.Is(err, domain.ErrUnauthorized): + return http.StatusUnauthorized, CodeUnauthorized, "Identification required" + case errors.Is(err, ErrUnsupportedMedia): + return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected Content-Type: application/json" + } + + var vErr *validate.Error + if errors.As(err, &vErr) { + return http.StatusBadRequest, CodeInvalidRequest, vErr.Error() + } + + return http.StatusInternalServerError, CodeInternalError, "Internal server error" +} + +func WriteError(c echo.Context, err error) error { + status, code, msg := Classify(err) + return c.JSON(status, errorBody{ + Error: errorPayload{ + Code: code, + Message: msg, + RequestID: c.Response().Header().Get(echo.HeaderXRequestID), + }, + }) +} diff --git a/app/internal/api/http/health.go b/app/internal/api/http/health.go new file mode 100644 index 0000000..ae459ea --- /dev/null +++ b/app/internal/api/http/health.go @@ -0,0 +1,24 @@ +package http + +import ( + "net/http" + + "github.com/labstack/echo/v4" +) + +type healthResponse struct { + Status string `json:"status"` +} + +func healthLive(c echo.Context) error { + return c.JSON(http.StatusOK, healthResponse{Status: "ok"}) +} + +func healthReady(isReady func() bool) echo.HandlerFunc { + return func(c echo.Context) error { + if !isReady() { + return echo.NewHTTPError(http.StatusServiceUnavailable, "Service unavailable") + } + return c.JSON(http.StatusOK, healthResponse{Status: "ok"}) + } +} diff --git a/app/internal/api/http/helpers_test.go b/app/internal/api/http/helpers_test.go new file mode 100644 index 0000000..73def66 --- /dev/null +++ b/app/internal/api/http/helpers_test.go @@ -0,0 +1,328 @@ +package http + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +type testRig struct { + t *testing.T + server *httptest.Server + memory *store.Memory + sessions session.Store + client *http.Client + + mu sync.Mutex + tokens map[string]string +} + +func newTestRig(t *testing.T) *testRig { + return newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: 1 << 20, + MaxInFlight: 256, + MaxMessagesGlobal: 100000, + MaxHeapBytes: 1 << 40, + }) +} + +func newTestRigWithLimits(t *testing.T, limits config.Limits) *testRig { + t.Helper() + return newRig(t, limits, session.NewMemory(), time.Hour) +} + +var defaultTestLimits = config.Limits{ + MaxBodyBytes: 1 << 20, + MaxInFlight: 256, + MaxMessagesGlobal: 100000, + MaxHeapBytes: 1 << 40, +} + +func newRig(t *testing.T, limits config.Limits, sessions session.Store, ttl time.Duration) *testRig { + t.Helper() + cfg := &config.Config{ + Env: "test", + Version: "test", + HTTP: config.HTTP{ + Addr: "127.0.0.1:0", + ReadTimeoutMs: 10000, + WriteTimeoutMs: 10000, + IdleTimeoutMs: 60000, + ShutdownTimeoutMs: 1000, + }, + Limits: limits, + } + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + memory := store.NewWithLimit(limits.MaxMessagesGlobal) + hasher := password.NewHasher(testHashParams, 8) + auth, err := service.NewAuth(memory, sessions, hasher, ttl) + if err != nil { + t.Fatal(err) + } + srv := NewServer(Deps{ + Config: cfg, + Logger: logger, + Store: memory, + Auth: auth, + Users: service.NewUsers(memory, hasher), + Chats: service.NewChats(memory), + Messages: service.NewMessages(memory), + }) + ts := httptest.NewServer(srv.e) + t.Cleanup(ts.Close) + return &testRig{ + t: t, + server: ts, + memory: memory, + sessions: sessions, + client: &http.Client{Timeout: 10 * time.Second}, + tokens: make(map[string]string), + } +} + +type testUser struct { + ID string + Username string + DisplayName string +} + +type errorResp struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` + } `json:"error"` +} + +func (r *testRig) do(method, path string, actorID string, headers map[string]string, body io.Reader) *http.Response { + r.t.Helper() + req, err := http.NewRequest(method, r.server.URL+path, body) + if err != nil { + r.t.Fatalf("new request %s %s: %v", method, path, err) + } + req.Header.Set("Accept", "application/json") + r.setAuth(req, actorID) + for k, v := range headers { + req.Header.Set(k, v) + } + resp, err := r.client.Do(req) + if err != nil { + r.t.Fatalf("do %s %s: %v", method, path, err) + } + return resp +} + +func (r *testRig) doJSON(method, path string, actorID string, payload any) *http.Response { + r.t.Helper() + var body io.Reader + if payload != nil { + body = bytes.NewReader(mustJSON(payload)) + } + return r.do(method, path, actorID, map[string]string{"Content-Type": "application/json"}, body) +} + +func readJSON(t *testing.T, resp *http.Response, dst any) { + t.Helper() + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + if len(data) == 0 { + return + } + if err := json.Unmarshal(data, dst); err != nil { + t.Fatalf("decode body (%s): %v", string(data), err) + } +} + +func readError(t *testing.T, resp *http.Response) errorResp { + t.Helper() + var e errorResp + readJSON(t, resp, &e) + return e +} + +func expectStatus(t *testing.T, resp *http.Response, want int) { + t.Helper() + if resp.StatusCode != want { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("expected status %d, got %d; body=%s", want, resp.StatusCode, string(data)) + } +} + +const testPassword = "test-password-123" + +var testHashParams = password.Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32} + +func (r *testRig) createUser(username, displayName string) testUser { + r.t.Helper() + resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, + DisplayName: displayName, + Password: testPassword, + }) + expectStatus(r.t, resp, http.StatusCreated) + var u dto.UserResponse + readJSON(r.t, resp, &u) + s := r.login(username, testPassword) + r.mu.Lock() + r.tokens[u.ID] = s.Token + r.mu.Unlock() + return testUser{ID: u.ID, Username: u.Username, DisplayName: u.DisplayName} +} + +// login входит по Basic и возвращает сессию; ожидает 201. +func (r *testRig) login(username, pw string) dto.SessionResponse { + r.t.Helper() + resp := r.basicLogin(username, pw) + expectStatus(r.t, resp, http.StatusCreated) + var s dto.SessionResponse + readJSON(r.t, resp, &s) + return s +} + +func (r *testRig) basicLogin(username, pw string) *http.Response { + r.t.Helper() + req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", nil) + req.SetBasicAuth(username, pw) + resp, err := r.client.Do(req) + if err != nil { + r.t.Fatalf("login: %v", err) + } + return resp +} + +func (r *testRig) setAuth(req *http.Request, actorID string) { + if actorID == "" { + return + } + r.mu.Lock() + tok, ok := r.tokens[strings.ToLower(actorID)] + r.mu.Unlock() + if !ok { + tok = "unknown-" + actorID + } + req.Header.Set("Authorization", "Bearer "+tok) +} + +func (r *testRig) createChat(owner testUser, title string, members ...string) dto.ChatResponse { + r.t.Helper() + resp := r.doJSON(http.MethodPost, "/api/v1/chats", owner.ID, dto.CreateChatRequest{ + Title: title, + MemberIDs: members, + }) + expectStatus(r.t, resp, http.StatusCreated) + var ch dto.ChatResponse + readJSON(r.t, resp, &ch) + return ch +} + +func (r *testRig) sendMessage(actor testUser, chatID, text string) (*http.Response, dto.MessageResponse) { + r.t.Helper() + resp := r.doJSON(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID, dto.CreateMessageRequest{Text: text}) + if resp.StatusCode != http.StatusCreated { + return resp, dto.MessageResponse{} + } + var m dto.MessageResponse + readJSON(r.t, resp, &m) + return resp, m +} + +func (r *testRig) sendRaw(actor testUser, chatID string, body []byte) (int, dto.MessageResponse, []byte) { + r.t.Helper() + resp := r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID, + map[string]string{"Content-Type": "application/json"}, bytes.NewReader(body)) + defer resp.Body.Close() + data, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusCreated { + return resp.StatusCode, dto.MessageResponse{}, data + } + var m dto.MessageResponse + if err := json.Unmarshal(data, &m); err != nil { + r.t.Fatalf("decode message: %v", err) + } + return resp.StatusCode, m, data +} + +func (r *testRig) send(actor testUser, chatID, text string) (int, dto.MessageResponse) { + r.t.Helper() + status, msg, _ := r.sendRaw(actor, chatID, mustJSON(dto.CreateMessageRequest{Text: text})) + return status, msg +} + +func (r *testRig) listMessages(actor testUser, chatID string, pageSize int) ([]dto.MessageResponse, int) { + r.t.Helper() + collected := []dto.MessageResponse{} + cursor := "" + for pages := 1; ; pages++ { + q := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chatID, pageSize) + if cursor != "" { + q += "&cursor=" + url.QueryEscape(cursor) + } + resp := r.do(http.MethodGet, q, actor.ID, nil, nil) + expectStatus(r.t, resp, http.StatusOK) + var page dto.MessagesPageResponse + readJSON(r.t, resp, &page) + collected = append(collected, page.Items...) + if page.NextCursor == nil { + return collected, pages + } + cursor = *page.NextCursor + if pages > 100_000 { + r.t.Fatalf("пагинация не сходится: next_cursor не исчезает") + } + } +} + +func bootstrap(r *testRig) (alice, bob, eve testUser, chat dto.ChatResponse) { + alice = r.createUser("own_alice_"+randomSuffix(), "Алиса") + bob = r.createUser("own_bob_"+randomSuffix(), "Боб") + eve = r.createUser("own_eve_"+randomSuffix(), "Ева") + chat = r.createChat(alice, "Контрактный тест", alice.ID, bob.ID) + return +} + +var suffixMu sync.Mutex +var suffixSeq int + +func randomSuffix() string { + suffixMu.Lock() + defer suffixMu.Unlock() + suffixSeq++ + return fmt.Sprintf("%09d_%d", time.Now().UnixNano()%1_000_000_000, suffixSeq) +} + +func mustJSON(v any) []byte { + data, err := json.Marshal(v) + if err != nil { + panic(err) + } + return data +} + +func extractErrorCode(t *testing.T, data []byte) string { + t.Helper() + var e errorResp + if err := json.Unmarshal(data, &e); err != nil { + t.Fatalf("decode error body: %v; raw=%s", err, string(data)) + } + return e.Error.Code +} diff --git a/app/internal/api/http/limits_test.go b/app/internal/api/http/limits_test.go new file mode 100644 index 0000000..d8ef795 --- /dev/null +++ b/app/internal/api/http/limits_test.go @@ -0,0 +1,312 @@ +package http + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" +) + +func TestLimits_PayloadTooLarge(t *testing.T) { + r := newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: 256, + MaxInFlight: 16, + MaxMessagesGlobal: 100, + MaxHeapBytes: 1 << 40, + }) + alice := r.createUser("a_"+randomSuffix(), "Алиса") + bob := r.createUser("b_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + + ok, _, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "ok"})) + if ok != http.StatusCreated { + t.Fatalf("baseline send expected 201, got %d", ok) + } + stored := r.memory.MessagesTotal() + if stored != 1 { + t.Fatalf("baseline total expected 1, got %d", stored) + } + + big := strings.Repeat("x", 512) + status, _, body := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: big})) + if status != http.StatusRequestEntityTooLarge { + t.Fatalf("expected 413 by content-length, got %d body=%s", status, string(body)) + } + code := extractErrorCode(t, body) + if code != CodePayloadTooLarge { + t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code) + } + + if got := r.memory.MessagesTotal(); got != stored { + t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got) + } +} + +func TestLimits_PayloadBoundaries(t *testing.T) { + const limit = 256 + r := newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: limit, + MaxInFlight: 16, + MaxMessagesGlobal: 100, + MaxHeapBytes: 1 << 40, + }) + alice := r.createUser("a_"+randomSuffix(), "Алиса") + bob := r.createUser("b_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + + exact := []byte(`{"text":"` + strings.Repeat("x", limit-len(`{"text":""}`)) + `"}`) + if len(exact) != limit { + t.Fatalf("test bug: body is %d bytes, want %d", len(exact), limit) + } + + post := func(body io.Reader) (int, []byte) { + req, _ := http.NewRequest(http.MethodPost, + r.server.URL+"/api/v1/chats/"+chat.ID+"/messages", body) + req.Header.Set("Content-Type", "application/json") + r.setAuth(req, alice.ID) + resp, err := r.client.Do(req) + if err != nil { + t.Fatalf("send: %v", err) + } + defer resp.Body.Close() + data, _ := io.ReadAll(resp.Body) + return resp.StatusCode, data + } + chunked := func(b []byte) io.Reader { return io.MultiReader(bytes.NewReader(b)) } + + if status, body := post(bytes.NewReader(exact)); status != http.StatusCreated { + t.Fatalf("body ровно %d байт с Content-Length: expected 201, got %d body=%s", limit, status, body) + } + if status, body := post(chunked(exact)); status != http.StatusCreated { + t.Fatalf("body ровно %d байт без Content-Length: expected 201, got %d body=%s", limit, status, body) + } + stored := r.memory.MessagesTotal() + + over := []byte(`{"text":"` + strings.Repeat("x", limit) + `"}`) + status, body := post(chunked(over)) + if status != http.StatusRequestEntityTooLarge { + t.Fatalf("body %d байт без Content-Length: expected 413, got %d body=%s", len(over), status, body) + } + if code := extractErrorCode(t, body); code != CodePayloadTooLarge { + t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code) + } + if got := r.memory.MessagesTotal(); got != stored { + t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got) + } +} + +type slowSessions struct { + *session.Memory + delay atomic.Int64 +} + +func (s *slowSessions) Get(ctx context.Context, h []byte) (session.Session, error) { + time.Sleep(time.Duration(s.delay.Load())) + return s.Memory.Get(ctx, h) +} + +func TestLimits_RateLimited(t *testing.T) { + sessions := &slowSessions{Memory: session.NewMemory()} + r := newRig(t, config.Limits{ + MaxBodyBytes: 1 << 16, + MaxInFlight: 2, + MaxMessagesGlobal: 10000, + MaxHeapBytes: 1 << 40, + }, sessions, time.Hour) + alice := r.createUser("c_"+randomSuffix(), "Алиса") + bob := r.createUser("d_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + sessions.delay.Store(int64(20 * time.Millisecond)) + + const total = 50 + var ( + ok atomic.Int32 + throttled atomic.Int32 + errs atomic.Int32 + wg sync.WaitGroup + ) + wg.Add(total) + start := make(chan struct{}) + for i := 0; i < total; i++ { + i := i + go func() { + defer wg.Done() + <-start + client := &http.Client{Timeout: 10 * time.Second} + body, _ := json.Marshal(dto.CreateMessageRequest{Text: fmt.Sprintf("flood-%d", i)}) + req, _ := http.NewRequest(http.MethodPost, + r.server.URL+"/api/v1/chats/"+chat.ID+"/messages", + bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + r.setAuth(req, alice.ID) + resp, err := client.Do(req) + if err != nil { + errs.Add(1) + return + } + switch resp.StatusCode { + case http.StatusCreated: + ok.Add(1) + case http.StatusTooManyRequests: + throttled.Add(1) + default: + errs.Add(1) + } + resp.Body.Close() + }() + } + close(start) + wg.Wait() + sessions.delay.Store(0) + + if errs.Load() != 0 { + t.Fatalf("неожиданные ошибки/статусы под нагрузкой: %d", errs.Load()) + } + if throttled.Load() == 0 { + t.Fatalf("ожидался хотя бы один 429 при maxInFlight=2 и %d параллельных запросах", total) + } + if ok.Load() == 0 { + t.Fatalf("ни одного 201 — лимит не пропускает валидный трафик") + } + if int(ok.Load()+throttled.Load()) != total { + t.Fatalf("ok=%d throttled=%d не покрывают total=%d", ok.Load(), throttled.Load(), total) + } + + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + status, _ := r.send(alice, chat.ID, "после-пика "+randomSuffix()) + if status == http.StatusCreated { + break + } + time.Sleep(20 * time.Millisecond) + } + status, _ := r.send(alice, chat.ID, "после-пика-2 "+randomSuffix()) + if status != http.StatusCreated { + t.Fatalf("после отступления нагрузки сервис не восстановился: %d", status) + } + + collected, _ := r.listMessages(alice, chat.ID, 100) + if int32(len(collected)) < ok.Load() { + t.Fatalf("часть подтверждённых сообщений потеряна: подтверждено %d, в истории %d", + ok.Load(), len(collected)) + } + t.Logf("ok=%d throttled=%d errors=%d; history=%d", ok.Load(), throttled.Load(), errs.Load(), len(collected)) +} + +func TestLimits_MessageQuota(t *testing.T) { + const quota = 10 + r := newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: 1 << 16, + MaxInFlight: 16, + MaxMessagesGlobal: quota, + MaxHeapBytes: 1 << 40, + }) + alice := r.createUser("e_"+randomSuffix(), "Алиса") + bob := r.createUser("f_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + + var saved []string + for i := 0; i < quota; i++ { + status, msg := r.send(alice, chat.ID, fmt.Sprintf("saved-%02d", i)) + if status != http.StatusCreated { + t.Fatalf("send %d: expected 201, got %d", i, status) + } + saved = append(saved, msg.ID) + } + + status, _, body := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "overflow"})) + if status != http.StatusServiceUnavailable { + t.Fatalf("expected 503 after quota exhausted, got %d body=%s", status, string(body)) + } + if code := extractErrorCode(t, body); code != CodeUnavailable { + t.Fatalf("expected code %q, got %q", CodeUnavailable, code) + } + + collected, _ := r.listMessages(alice, chat.ID, 100) + if len(collected) != quota { + t.Fatalf("после 503 история чата %d, ожидалось %d", len(collected), quota) + } + gotIDs := make(map[string]struct{}, len(collected)) + for _, m := range collected { + gotIDs[m.ID] = struct{}{} + } + for _, id := range saved { + if _, ok := gotIDs[id]; !ok { + t.Fatalf("подтверждённое сообщение %s исчезло из истории", id) + } + } + + for i := 0; i < 5; i++ { + s, _, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "still-over"})) + if s != http.StatusServiceUnavailable { + t.Fatalf("повторный 503 ожидался, получен %d", s) + } + } + + req, _ := http.NewRequest(http.MethodGet, r.server.URL+"/health/live", nil) + resp, err := r.client.Do(req) + if err != nil { + t.Fatalf("health/live: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("health/live под перегрузкой: ожидали 200, получили %d", resp.StatusCode) + } +} + +func TestLimits_NoSilentLoss(t *testing.T) { + const quota = 20 + r := newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: 1 << 16, + MaxInFlight: 8, + MaxMessagesGlobal: quota, + MaxHeapBytes: 1 << 40, + }) + alice := r.createUser("g_"+randomSuffix(), "Алиса") + bob := r.createUser("h_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + + const attempts = quota * 3 + acked := make([]string, 0, quota) + codes := make(map[int]int) + for i := 0; i < attempts; i++ { + status, msg, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: fmt.Sprintf("loss-%03d", i)})) + codes[status]++ + if status == http.StatusCreated { + acked = append(acked, msg.ID) + } + } + if len(acked) != quota { + t.Fatalf("ожидалось ровно %d подтверждённых записей, получено %d; codes=%v", quota, len(acked), codes) + } + if codes[http.StatusServiceUnavailable] == 0 { + t.Fatalf("ни одного 503 — лимит не сработал") + } + + collected, _ := r.listMessages(alice, chat.ID, 100) + gotIDs := make(map[string]struct{}, len(collected)) + for _, m := range collected { + gotIDs[m.ID] = struct{}{} + } + for _, id := range acked { + if _, ok := gotIDs[id]; !ok { + t.Fatalf("подтверждённое сообщение %s исчезло из истории — незаметная потеря данных", id) + } + } + if len(collected) != len(acked) { + t.Fatalf("история чата содержит %d сообщений, подтверждено %d — скрытое отличие", + len(collected), len(acked)) + } + t.Logf("codes=%v acked=%d history=%d", codes, len(acked), len(collected)) +} diff --git a/app/internal/api/http/messages.go b/app/internal/api/http/messages.go new file mode 100644 index 0000000..a9aaeba --- /dev/null +++ b/app/internal/api/http/messages.go @@ -0,0 +1,71 @@ +package http + +import ( + "net/http" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" +) + +type messagesHandler struct { + messages service.MessagesService +} + +func (h *messagesHandler) send(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + chatID := c.Param("chat_id") + + var req dto.CreateMessageRequest + if err := decodeJSON(c.Request().Body, &req); err != nil { + return WriteError(c, err) + } + + msg, err := h.messages.Send(c.Request().Context(), callerID, chatID, req.Text) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, toMessageResponse(msg)) +} + +func (h *messagesHandler) list(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + chatID := c.Param("chat_id") + + limit, cursor, err := parsePageParams(c) + if err != nil { + return WriteError(c, err) + } + + page, err := h.messages.List(c.Request().Context(), callerID, chatID, cursor, limit) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toMessagesPage(page)) +} + +func toMessageResponse(m domain.Message) dto.MessageResponse { + return dto.MessageResponse{ + ID: m.ID, + ChatID: m.ChatID, + SenderID: m.AuthorID, + Text: m.Text, + CreatedAt: m.CreatedAt, + } +} + +func toMessagesPage(p domain.Page[domain.Message]) dto.MessagesPageResponse { + items := make([]dto.MessageResponse, 0, len(p.Items)) + for _, m := range p.Items { + items = append(items, toMessageResponse(m)) + } + var next *string + if p.NextCursor != "" { + s := p.NextCursor + next = &s + } + return dto.MessagesPageResponse{Items: items, NextCursor: next} +} diff --git a/app/internal/api/http/middleware/auth.go b/app/internal/api/http/middleware/auth.go new file mode 100644 index 0000000..9f6847c --- /dev/null +++ b/app/internal/api/http/middleware/auth.go @@ -0,0 +1,62 @@ +package middleware + +import ( + "context" + "errors" + "net/http" + "strings" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "github.com/labstack/echo/v4" +) + +const AuthTokenKey = "auth_token" + +const ( + BearerChallenge = `Bearer realm="messenger"` + BasicChallenge = `Basic realm="messenger", charset="UTF-8"` +) + +type Authenticator interface { + Authenticate(ctx context.Context, token string) (userID string, err error) +} + + +func Bearer(auth Authenticator) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + tok, ok := BearerToken(c.Request().Header.Get(echo.HeaderAuthorization)) + if !ok { + return unauthorized(c, BearerChallenge, "Bearer token required") + } + userID, err := auth.Authenticate(c.Request().Context(), tok) + if err != nil { + if errors.Is(err, domain.ErrUnauthorized) { + return unauthorized(c, BearerChallenge, "Invalid or expired session") + } + return err + } + c.Set(AuthUserIDKey, userID) + c.Set(AuthTokenKey, tok) + return next(c) + } + } +} + +func BearerToken(header string) (string, bool) { + scheme, tok, found := strings.Cut(header, " ") + if !found || !strings.EqualFold(scheme, "Bearer") { + return "", false + } + tok = strings.TrimSpace(tok) + return tok, tok != "" +} + +func unauthorized(c echo.Context, challenge, msg string) error { + c.Response().Header().Set(echo.HeaderWWWAuthenticate, challenge) + return echo.NewHTTPError(http.StatusUnauthorized, msg) +} + +func Unauthorized(c echo.Context, challenge, msg string) error { + return unauthorized(c, challenge, msg) +} diff --git a/app/internal/api/http/middleware/content_type.go b/app/internal/api/http/middleware/content_type.go new file mode 100644 index 0000000..dc6ef03 --- /dev/null +++ b/app/internal/api/http/middleware/content_type.go @@ -0,0 +1,42 @@ +package middleware + +import ( + "mime" + "net/http" + "strings" + + "github.com/labstack/echo/v4" +) + +func ContentType() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if !methodHasBody(c.Request().Method) { + return next(c) + } + if !isApplicationJSON(c.Request().Header.Get(echo.HeaderContentType)) { + return echo.NewHTTPError(http.StatusUnsupportedMediaType, "Expected Content-Type: application/json") + } + return next(c) + } + } +} + +func methodHasBody(method string) bool { + switch method { + case http.MethodPost, http.MethodPut, http.MethodPatch: + return true + } + return false +} + +func isApplicationJSON(ct string) bool { + if ct == "" { + return false + } + mediatype, _, err := mime.ParseMediaType(ct) + if err != nil { + return false + } + return strings.EqualFold(mediatype, "application/json") +} diff --git a/app/internal/api/http/middleware/limits.go b/app/internal/api/http/middleware/limits.go new file mode 100644 index 0000000..ae44790 --- /dev/null +++ b/app/internal/api/http/middleware/limits.go @@ -0,0 +1,110 @@ +package middleware + +import ( + "io" + "runtime" + "sync/atomic" + "time" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +func BodyLimit(maxBytes int64) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if !methodHasBody(c.Request().Method) { + return next(c) + } + if cl := c.Request().ContentLength; cl > maxBytes { + return domain.ErrPayloadTooLarge + } + c.Request().Body = &limitedBody{ + raw: c.Request().Body, + maxLeft: maxBytes, + } + return next(c) + } + } +} + +type limitedBody struct { + raw io.ReadCloser + maxLeft int64 +} + +func (b *limitedBody) Read(p []byte) (int, error) { + if int64(len(p)) > b.maxLeft+1 { + p = p[:b.maxLeft+1] + } + n, err := b.raw.Read(p) + b.maxLeft -= int64(n) + if b.maxLeft < 0 { + return n, domain.ErrPayloadTooLarge + } + return n, err +} + +func (b *limitedBody) Close() error { + return b.raw.Close() +} + +func InFlight(maxInFlight int) echo.MiddlewareFunc { + sem := make(chan struct{}, maxInFlight) + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if isHealthPath(c.Request().URL.Path) { + return next(c) + } + select { + case sem <- struct{}{}: + defer func() { <-sem }() + return next(c) + default: + return domain.ErrRateLimited + } + } + } +} + +func MemoryGuard(maxHeapBytes uint64, poll time.Duration) echo.MiddlewareFunc { + var sample atomic.Uint64 + + readOnce := func() { + var m runtime.MemStats + runtime.ReadMemStats(&m) + if m.HeapInuse > maxHeapBytes { + runtime.GC() + runtime.ReadMemStats(&m) + } + sample.Store(m.HeapInuse) + } + readOnce() + + if poll > 0 { + go func() { + t := time.NewTicker(poll) + defer t.Stop() + for range t.C { + readOnce() + } + }() + } + + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if !methodHasBody(c.Request().Method) || isHealthPath(c.Request().URL.Path) { + return next(c) + } + if sample.Load() > maxHeapBytes { + return domain.ErrUnavailable + } + return next(c) + } + } +} + +func isHealthPath(path string) bool { + return path == "/health/live" || path == "/health/ready" +} diff --git a/app/internal/api/http/middleware/logger.go b/app/internal/api/http/middleware/logger.go new file mode 100644 index 0000000..ed94ef1 --- /dev/null +++ b/app/internal/api/http/middleware/logger.go @@ -0,0 +1,48 @@ +package middleware + +import ( + "log/slog" + "time" + + "github.com/labstack/echo/v4" +) + +const AuthUserIDKey = "caller_id" + +func Logger(logger *slog.Logger) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + start := time.Now() + if err := next(c); err != nil { + c.Error(err) + } + status := c.Response().Status + + rid, _ := c.Get(RequestIDKey).(string) + uid, _ := c.Get(AuthUserIDKey).(string) + + attrs := []slog.Attr{ + slog.String("request_id", rid), + slog.String("method", c.Request().Method), + slog.String("path", c.Request().URL.Path), + slog.Int("status", status), + slog.Int64("duration_ms", time.Since(start).Milliseconds()), + slog.String("remote_ip", c.RealIP()), + } + if uid != "" { + attrs = append(attrs, slog.String("user_id", uid)) + } + + level := slog.LevelInfo + switch { + case status >= 500: + level = slog.LevelError + case status >= 400: + level = slog.LevelWarn + } + logger.LogAttrs(c.Request().Context(), level, "http request", attrs...) + + return nil + } + } +} diff --git a/app/internal/api/http/middleware/recover.go b/app/internal/api/http/middleware/recover.go new file mode 100644 index 0000000..862313d --- /dev/null +++ b/app/internal/api/http/middleware/recover.go @@ -0,0 +1,32 @@ +package middleware + +import ( + "log/slog" + "net/http" + "runtime/debug" + + "github.com/labstack/echo/v4" +) + +func Recover(logger *slog.Logger) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) (err error) { + defer func() { + r := recover() + if r == nil { + return + } + rid, _ := c.Get(RequestIDKey).(string) + logger.Error("panic recovered", + slog.String("request_id", rid), + slog.String("method", c.Request().Method), + slog.String("path", c.Request().URL.Path), + slog.Any("panic", r), + slog.String("stack", string(debug.Stack())), + ) + err = echo.NewHTTPError(http.StatusInternalServerError, "Internal server error") + }() + return next(c) + } + } +} diff --git a/app/internal/api/http/middleware/request_id.go b/app/internal/api/http/middleware/request_id.go new file mode 100644 index 0000000..6447646 --- /dev/null +++ b/app/internal/api/http/middleware/request_id.go @@ -0,0 +1,22 @@ +package middleware + +import ( + "github.com/google/uuid" + "github.com/labstack/echo/v4" +) + +const RequestIDKey = "request_id" + +func RequestID() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + rid := c.Request().Header.Get(echo.HeaderXRequestID) + if rid == "" { + rid = uuid.NewString() + } + c.Response().Header().Set(echo.HeaderXRequestID, rid) + c.Set(RequestIDKey, rid) + return next(c) + } + } +} diff --git a/app/internal/api/http/pagination_test.go b/app/internal/api/http/pagination_test.go new file mode 100644 index 0000000..cdd348a --- /dev/null +++ b/app/internal/api/http/pagination_test.go @@ -0,0 +1,89 @@ +package http + +import ( + "fmt" + "net/http" + "net/url" + "testing" +) + +func TestPagination_MultiPageWalk(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + + const total = 7 + var sentIDs []string + for i := 0; i < total; i++ { + actor := alice + if i%2 == 1 { + actor = bob + } + _, msg := r.sendMessage(actor, chat.ID, fmt.Sprintf("page-%02d", i)) + if msg.ID == "" { + t.Fatalf("send message %d failed", i) + } + sentIDs = append(sentIDs, msg.ID) + } + + history, pages := r.listMessages(alice, chat.ID, 3) + if pages != 3 { + t.Fatalf("ожидалось 3 страницы (3+3+1), получено %d", pages) + } + if len(history) != total { + t.Fatalf("собрано %d сообщений, ожидалось %d", len(history), total) + } + for i, m := range history { + if m.ID != sentIDs[i] { + t.Fatalf("позиция %d: ожидался %s, получен %s (повтор, пропуск или нарушен порядок)", i, sentIDs[i], m.ID) + } + } +} + +func TestPagination_ExactPageAndEmptyChat(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + + history, pages := r.listMessages(alice, chat.ID, 5) + if len(history) != 0 || pages != 1 { + t.Fatalf("пустой чат: items=%d pages=%d", len(history), pages) + } + + for i := 0; i < 4; i++ { + r.send(alice, chat.ID, fmt.Sprintf("m%d", i)) + } + if _, pages := r.listMessages(alice, chat.ID, 4); pages != 1 { + t.Fatalf("4 сообщения при limit=4: ожидалась 1 страница, получено %d", pages) + } + if _, pages := r.listMessages(alice, chat.ID, 2); pages != 2 { + t.Fatalf("4 сообщения при limit=2: ожидалось 2 страницы, получено %d", pages) + } +} + +func TestPagination_CursorBoundToChat(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + other := r.createChat(alice, "Другой", alice.ID, bob.ID) + for i := 0; i < 3; i++ { + r.send(alice, chat.ID, fmt.Sprintf("m%d", i)) + } + + resp := r.do(http.MethodGet, "/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + var page struct { + NextCursor *string `json:"next_cursor"` + } + readJSON(t, resp, &page) + if page.NextCursor == nil { + t.Fatal("ожидался next_cursor") + } + + for _, path := range []string{ + "/api/v1/chats/" + other.ID + "/messages?cursor=" + url.QueryEscape(*page.NextCursor), + "/api/v1/chats?cursor=" + url.QueryEscape(*page.NextCursor), + "/api/v1/chats/" + chat.ID + "/messages?cursor=not-a-cursor", + } { + resp := r.do(http.MethodGet, path, alice.ID, nil, nil) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() + } +} diff --git a/app/internal/api/http/router.go b/app/internal/api/http/router.go new file mode 100644 index 0000000..a658959 --- /dev/null +++ b/app/internal/api/http/router.go @@ -0,0 +1,32 @@ +package http + +import ( + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" +) + +func registerRoutes(e *echo.Echo, d Deps, isReady func() bool) { + e.GET("/health/live", healthLive) + e.GET("/health/ready", healthReady(isReady)) + + usersH := &usersHandler{users: d.Users} + chatsH := &chatsHandler{chats: d.Chats} + messagesH := &messagesHandler{messages: d.Messages} + authH := &authHandler{auth: d.Auth} + + auth := middleware.Bearer(d.Auth) + + jsonBody := middleware.ContentType() + + v1 := e.Group("/api/v1") + v1.POST("/users", usersH.create, jsonBody) + v1.POST("/auth/sessions", authH.createSession) + v1.DELETE("/auth/sessions/current", authH.revokeSession, auth) + v1.GET("/users/me", usersH.me, auth) + v1.POST("/chats", chatsH.create, auth, jsonBody) + v1.GET("/chats", chatsH.list, auth) + v1.GET("/chats/:chat_id", chatsH.get, auth) + v1.POST("/chats/:chat_id/messages", messagesH.send, auth, jsonBody) + v1.GET("/chats/:chat_id/messages", messagesH.list, auth) +} diff --git a/app/internal/api/http/server.go b/app/internal/api/http/server.go new file mode 100644 index 0000000..8a3f90a --- /dev/null +++ b/app/internal/api/http/server.go @@ -0,0 +1,165 @@ +package http + +import ( + "context" + "errors" + "log/slog" + nethttp "net/http" + "sync/atomic" + "time" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +type Deps struct { + Config *config.Config + Logger *slog.Logger + Store store.Store + Auth service.AuthService + Users service.UsersService + Chats service.ChatsService + Messages service.MessagesService + + + Ready func(ctx context.Context) error +} + +type Server struct { + e *echo.Echo + cfg config.HTTP + logger *slog.Logger + shutting atomic.Bool + ready func(ctx context.Context) error +} + +func NewServer(d Deps) *Server { + s := &Server{ + e: echo.New(), + cfg: d.Config.HTTP, + logger: d.Logger, + ready: d.Ready, + } + + s.e.HideBanner = true + s.e.HidePort = true + s.e.HTTPErrorHandler = s.httpErrorHandler + + s.e.Server.ReadTimeout = time.Duration(s.cfg.ReadTimeoutMs) * time.Millisecond + s.e.Server.WriteTimeout = time.Duration(s.cfg.WriteTimeoutMs) * time.Millisecond + s.e.Server.IdleTimeout = time.Duration(s.cfg.IdleTimeoutMs) * time.Millisecond + + s.e.Use(middleware.Recover(d.Logger)) + s.e.Use(middleware.RequestID()) + s.e.Use(middleware.Logger(d.Logger)) + s.e.Use(middleware.InFlight(d.Config.Limits.MaxInFlight)) + s.e.Use(middleware.BodyLimit(d.Config.Limits.MaxBodyBytes)) + s.e.Use(middleware.MemoryGuard(d.Config.Limits.MaxHeapBytes, 100*time.Millisecond)) + + registerRoutes(s.e, d, s.IsReady) + return s +} + +func (s *Server) Start() error { + s.logger.Info("http server starting", slog.String("addr", s.cfg.Addr)) + err := s.e.Start(s.cfg.Addr) + if errors.Is(err, nethttp.ErrServerClosed) { + return nil + } + return err +} + +func (s *Server) Shutdown(ctx context.Context) error { + s.shutting.Store(true) + s.logger.Info("http server shutting down") + return s.e.Shutdown(ctx) +} + +func (s *Server) IsReady() bool { + if s.shutting.Load() { + return false + } + if s.ready == nil { + return true + } + ctx, cancel := context.WithTimeout(context.Background(), readyTimeout) + defer cancel() + return s.ready(ctx) == nil +} + +const readyTimeout = time.Second + +func (s *Server) Handler() nethttp.Handler { + return s.e +} + +func (s *Server) httpErrorHandler(err error, c echo.Context) { + if c.Response().Committed { + return + } + + var httpErr *echo.HTTPError + if errors.As(err, &httpErr) { + code := codeFromStatus(httpErr.Code) + msg, _ := httpErr.Message.(string) + if msg == "" || msg == nethttp.StatusText(httpErr.Code) { + msg = messageFor(httpErr.Code, code) + } + _ = c.JSON(httpErr.Code, errorBody{ + Error: errorPayload{ + Code: code, + Message: msg, + RequestID: c.Response().Header().Get(echo.HeaderXRequestID), + }, + }) + return + } + + _ = WriteError(c, err) +} + +var codesByStatus = map[int]string{ + nethttp.StatusBadRequest: CodeInvalidRequest, + nethttp.StatusUnauthorized: CodeUnauthorized, + nethttp.StatusNotFound: CodeNotFound, + nethttp.StatusMethodNotAllowed: CodeInvalidRequest, + nethttp.StatusConflict: CodeConflict, + nethttp.StatusRequestEntityTooLarge: CodePayloadTooLarge, + nethttp.StatusUnsupportedMediaType: CodeUnsupportedMedia, + nethttp.StatusTooManyRequests: CodeRateLimited, + nethttp.StatusServiceUnavailable: CodeUnavailable, +} + +func codeFromStatus(status int) string { + if c, ok := codesByStatus[status]; ok { + return c + } + return CodeInternalError +} + +var messagesByStatus = map[int]string{ + nethttp.StatusMethodNotAllowed: "Method not allowed", +} + +func messageFor(status int, code string) string { + if m, ok := messagesByStatus[status]; ok { + return m + } + return defaultMessages[code] +} + +var defaultMessages = map[string]string{ + CodeInvalidRequest: "Invalid request", + CodeUnauthorized: "Identification required", + CodeNotFound: "Object not found", + CodeConflict: "Conflict", + CodePayloadTooLarge: "Request body too large", + CodeUnsupportedMedia: "Unsupported Content-Type", + CodeRateLimited: "Too many requests", + CodeUnavailable: "Service unavailable", + CodeInternalError: "Internal server error", +} diff --git a/app/internal/api/http/users.go b/app/internal/api/http/users.go new file mode 100644 index 0000000..8be6655 --- /dev/null +++ b/app/internal/api/http/users.go @@ -0,0 +1,114 @@ +package http + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "reflect" + "strings" + "unicode/utf8" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +type usersHandler struct { + users service.UsersService +} + +func (h *usersHandler) create(c echo.Context) error { + var req dto.CreateUserRequest + if err := decodeJSON(c.Request().Body, &req); err != nil { + return WriteError(c, err) + } + + user, err := h.users.Register(c.Request().Context(), req.Username, req.DisplayName, req.Password) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, toUserResponse(user)) +} + +func (h *usersHandler) me(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + user, err := h.users.Me(c.Request().Context(), callerID) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toUserResponse(user)) +} + +func toUserResponse(u domain.User) dto.UserResponse { + return dto.UserResponse{ + ID: u.ID, + Username: u.Username, + DisplayName: u.DisplayName, + CreatedAt: u.CreatedAt, + } +} + +func decodeJSON(body io.Reader, dst any) error { + data, err := io.ReadAll(body) + if err != nil { + if errors.Is(err, domain.ErrPayloadTooLarge) { + return err + } + return &validate.Error{Field: "body", Reason: "cannot read body"} + } + if !utf8.Valid(data) { + return &validate.Error{Field: "body", Reason: "invalid UTF-8"} + } + dec := json.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return &validate.Error{Field: "body", Reason: jsonErrorReason(err)} + } + if dec.More() { + return &validate.Error{Field: "body", Reason: "unexpected data after JSON object"} + } + return checkExactKeys(data, dst) +} + +func checkExactKeys(data []byte, dst any) error { + var obj map[string]json.RawMessage + if err := json.Unmarshal(data, &obj); err != nil { + return nil + } + allowed := make(map[string]struct{}) + t := reflect.TypeOf(dst).Elem() + for i := 0; i < t.NumField(); i++ { + name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",") + allowed[name] = struct{}{} + } + for key := range obj { + if _, ok := allowed[key]; !ok { + return &validate.Error{Field: "body", Reason: fmt.Sprintf("unknown field %q", key)} + } + } + return nil +} + +func jsonErrorReason(err error) string { + if errors.Is(err, io.EOF) { + return "empty body" + } + var typeErr *json.UnmarshalTypeError + if errors.As(err, &typeErr) { + if typeErr.Field == "" { + return "expected a JSON object" + } + return fmt.Sprintf("field %q: invalid type", typeErr.Field) + } + if name, ok := strings.CutPrefix(err.Error(), "json: unknown field "); ok { + return "unknown field " + name + } + return "invalid JSON" +} diff --git a/app/internal/api/http/validation_test.go b/app/internal/api/http/validation_test.go new file mode 100644 index 0000000..8169227 --- /dev/null +++ b/app/internal/api/http/validation_test.go @@ -0,0 +1,225 @@ +package http + +import ( + "bytes" + "io" + "net/http" + "strings" + "testing" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" +) + +func TestValidation_InvalidJSON(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + path := "/api/v1/chats/" + chat.ID + "/messages" + + bad := [][]byte{ + []byte(`{"text":`), + []byte(`not json at all`), + []byte(`{"text": 123,}`), + []byte(``), + []byte(`{"text": "ok"}{"text":"bonus"}`), + []byte("{\"text\":\"\xff\xfe bad utf8\"}"), + } + for _, payload := range bad { + resp := r.do(http.MethodPost, path, alice.ID, + map[string]string{"Content-Type": "application/json"}, + bytes.NewReader(payload)) + if resp.StatusCode != http.StatusBadRequest { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("payload %q: expected 400, got %d; body=%s", payload, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Code != CodeInvalidRequest { + t.Fatalf("payload %q: expected code %q, got %q", payload, CodeInvalidRequest, e.Error.Code) + } + if e.Error.RequestID == "" { + t.Fatalf("payload %q: missing request_id in body", payload) + } + } +} + +func TestValidation_InvalidUTF8(t *testing.T) { + r := newTestRig(t) + alice, bob, _, _ := bootstrap(r) + + cases := []struct { + path, actor string + payload []byte + }{ + {"/api/v1/users", "", []byte("{\"username\":\"u_" + randomSuffix()[:8] + "\",\"display_name\":\"\xc3\x28\"}")}, + {"/api/v1/chats", alice.ID, []byte("{\"title\":\"\xe2\x82\",\"member_ids\":[\"" + alice.ID + "\",\"" + bob.ID + "\"]}")}, + } + for _, tc := range cases { + resp := r.do(http.MethodPost, tc.path, tc.actor, + map[string]string{"Content-Type": "application/json"}, + bytes.NewReader(tc.payload)) + if resp.StatusCode != http.StatusBadRequest { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("%s %q: expected 400, got %d; body=%s", tc.path, tc.payload, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Code != CodeInvalidRequest { + t.Fatalf("%s: expected code %q, got %q", tc.path, CodeInvalidRequest, e.Error.Code) + } + } +} + +func TestValidation_JSONKeysAreCaseSensitive(t *testing.T) { + r := newTestRig(t) + resp := r.do(http.MethodPost, "/api/v1/users", "", + map[string]string{"Content-Type": "application/json"}, + strings.NewReader(`{"USERNAME":"case_bob","Display_Name":"B"}`)) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() +} + +func TestValidation_ErrorMessages(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + msgs := "/api/v1/chats/" + chat.ID + "/messages" + + cases := []struct { + method, path, actor, body, message string + }{ + {http.MethodPost, "/api/v1/users", "", `{"username":"ab","display_name":"x"}`, + "username: must match [a-z0-9_]{3,32}"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc_` + randomSuffix()[:6] + `","display_name":" "}`, + "display_name: must not be empty or whitespace only"}, + {http.MethodPost, "/api/v1/users", "", `{"username":123,"display_name":"x"}`, + `body: field "username": invalid type`}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"p"}`, + "password: length must be in [12, 128] code points"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}`, + "password: must not be empty or whitespace only"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"` + strings.Repeat("я", 129) + `"}`, + "password: length must be in [12, 128] code points"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"long-enough-pw","password_hash":"h"}`, + `body: unknown field "password_hash"`}, + {http.MethodPost, "/api/v1/users", "", `{"username":`, "body: invalid JSON"}, + {http.MethodPost, "/api/v1/users", "", ``, "body: empty body"}, + {http.MethodPost, "/api/v1/users", "", `[]`, "body: expected a JSON object"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"} {}`, "body: unexpected data after JSON object"}, + {http.MethodPost, "/api/v1/users", "", "{\"username\":\"abc\",\"display_name\":\"\xff\"}", + "body: invalid UTF-8"}, + {http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + bob.ID + `"]}`, + "member_ids: must contain caller"}, + {http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + alice.ID + `","x"]}`, + "member_ids[1]: must be a valid UUID"}, + {http.MethodPost, msgs, alice.ID, `{"text":" "}`, "text: must not be empty or whitespace only"}, + {http.MethodGet, msgs + "?limit=abc", alice.ID, "", "limit: must be an integer"}, + {http.MethodGet, msgs + "?limit=0", alice.ID, "", "limit: must be in [1, 100]"}, + {http.MethodGet, msgs + "?limit=", alice.ID, "", "limit: must be an integer"}, + {http.MethodGet, msgs + "?cursor=", alice.ID, "", "cursor: must not be empty"}, + {http.MethodGet, msgs + "?limit=10&cursor=", alice.ID, "", "cursor: must not be empty"}, + {http.MethodGet, "/api/v1/chats?limit=", alice.ID, "", "limit: must be an integer"}, + {http.MethodGet, "/api/v1/chats?cursor=", alice.ID, "", "cursor: must not be empty"}, + } + for _, tc := range cases { + headers := map[string]string{} + var body io.Reader + if tc.method == http.MethodPost { + headers["Content-Type"] = "application/json" + body = bytes.NewReader([]byte(tc.body)) + } + resp := r.do(tc.method, tc.path, tc.actor, headers, body) + if resp.StatusCode != http.StatusBadRequest { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("%s %s %q: expected 400, got %d; body=%s", tc.method, tc.path, tc.body, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Message != tc.message { + t.Fatalf("%s %s %q:\n want %q\n got %q", tc.method, tc.path, tc.body, tc.message, e.Error.Message) + } + } +} + +func TestValidation_EmptyMessage(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + path := "/api/v1/chats/" + chat.ID + "/messages" + + for _, text := range []string{"", " ", "\n\t "} { + resp := r.doJSON(http.MethodPost, path, alice.ID, dto.CreateMessageRequest{Text: text}) + if resp.StatusCode != http.StatusBadRequest { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("text %q: expected 400, got %d; body=%s", text, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Code != CodeInvalidRequest { + t.Fatalf("text %q: expected code %q, got %q", text, CodeInvalidRequest, e.Error.Code) + } + } +} + +func TestValidation_DuplicateUsername(t *testing.T) { + r := newTestRig(t) + username := "own_dup_" + randomSuffix() + + first := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, + DisplayName: "Первый", + Password: testPassword, + }) + expectStatus(t, first, http.StatusCreated) + first.Body.Close() + + second := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, + DisplayName: "Второй", + Password: testPassword, + }) + if second.StatusCode != http.StatusConflict { + data, _ := io.ReadAll(second.Body) + second.Body.Close() + t.Fatalf("second POST same username: expected 409, got %d; body=%s", second.StatusCode, string(data)) + } + e := readError(t, second) + if e.Error.Code != CodeConflict { + t.Fatalf("expected code %q, got %q", CodeConflict, e.Error.Code) + } + + third := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, + DisplayName: "Первый", + Password: testPassword, + }) + if third.StatusCode != http.StatusConflict { + data, _ := io.ReadAll(third.Body) + third.Body.Close() + t.Fatalf("third POST same username/display_name: expected 409, got %d; body=%s", third.StatusCode, string(data)) + } + third.Body.Close() +} + +func TestValidation_UUIDForms(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + upper := strings.ToUpper(alice.ID) + + resp := r.do(http.MethodGet, "/api/v1/users/me", upper, nil, nil) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() + resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ToUpper(chat.ID), alice.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() + + resp = r.do(http.MethodGet, "/api/v1/users/me", "{"+alice.ID+"}", nil, nil) + expectStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ReplaceAll(chat.ID, "-", ""), alice.ID, nil, nil) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() + + resp = r.doJSON(http.MethodPost, "/api/v1/chats", alice.ID, map[string]any{ + "title": "dup", "member_ids": []string{alice.ID, upper, bob.ID}, + }) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() +} diff --git a/app/internal/cache/history.go b/app/internal/cache/history.go new file mode 100644 index 0000000..0d6d526 --- /dev/null +++ b/app/internal/cache/history.go @@ -0,0 +1,396 @@ +package cache + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/redis/go-redis/v9" + "golang.org/x/sync/singleflight" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +const ( + ModeOff = "off" + ModeNaive = "naive" + ModeSafe = "safe" +) + +type Source interface { + store.MessageStore + IsMember(ctx context.Context, chatID, userID string) (bool, error) + HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) +} + +type Options struct { + Mode string + PageTTL time.Duration + LockTTL time.Duration + FillDelay time.Duration + Logger *slog.Logger +} + +var _ store.MessageStore = (*Messages)(nil) + +type Messages struct { + src Source + rdb *redis.Client + opt Options + group singleflight.Group + log *slog.Logger + + downUntil atomic.Int64 + + mu sync.Mutex + pending map[string]struct{} + stop chan struct{} + done chan struct{} +} + +const ( + memberTTL = 24 * time.Hour + versionTTL = 24 * time.Hour + breakerPause = time.Second + retryInterval = 200 * time.Millisecond + pollInterval = 5 * time.Millisecond + defaultPageTTL = 30 * time.Second + defaultLockTTL = 500 * time.Millisecond +) + +func New(src Source, rdb *redis.Client, opt Options) *Messages { + if opt.PageTTL <= 0 { + opt.PageTTL = defaultPageTTL + } + if opt.LockTTL <= 0 { + opt.LockTTL = defaultLockTTL + } + if opt.Logger == nil { + opt.Logger = slog.Default() + } + m := &Messages{ + src: src, + rdb: rdb, + opt: opt, + log: opt.Logger, + pending: make(map[string]struct{}), + stop: make(chan struct{}), + done: make(chan struct{}), + } + go m.retryLoop() + return m +} + +func Connect(cfg config.HistoryCache) (*redis.Client, error) { + url := cfg.URL + if cfg.URLFile != "" { + b, err := os.ReadFile(cfg.URLFile) + if err != nil { + return nil, fmt.Errorf("cache: read HISTORY_CACHE_URL_FILE: %w", err) + } + url = strings.TrimSpace(string(b)) + } + if url == "" { + return nil, errors.New("cache: HISTORY_CACHE_URL_FILE or HISTORY_CACHE_URL is required unless HISTORY_CACHE=off") + } + opts, err := redis.ParseURL(url) + if err != nil { + return nil, errors.New("cache: invalid HISTORY_CACHE_URL") + } + timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond + opts.PoolSize = cfg.PoolSize + opts.DialTimeout = timeout + opts.ReadTimeout = timeout + opts.WriteTimeout = timeout + opts.PoolTimeout = timeout + opts.MaxRetries = -1 // без повторов: промах кэша дешевле ожидания + return redis.NewClient(opts), nil +} + +func (m *Messages) Close() { + close(m.stop) + <-m.done +} + +func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, text string) (domain.Message, error) { + msg, err := m.src.AddMessage(ctx, callerID, chatID, text) + if err != nil { + return msg, err + } + ictx := context.WithoutCancel(ctx) + switch m.opt.Mode { + case ModeNaive: + m.naiveInvalidate(ictx, chatID) + case ModeSafe: + if err := m.rdb.Del(ictx, verKey(chatID)).Err(); err != nil { + m.markDown(err) + m.addPending(chatID) + } + } + return msg, nil +} + +func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + if m.opt.Mode == ModeOff || m.bypass(chatID) { + return m.src.ListMessages(ctx, callerID, chatID, cursor, limit) + } + if err := m.checkMember(ctx, chatID, callerID); err != nil { + return domain.Page[domain.Message]{}, err + } + if m.opt.Mode == ModeNaive { + return m.naiveList(ctx, chatID, cursor, limit) + } + return m.safeList(ctx, chatID, cursor, limit) +} + +func (m *Messages) checkMember(ctx context.Context, chatID, userID string) error { + key := "hc:member:" + chatID + ":" + userID + if !m.isDown() { + v, err := m.rdb.Get(ctx, key).Result() + if err == nil && v == "1" { + return nil + } + m.markDown(err) + } + ok, err := m.src.IsMember(ctx, chatID, userID) + if err != nil { + return err + } + if !ok { + // Отрицательный ответ не кэшируем. + return domain.ErrNotFound + } + if !m.isDown() { + m.markDown(m.rdb.Set(ctx, key, "1", memberTTL).Err()) + } + return nil +} + +func (m *Messages) naiveList(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + key := pageKey("hc:naive:"+chatID, cursor, limit) + if page, ok := m.getPage(ctx, key); ok { + return page, nil + } + page, err := m.src.HistoryPage(ctx, chatID, cursor, limit) + if err != nil { + return page, err + } + m.sleepFill(ctx) + if b, err := encodePage(page); err == nil { + setKey := "hc:naive:keys:" + chatID + _, err := m.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { + p.Set(ctx, key, b, m.opt.PageTTL) + p.SAdd(ctx, setKey, key) + p.Expire(ctx, setKey, m.opt.PageTTL) + return nil + }) + m.markDown(err) + } + return page, nil +} + +func (m *Messages) naiveInvalidate(ctx context.Context, chatID string) { + setKey := "hc:naive:keys:" + chatID + keys, err := m.rdb.SMembers(ctx, setKey).Result() + if err != nil { + m.markDown(err) + return + } + m.markDown(m.rdb.Del(ctx, append(keys, setKey)...).Err()) +} + +func (m *Messages) safeList(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + ver, err := m.version(ctx, chatID) + if err != nil { + m.markDown(err) + return m.src.HistoryPage(ctx, chatID, cursor, limit) + } + key := pageKey("hc:page:"+chatID+":"+ver, cursor, limit) + if page, ok := m.getPage(ctx, key); ok { + return page, nil + } + v, err, _ := m.group.Do(key, func() (any, error) { + return m.fill(context.WithoutCancel(ctx), key, chatID, cursor, limit) + }) + if err != nil { + return domain.Page[domain.Message]{}, err + } + return v.(domain.Page[domain.Message]), nil +} + +func (m *Messages) version(ctx context.Context, chatID string) (string, error) { + key := verKey(chatID) + v, err := m.rdb.Get(ctx, key).Result() + if err == nil { + return v, nil + } + if !errors.Is(err, redis.Nil) { + return "", err + } + fresh := randomVersion() + old, err := m.rdb.SetArgs(ctx, key, fresh, redis.SetArgs{Mode: "NX", Get: true, TTL: versionTTL}).Result() + if errors.Is(err, redis.Nil) { + return fresh, nil + } + if err != nil { + return "", err + } + return old, nil +} + +var unlockScript = redis.NewScript(` +if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) end +return 0`) + +func (m *Messages) fill(ctx context.Context, key, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + lockKey := "hc:lock:" + key + token := randomVersion() + locked, err := m.rdb.SetNX(ctx, lockKey, token, m.opt.LockTTL).Result() + if err != nil { + m.markDown(err) + return m.src.HistoryPage(ctx, chatID, cursor, limit) + } + if !locked { + deadline := time.Now().Add(m.opt.LockTTL) + for time.Now().Before(deadline) { + time.Sleep(pollInterval) + if page, ok := m.getPage(ctx, key); ok { + return page, nil + } + } + return m.src.HistoryPage(ctx, chatID, cursor, limit) + } + defer unlockScript.Run(ctx, m.rdb, []string{lockKey}, token) + + page, err := m.src.HistoryPage(ctx, chatID, cursor, limit) + if err != nil { + return page, err + } + m.sleepFill(ctx) + if b, err := encodePage(page); err == nil { + m.markDown(m.rdb.Set(ctx, key, b, m.opt.PageTTL).Err()) + } + return page, nil +} + +func (m *Messages) addPending(chatID string) { + m.mu.Lock() + m.pending[chatID] = struct{}{} + m.mu.Unlock() + m.log.Warn("history cache invalidation deferred", slog.String("chat_id", chatID)) +} + +func (m *Messages) bypass(chatID string) bool { + if m.isDown() { + return true + } + m.mu.Lock() + _, ok := m.pending[chatID] + m.mu.Unlock() + return ok +} + +func (m *Messages) retryLoop() { + defer close(m.done) + t := time.NewTicker(retryInterval) + defer t.Stop() + for { + select { + case <-m.stop: + return + case <-t.C: + } + m.mu.Lock() + chats := make([]string, 0, len(m.pending)) + for id := range m.pending { + chats = append(chats, id) + } + m.mu.Unlock() + for _, id := range chats { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + err := m.rdb.Del(ctx, verKey(id)).Err() + cancel() + if err != nil { + break + } + m.mu.Lock() + delete(m.pending, id) + m.mu.Unlock() + } + } +} + +func (m *Messages) isDown() bool { + return time.Now().UnixNano() < m.downUntil.Load() +} + +func (m *Messages) markDown(err error) { + if err == nil || errors.Is(err, redis.Nil) { + return + } + if !m.isDown() { + m.log.Warn("history cache unavailable, bypassing", slog.Any("err", err)) + } + m.downUntil.Store(time.Now().Add(breakerPause).UnixNano()) +} + +func (m *Messages) getPage(ctx context.Context, key string) (domain.Page[domain.Message], bool) { + b, err := m.rdb.Get(ctx, key).Bytes() + if err != nil { + m.markDown(err) + return domain.Page[domain.Message]{}, false + } + page, err := decodePage(b) + return page, err == nil +} + +func (m *Messages) sleepFill(ctx context.Context) { + if m.opt.FillDelay <= 0 { + return + } + select { + case <-time.After(m.opt.FillDelay): + case <-ctx.Done(): + } +} + +func verKey(chatID string) string { return "hc:ver:" + chatID } + +func pageKey(prefix, cursor string, limit int) string { + return prefix + ":" + strconv.Itoa(limit) + ":" + cursor +} + +func randomVersion() string { + var b [8]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} + +type cachedPage struct { + Items []domain.Message `json:"items"` + NextCursor string `json:"next_cursor"` +} + +func encodePage(p domain.Page[domain.Message]) ([]byte, error) { + return json.Marshal(cachedPage{Items: p.Items, NextCursor: p.NextCursor}) +} + +func decodePage(b []byte) (domain.Page[domain.Message], error) { + var c cachedPage + if err := json.Unmarshal(b, &c); err != nil { + return domain.Page[domain.Message]{}, err + } + return domain.Page[domain.Message]{Items: c.Items, NextCursor: c.NextCursor}, nil +} diff --git a/app/internal/cache/history_test.go b/app/internal/cache/history_test.go new file mode 100644 index 0000000..9b91c52 --- /dev/null +++ b/app/internal/cache/history_test.go @@ -0,0 +1,266 @@ +package cache + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "os" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/redis/go-redis/v9" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +const member = "alice" + +type fakeSource struct { + mu sync.Mutex + msgs []domain.Message + queryDelay time.Duration + pageCalls atomic.Int64 +} + +func (f *fakeSource) AddMessage(_ context.Context, callerID, chatID, text string) (domain.Message, error) { + f.mu.Lock() + defer f.mu.Unlock() + m := domain.Message{ + ID: fmt.Sprintf("m%04d", len(f.msgs)), + ChatID: chatID, + AuthorID: callerID, + Text: text, + CreatedAt: time.Now().UTC(), + } + f.msgs = append(f.msgs, m) + return m, nil +} + +func (f *fakeSource) IsMember(_ context.Context, _, userID string) (bool, error) { + return userID == member, nil +} + +func (f *fakeSource) HistoryPage(context.Context, string, string, int) (domain.Page[domain.Message], error) { + f.pageCalls.Add(1) + f.mu.Lock() + snapshot := append([]domain.Message(nil), f.msgs...) + f.mu.Unlock() + time.Sleep(f.queryDelay) + return domain.Page[domain.Message]{Items: snapshot}, nil +} + +func (f *fakeSource) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + if ok, _ := f.IsMember(ctx, chatID, callerID); !ok { + return domain.Page[domain.Message]{}, domain.ErrNotFound + } + return f.HistoryPage(ctx, chatID, cursor, limit) +} + +func testClient(t *testing.T) *redis.Client { + t.Helper() + url := os.Getenv("TEST_HISTORY_CACHE_URL") + if url == "" { + t.Skip("TEST_HISTORY_CACHE_URL не задан (scripts/integration-tests.sh)") + } + opts, err := redis.ParseURL(url) + if err != nil { + t.Fatal("bad TEST_HISTORY_CACHE_URL") + } + opts.DB = 15 + c := redis.NewClient(opts) + t.Cleanup(func() { c.Close() }) + if err := c.FlushDB(context.Background()).Err(); err != nil { + t.Fatalf("flushdb: %v", err) + } + return c +} + +func newCache(t *testing.T, c *redis.Client, mode string, src *fakeSource, fillDelay time.Duration) *Messages { + t.Helper() + m := New(src, c, Options{ + Mode: mode, + PageTTL: time.Minute, + FillDelay: fillDelay, + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + }) + t.Cleanup(m.Close) + return m +} + +func contains(p domain.Page[domain.Message], id string) bool { + for _, m := range p.Items { + if m.ID == id { + return true + } + } + return false +} + +func TestReadAfterWrite_FillRace(t *testing.T) { + ctx := context.Background() + for _, tc := range []struct { + mode string + wantStale bool + }{ + {ModeNaive, true}, + {ModeSafe, false}, + } { + t.Run(tc.mode, func(t *testing.T) { + c := testClient(t) + src := &fakeSource{} + h := newCache(t, c, tc.mode, src, 100*time.Millisecond) + chat := "chat-raw-" + tc.mode + if _, err := h.AddMessage(ctx, member, chat, "old"); err != nil { + t.Fatal(err) + } + + readerDone := make(chan struct{}) + go func() { + defer close(readerDone) + _, _ = h.ListMessages(ctx, member, chat, "", 50) // промах → снимок без "new" → пауза → SET + }() + time.Sleep(30 * time.Millisecond) // читатель уже внутри окна FillDelay + msg, err := h.AddMessage(ctx, member, chat, "new") + if err != nil { + t.Fatal(err) + } + <-readerDone + + page, err := h.ListMessages(ctx, member, chat, "", 50) + if err != nil { + t.Fatal(err) + } + stale := !contains(page, msg.ID) + if stale != tc.wantStale { + t.Fatalf("%s: stale=%v, ожидалось %v", tc.mode, stale, tc.wantStale) + } + t.Logf("%s: чтение после подтверждённой записи stale=%v", tc.mode, stale) + }) + } +} + +func TestStampede_SQLCount(t *testing.T) { + ctx := context.Background() + const readers = 50 + results := map[string]int64{} + for _, mode := range []string{ModeNaive, ModeSafe} { + t.Run(mode, func(t *testing.T) { + c := testClient(t) + src := &fakeSource{queryDelay: 20 * time.Millisecond} + h := newCache(t, c, mode, src, 0) + chat := "chat-stampede-" + mode + if _, err := h.ListMessages(ctx, member, chat, "", 50); err != nil { + t.Fatal(err) + } + warmPool(t, c, readers) + msg, _ := h.AddMessage(ctx, member, chat, "invalidate") + before := src.pageCalls.Load() + + var wg sync.WaitGroup + var stale atomic.Int64 + start := make(chan struct{}) + for i := 0; i < readers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + p, err := h.ListMessages(ctx, member, chat, "", 50) + if err != nil || !contains(p, msg.ID) { + stale.Add(1) + } + }() + } + close(start) + wg.Wait() + calls := src.pageCalls.Load() - before + results[mode] = calls + if stale.Load() != 0 { + t.Fatalf("%d читателей не увидели подтверждённое сообщение", stale.Load()) + } + t.Logf("%s: %d одновременных промахов → %d запросов страницы в БД", mode, readers, calls) + if mode == ModeSafe && calls != 1 { + t.Fatalf("safe: ожидался 1 запрос в БД, было %d", calls) + } + if mode == ModeNaive && calls < readers/2 { + t.Fatalf("naive: ожидался stampede (≥%d запросов), было %d", readers/2, calls) + } + }) + } +} + +func warmPool(t *testing.T, c *redis.Client, n int) { + t.Helper() + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _ = c.Do(context.Background(), "DEBUG", "SLEEP", "0.05").Err() + }() + } + wg.Wait() +} + +func TestAccessCheckedBeforeCache(t *testing.T) { + ctx := context.Background() + c := testClient(t) + h := newCache(t, c, ModeSafe, &fakeSource{}, 0) + if _, err := h.ListMessages(ctx, member, "chat-acl", "", 50); err != nil { + t.Fatal(err) + } + if _, err := h.ListMessages(ctx, "mallory", "chat-acl", "", 50); !errors.Is(err, domain.ErrNotFound) { + t.Fatalf("посторонний: err = %v, want ErrNotFound", err) + } +} + +func TestCacheLossIsOnlyMiss(t *testing.T) { + ctx := context.Background() + c := testClient(t) + src := &fakeSource{} + h := newCache(t, c, ModeSafe, src, 0) + chat := "chat-loss" + if _, err := h.ListMessages(ctx, member, chat, "", 50); err != nil { + t.Fatal(err) + } + if err := c.Del(ctx, verKey(chat)).Err(); err != nil { + t.Fatal(err) + } + msg, _ := src.AddMessage(ctx, member, chat, "написано в обход кэша") + before := src.pageCalls.Load() + page, err := h.ListMessages(ctx, member, chat, "", 50) + if err != nil { + t.Fatal(err) + } + if !contains(page, msg.ID) || src.pageCalls.Load() != before+1 { + t.Fatalf("после потери версии ожидался промах и свежая страница") + } +} + +func TestCacheDown_Bypass(t *testing.T) { + ctx := context.Background() + dead := redis.NewClient(&redis.Options{ + Addr: "127.0.0.1:1", DialTimeout: 50 * time.Millisecond, MaxRetries: -1, + }) + t.Cleanup(func() { dead.Close() }) + src := &fakeSource{} + h := newCache(t, dead, ModeSafe, src, 0) + + msg, err := h.AddMessage(ctx, member, "chat-down", "при упавшем кэше") + if err != nil { + t.Fatalf("запись при упавшем кэше: %v", err) + } + page, err := h.ListMessages(ctx, member, "chat-down", "", 50) + if err != nil || !contains(page, msg.ID) { + t.Fatalf("чтение при упавшем кэше: err=%v", err) + } + if !h.bypass("chat-down") { + t.Fatal("чат с несброшенной версией должен читаться мимо кэша") + } + if _, err := h.ListMessages(ctx, "mallory", "chat-down", "", 50); !errors.Is(err, domain.ErrNotFound) { + t.Fatalf("обход кэша не должен пропускать постороннего: %v", err) + } +} diff --git a/app/internal/config/config.go b/app/internal/config/config.go new file mode 100644 index 0000000..fc4f69f --- /dev/null +++ b/app/internal/config/config.go @@ -0,0 +1,146 @@ +package config + +import ( + "errors" + "fmt" + "os" + "strings" +) + +type Config struct { + Env string + Version string + + HTTP HTTP + Logger Logger + Limits Limits + Database Database + Cache Cache + Session Session + + HistoryCache HistoryCache +} + +func Load() (*Config, error) { + cfg := defaults() + if err := cfg.applyEnv(os.LookupEnv); err != nil { + return nil, fmt.Errorf("config: env: %w", err) + } + if err := cfg.validate(); err != nil { + return nil, fmt.Errorf("config: validate: %w", err) + } + return cfg, nil +} + +func defaults() *Config { + return &Config{ + Env: "lab", + Version: "dev", + HTTP: HTTP{ + Addr: "0.0.0.0:8080", + ReadTimeoutMs: 10000, + WriteTimeoutMs: 10000, + IdleTimeoutMs: 60000, + ShutdownTimeoutMs: 10000, + }, + Logger: Logger{Level: "info"}, + Limits: Limits{ + MaxBodyBytes: 64 * 1024, + MaxInFlight: 64, + MaxMessagesGlobal: 100000, + MaxHeapBytes: 256 * 1024 * 1024, + }, + Database: Database{ + MaxConns: 10, + ConnectTimeoutMs: 5000, + QueryTimeoutMs: 3000, + }, + Cache: Cache{ + PoolSize: 20, + TimeoutMs: 1000, + }, + Session: Session{Store: "valkey", TTLSeconds: 3600}, + HistoryCache: HistoryCache{ + Mode: "off", + PageTTLSeconds: 30, + TimeoutMs: 200, + PoolSize: 20, + }, + } +} + +func (c *Config) validate() error { + if strings.TrimSpace(c.Env) == "" { + return errors.New("env is required") + } + if strings.TrimSpace(c.Version) == "" { + return errors.New("version is required") + } + if strings.TrimSpace(c.HTTP.Addr) == "" { + return errors.New("http.addr is required") + } + if c.HTTP.ShutdownTimeoutMs <= 0 || c.HTTP.ShutdownTimeoutMs > 10000 { + return fmt.Errorf("APP_SHUTDOWN_TIMEOUT_MS must be in (0, 10000], got %d", c.HTTP.ShutdownTimeoutMs) + } + if c.HTTP.ReadTimeoutMs <= 0 { + return fmt.Errorf("APP_READ_TIMEOUT_MS must be > 0, got %d", c.HTTP.ReadTimeoutMs) + } + if c.HTTP.WriteTimeoutMs <= 0 { + return fmt.Errorf("APP_WRITE_TIMEOUT_MS must be > 0, got %d", c.HTTP.WriteTimeoutMs) + } + if c.HTTP.IdleTimeoutMs <= 0 { + return fmt.Errorf("APP_IDLE_TIMEOUT_MS must be > 0, got %d", c.HTTP.IdleTimeoutMs) + } + + if c.Limits.MaxBodyBytes <= 0 { + return fmt.Errorf("APP_MAX_BODY_BYTES must be > 0, got %d", c.Limits.MaxBodyBytes) + } + if c.Limits.MaxInFlight <= 0 { + return fmt.Errorf("APP_MAX_INFLIGHT must be > 0, got %d", c.Limits.MaxInFlight) + } + if c.Limits.MaxMessagesGlobal <= 0 { + return fmt.Errorf("APP_MAX_MESSAGES must be > 0, got %d", c.Limits.MaxMessagesGlobal) + } + if c.Limits.MaxHeapBytes == 0 { + return errors.New("APP_MAX_HEAP_BYTES must be > 0") + } + + if c.Database.MaxConns <= 0 { + return fmt.Errorf("DB_MAX_CONNS must be > 0, got %d", c.Database.MaxConns) + } + if c.Database.ConnectTimeoutMs <= 0 { + return fmt.Errorf("DB_CONNECT_TIMEOUT_MS must be > 0, got %d", c.Database.ConnectTimeoutMs) + } + if c.Database.QueryTimeoutMs <= 0 { + return fmt.Errorf("DB_QUERY_TIMEOUT_MS must be > 0, got %d", c.Database.QueryTimeoutMs) + } + if c.Cache.PoolSize <= 0 { + return fmt.Errorf("CACHE_POOL_SIZE must be > 0, got %d", c.Cache.PoolSize) + } + if c.Cache.TimeoutMs <= 0 { + return fmt.Errorf("CACHE_TIMEOUT_MS must be > 0, got %d", c.Cache.TimeoutMs) + } + switch c.HistoryCache.Mode { + case "off", "naive", "safe": + default: + return fmt.Errorf("HISTORY_CACHE must be off|naive|safe, got %q", c.HistoryCache.Mode) + } + if c.HistoryCache.PageTTLSeconds <= 0 { + return fmt.Errorf("HISTORY_CACHE_TTL_SECONDS must be > 0, got %d", c.HistoryCache.PageTTLSeconds) + } + if c.HistoryCache.TimeoutMs <= 0 || c.HistoryCache.PoolSize <= 0 { + return errors.New("HISTORY_CACHE_TIMEOUT_MS and HISTORY_CACHE_POOL_SIZE must be > 0") + } + if c.HistoryCache.FillDelayMs < 0 || c.HistoryCache.FillDelayMs > 1000 { + return fmt.Errorf("HISTORY_CACHE_FILL_DELAY_MS must be in [0, 1000], got %d", c.HistoryCache.FillDelayMs) + } + // Реализовано одно хранилище сессий; иное значение — ошибка конфигурации, а не тихий выбор. + if c.Session.Store != "valkey" { + return fmt.Errorf("SESSION_STORE must be valkey (the only implemented session store), got %q", c.Session.Store) + } + if c.Session.TTLSeconds <= 0 { + return fmt.Errorf("SESSION_TTL_SECONDS must be > 0, got %d", c.Session.TTLSeconds) + } + + return nil +} diff --git a/app/internal/config/database.go b/app/internal/config/database.go new file mode 100644 index 0000000..c56f8df --- /dev/null +++ b/app/internal/config/database.go @@ -0,0 +1,9 @@ +package config + +type Database struct { + URLFile string + URL string + MaxConns int32 + ConnectTimeoutMs int + QueryTimeoutMs int +} diff --git a/app/internal/config/env.go b/app/internal/config/env.go new file mode 100644 index 0000000..e120e9e --- /dev/null +++ b/app/internal/config/env.go @@ -0,0 +1,121 @@ +package config + +import ( + "fmt" + "net" + "strconv" + "strings" +) + +func (c *Config) applyEnv(lookup func(string) (string, bool)) error { + get := func(key string) (string, bool) { + v, ok := lookup(key) + v = strings.TrimSpace(v) + return v, ok && v != "" + } + + if v, ok := get("APP_ENV"); ok { + c.Env = v + } + if v, ok := get("APP_VERSION"); ok { + c.Version = v + } + if v, ok := get("APP_LOG_LEVEL"); ok { + c.Logger.Level = v + } + if v, ok := get("DATABASE_URL_FILE"); ok { + c.Database.URLFile = v + } + if v, ok := get("DATABASE_URL"); ok { + c.Database.URL = v + } + if v, ok := get("CACHE_URL_FILE"); ok { + c.Cache.URLFile = v + } + if v, ok := get("CACHE_URL"); ok { + c.Cache.URL = v + } + if v, ok := get("SESSION_STORE"); ok { + c.Session.Store = strings.ToLower(v) + } + if v, ok := get("HISTORY_CACHE"); ok { + c.HistoryCache.Mode = strings.ToLower(v) + } + if v, ok := get("HISTORY_CACHE_URL_FILE"); ok { + c.HistoryCache.URLFile = v + } + if v, ok := get("HISTORY_CACHE_URL"); ok { + c.HistoryCache.URL = v + } + + host, port, err := net.SplitHostPort(c.HTTP.Addr) + if err != nil { + return fmt.Errorf("default addr %q: %w", c.HTTP.Addr, err) + } + if v, ok := get("APP_HOST"); ok { + host = v + } + if v, ok := get("APP_PORT"); ok { + port = v + } + if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 { + return fmt.Errorf("APP_PORT must be in [1, 65535], got %q", port) + } + c.HTTP.Addr = net.JoinHostPort(host, port) + + ints := []struct { + key string + dst *int + }{ + {"APP_READ_TIMEOUT_MS", &c.HTTP.ReadTimeoutMs}, + {"APP_WRITE_TIMEOUT_MS", &c.HTTP.WriteTimeoutMs}, + {"APP_IDLE_TIMEOUT_MS", &c.HTTP.IdleTimeoutMs}, + {"APP_SHUTDOWN_TIMEOUT_MS", &c.HTTP.ShutdownTimeoutMs}, + {"APP_MAX_INFLIGHT", &c.Limits.MaxInFlight}, + {"APP_MAX_MESSAGES", &c.Limits.MaxMessagesGlobal}, + {"DB_CONNECT_TIMEOUT_MS", &c.Database.ConnectTimeoutMs}, + {"DB_QUERY_TIMEOUT_MS", &c.Database.QueryTimeoutMs}, + {"CACHE_POOL_SIZE", &c.Cache.PoolSize}, + {"CACHE_TIMEOUT_MS", &c.Cache.TimeoutMs}, + {"SESSION_TTL_SECONDS", &c.Session.TTLSeconds}, + {"HISTORY_CACHE_TTL_SECONDS", &c.HistoryCache.PageTTLSeconds}, + {"HISTORY_CACHE_TIMEOUT_MS", &c.HistoryCache.TimeoutMs}, + {"HISTORY_CACHE_POOL_SIZE", &c.HistoryCache.PoolSize}, + {"HISTORY_CACHE_FILL_DELAY_MS", &c.HistoryCache.FillDelayMs}, + } + for _, it := range ints { + v, ok := get(it.key) + if !ok { + continue + } + n, err := strconv.Atoi(v) + if err != nil { + return fmt.Errorf("%s: not an integer: %q", it.key, v) + } + *it.dst = n + } + + if v, ok := get("APP_MAX_BODY_BYTES"); ok { + n, err := strconv.ParseInt(v, 10, 64) + if err != nil { + return fmt.Errorf("APP_MAX_BODY_BYTES: not an integer: %q", v) + } + c.Limits.MaxBodyBytes = n + } + if v, ok := get("DB_MAX_CONNS"); ok { + n, err := strconv.ParseInt(v, 10, 32) + if err != nil { + return fmt.Errorf("DB_MAX_CONNS: not an integer: %q", v) + } + c.Database.MaxConns = int32(n) + } + if v, ok := get("APP_MAX_HEAP_BYTES"); ok { + n, err := strconv.ParseUint(v, 10, 64) + if err != nil { + return fmt.Errorf("APP_MAX_HEAP_BYTES: not a non-negative integer: %q", v) + } + c.Limits.MaxHeapBytes = n + } + + return nil +} diff --git a/app/internal/config/env_test.go b/app/internal/config/env_test.go new file mode 100644 index 0000000..7748dac --- /dev/null +++ b/app/internal/config/env_test.go @@ -0,0 +1,63 @@ +package config + +import "testing" + +func TestLoad_Defaults(t *testing.T) { + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.Addr != "0.0.0.0:8080" || cfg.Env != "lab" || cfg.Limits.MaxInFlight != 64 { + t.Errorf("cfg = %+v", cfg) + } +} + +func TestLoad_EnvOverridesDefaults(t *testing.T) { + t.Setenv("APP_HOST", "127.0.0.1") + t.Setenv("APP_PORT", "9090") + t.Setenv("APP_ENV", "docker") + t.Setenv("APP_MAX_INFLIGHT", "8") + t.Setenv("APP_MAX_BODY_BYTES", "2048") + + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.Addr != "127.0.0.1:9090" { + t.Errorf("addr = %q, want 127.0.0.1:9090", cfg.HTTP.Addr) + } + if cfg.Env != "docker" { + t.Errorf("env = %q, want docker", cfg.Env) + } + if cfg.Limits.MaxInFlight != 8 || cfg.Limits.MaxBodyBytes != 2048 { + t.Errorf("limits = %+v", cfg.Limits) + } +} + +func TestLoad_PortOnlyKeepsDefaultHost(t *testing.T) { + t.Setenv("APP_PORT", "18080") + + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.Addr != "0.0.0.0:18080" { + t.Errorf("addr = %q, want 0.0.0.0:18080", cfg.HTTP.Addr) + } +} + +func TestLoad_InvalidEnvFails(t *testing.T) { + for key, val := range map[string]string{ + "APP_PORT": "http", + "APP_MAX_INFLIGHT": "many", + "APP_MAX_MESSAGES": "0", + "APP_SHUTDOWN_TIMEOUT_MS": "30000", + } { + t.Run(key, func(t *testing.T) { + t.Setenv(key, val) + if _, err := Load(); err == nil { + t.Errorf("%s=%q: expected error", key, val) + } + }) + } +} diff --git a/app/internal/config/history_cache.go b/app/internal/config/history_cache.go new file mode 100644 index 0000000..e28fb81 --- /dev/null +++ b/app/internal/config/history_cache.go @@ -0,0 +1,11 @@ +package config + +type HistoryCache struct { + Mode string + URLFile string + URL string + PageTTLSeconds int + TimeoutMs int + PoolSize int + FillDelayMs int +} diff --git a/app/internal/config/http.go b/app/internal/config/http.go new file mode 100644 index 0000000..cfb9253 --- /dev/null +++ b/app/internal/config/http.go @@ -0,0 +1,9 @@ +package config + +type HTTP struct { + Addr string + ReadTimeoutMs int + WriteTimeoutMs int + IdleTimeoutMs int + ShutdownTimeoutMs int +} diff --git a/app/internal/config/limits.go b/app/internal/config/limits.go new file mode 100644 index 0000000..889fab5 --- /dev/null +++ b/app/internal/config/limits.go @@ -0,0 +1,8 @@ +package config + +type Limits struct { + MaxBodyBytes int64 + MaxInFlight int + MaxMessagesGlobal int + MaxHeapBytes uint64 +} diff --git a/app/internal/config/logger.go b/app/internal/config/logger.go new file mode 100644 index 0000000..be8e36b --- /dev/null +++ b/app/internal/config/logger.go @@ -0,0 +1,5 @@ +package config + +type Logger struct { + Level string +} diff --git a/app/internal/config/session.go b/app/internal/config/session.go new file mode 100644 index 0000000..56e0da4 --- /dev/null +++ b/app/internal/config/session.go @@ -0,0 +1,13 @@ +package config + +type Session struct { + Store string + TTLSeconds int +} + +type Cache struct { + URLFile string + URL string + PoolSize int + TimeoutMs int +} diff --git a/app/internal/domain/chat.go b/app/internal/domain/chat.go new file mode 100644 index 0000000..2de7174 --- /dev/null +++ b/app/internal/domain/chat.go @@ -0,0 +1,10 @@ +package domain + +import "time" + +type Chat struct { + ID string + Title string + MemberIDs []string + CreatedAt time.Time +} diff --git a/app/internal/domain/errors.go b/app/internal/domain/errors.go new file mode 100644 index 0000000..a86894b --- /dev/null +++ b/app/internal/domain/errors.go @@ -0,0 +1,19 @@ +package domain + +import "errors" + +var ( + ErrNotFound = errors.New("not found") + + ErrUnauthorized = errors.New("unauthorized") + + ErrConflict = errors.New("conflict") + + ErrInvalidArgument = errors.New("invalid argument") + + ErrUnavailable = errors.New("unavailable") + + ErrPayloadTooLarge = errors.New("payload too large") + + ErrRateLimited = errors.New("rate limited") +) diff --git a/app/internal/domain/message.go b/app/internal/domain/message.go new file mode 100644 index 0000000..ba213e5 --- /dev/null +++ b/app/internal/domain/message.go @@ -0,0 +1,11 @@ +package domain + +import "time" + +type Message struct { + ID string + ChatID string + AuthorID string + Text string + CreatedAt time.Time +} diff --git a/app/internal/domain/page.go b/app/internal/domain/page.go new file mode 100644 index 0000000..935e700 --- /dev/null +++ b/app/internal/domain/page.go @@ -0,0 +1,55 @@ +package domain + +import ( + "encoding/base64" + "encoding/json" + "time" +) + +type Page[T any] struct { + Items []T + NextCursor string +} + +type Cursor struct { + CreatedAt time.Time `json:"t"` + ID string `json:"i"` + Scope string `json:"s,omitempty"` +} + +func (c Cursor) IsZero() bool { + return c.ID == "" && c.CreatedAt.IsZero() +} + +func (c Cursor) Less(createdAt time.Time, id string) bool { + if c.CreatedAt.Before(createdAt) { + return true + } + if c.CreatedAt.After(createdAt) { + return false + } + return c.ID < id +} + +func EncodeCursor(c Cursor) string { + if c.IsZero() { + return "" + } + b, _ := json.Marshal(c) + return base64.RawURLEncoding.EncodeToString(b) +} + +func DecodeCursor(s string) (Cursor, error) { + if s == "" { + return Cursor{}, nil + } + raw, err := base64.RawURLEncoding.DecodeString(s) + if err != nil { + return Cursor{}, ErrInvalidArgument + } + var c Cursor + if err := json.Unmarshal(raw, &c); err != nil { + return Cursor{}, ErrInvalidArgument + } + return c, nil +} diff --git a/app/internal/domain/session.go b/app/internal/domain/session.go new file mode 100644 index 0000000..f62cd52 --- /dev/null +++ b/app/internal/domain/session.go @@ -0,0 +1,9 @@ +package domain + +import "time" + +type Session struct { + Token string + ExpiresAt time.Time + User User +} diff --git a/app/internal/domain/user.go b/app/internal/domain/user.go new file mode 100644 index 0000000..34d5235 --- /dev/null +++ b/app/internal/domain/user.go @@ -0,0 +1,10 @@ +package domain + +import "time" + +type User struct { + ID string + Username string + DisplayName string + CreatedAt time.Time +} diff --git a/app/internal/logging/logging.go b/app/internal/logging/logging.go new file mode 100644 index 0000000..551b53b --- /dev/null +++ b/app/internal/logging/logging.go @@ -0,0 +1,51 @@ +package logging + +import ( + "fmt" + "io" + "log/slog" + "os" + "strings" +) + +func New(level, env, version string) (*slog.Logger, error) { + lvl, err := parseLevel(level) + if err != nil { + return nil, err + } + return build(os.Stdout, lvl, env, version), nil +} + +func build(w io.Writer, lvl slog.Level, env, version string) *slog.Logger { + handler := slog.NewJSONHandler(w, &slog.HandlerOptions{ + Level: lvl, + ReplaceAttr: forceUTCTime, + }) + return slog.New(handler).With( + slog.String("service", "messenger"), + slog.String("env", env), + slog.String("version", version), + ) +} + +func forceUTCTime(_ []string, a slog.Attr) slog.Attr { + if a.Value.Kind() == slog.KindTime { + a.Value = slog.TimeValue(a.Value.Time().UTC()) + } + return a +} + +func parseLevel(s string) (slog.Level, error) { + switch strings.ToLower(strings.TrimSpace(s)) { + case "", "info": + return slog.LevelInfo, nil + case "debug": + return slog.LevelDebug, nil + case "warn", "warning": + return slog.LevelWarn, nil + case "error": + return slog.LevelError, nil + default: + return 0, fmt.Errorf("logging: unknown level %q (want debug|info|warn|error)", s) + } +} diff --git a/app/internal/password/password.go b/app/internal/password/password.go new file mode 100644 index 0000000..e25b9b1 --- /dev/null +++ b/app/internal/password/password.go @@ -0,0 +1,113 @@ +package password + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +type Params struct { + MemoryKiB uint32 + Iterations uint32 + Parallelism uint8 + SaltLen uint32 + KeyLen uint32 +} + +var Default = Params{ + MemoryKiB: 19 * 1024, + Iterations: 2, + Parallelism: 1, + SaltLen: 16, + KeyLen: 32, +} + +var ErrMalformedHash = errors.New("password: malformed hash") + +var b64 = base64.RawStdEncoding + + +type Hasher struct { + params Params + slots chan struct{} +} + +func NewHasher(p Params, maxConcurrent int) *Hasher { + if maxConcurrent <= 0 { + maxConcurrent = 1 + } + return &Hasher{params: p, slots: make(chan struct{}, maxConcurrent)} +} + +func (h *Hasher) acquire(ctx context.Context) error { + select { + case h.slots <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (h *Hasher) release() { <-h.slots } + +// Hash возвращает PHC-строку Argon2id со случайной солью. +func (h *Hasher) Hash(ctx context.Context, plain string) (string, error) { + salt := make([]byte, h.params.SaltLen) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("password: rand: %w", err) + } + if err := h.acquire(ctx); err != nil { + return "", err + } + defer h.release() + + p := h.params + key := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, p.KeyLen) + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, p.MemoryKiB, p.Iterations, p.Parallelism, + b64.EncodeToString(salt), b64.EncodeToString(key)), nil +} + +func (h *Hasher) Verify(ctx context.Context, plain, encoded string) (bool, error) { + p, salt, want, err := decode(encoded) + if err != nil { + return false, err + } + if err := h.acquire(ctx); err != nil { + return false, err + } + defer h.release() + + got := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, uint32(len(want))) + return subtle.ConstantTimeCompare(got, want) == 1, nil +} + +func decode(encoded string) (Params, []byte, []byte, error) { + parts := strings.Split(encoded, "$") + if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" { + return Params{}, nil, nil, ErrMalformedHash + } + var version int + if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version { + return Params{}, nil, nil, ErrMalformedHash + } + var p Params + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.MemoryKiB, &p.Iterations, &p.Parallelism); err != nil { + return Params{}, nil, nil, ErrMalformedHash + } + salt, err := b64.DecodeString(parts[4]) + if err != nil || len(salt) == 0 { + return Params{}, nil, nil, ErrMalformedHash + } + key, err := b64.DecodeString(parts[5]) + if err != nil || len(key) == 0 { + return Params{}, nil, nil, ErrMalformedHash + } + return p, salt, key, nil +} diff --git a/app/internal/password/password_test.go b/app/internal/password/password_test.go new file mode 100644 index 0000000..d4dabda --- /dev/null +++ b/app/internal/password/password_test.go @@ -0,0 +1,76 @@ +package password + +import ( + "context" + "errors" + "strings" + "testing" +) + +var testParams = Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32} + +func TestHashVerify(t *testing.T) { + h := NewHasher(testParams, 2) + ctx := context.Background() + + pw := "пароль:с-двоеточием-и-юникодом" + encoded, err := h.Hash(ctx, pw) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(encoded, "$argon2id$v=19$m=64,t=1,p=1$") { + t.Errorf("unexpected format %q", encoded) + } + if strings.Contains(encoded, pw) { + t.Error("hash contains plaintext") + } + + ok, err := h.Verify(ctx, pw, encoded) + if err != nil || !ok { + t.Errorf("Verify(correct) = %v, %v", ok, err) + } + ok, err = h.Verify(ctx, pw+"x", encoded) + if err != nil || ok { + t.Errorf("Verify(wrong) = %v, %v", ok, err) + } +} + +func TestHash_RandomSalt(t *testing.T) { + h := NewHasher(testParams, 1) + a, _ := h.Hash(context.Background(), "same-password-123") + b, _ := h.Hash(context.Background(), "same-password-123") + if a == b { + t.Error("two hashes of the same password are equal: salt is not random") + } +} + +func TestVerify_UsesParamsFromHash(t *testing.T) { + old := NewHasher(testParams, 1) + encoded, _ := old.Hash(context.Background(), "long-enough-password") + + stronger := testParams + stronger.Iterations = 3 + ok, err := NewHasher(stronger, 1).Verify(context.Background(), "long-enough-password", encoded) + if err != nil || !ok { + t.Errorf("old hash must verify after params change: %v, %v", ok, err) + } +} + +func TestVerify_Malformed(t *testing.T) { + h := NewHasher(testParams, 1) + for _, s := range []string{"", "!", "$argon2i$v=19$m=64,t=1,p=1$AAAA$AAAA", "$argon2id$v=19$m=64$AAAA$AAAA"} { + if _, err := h.Verify(context.Background(), "x", s); !errors.Is(err, ErrMalformedHash) { + t.Errorf("Verify(%q) err = %v, want ErrMalformedHash", s, err) + } + } +} + +func TestHash_RespectsContextWhenBusy(t *testing.T) { + h := NewHasher(testParams, 1) + h.slots <- struct{}{} // единственный слот занят + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := h.Hash(ctx, "long-enough-password"); !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } +} diff --git a/app/internal/service/auth.go b/app/internal/service/auth.go new file mode 100644 index 0000000..770735e --- /dev/null +++ b/app/internal/service/auth.go @@ -0,0 +1,101 @@ +package service + +import ( + "context" + "errors" + "fmt" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token" +) + +var ( + _ AuthService = (*Auth)(nil) +) + +type Auth struct { + users store.UserStore + sessions session.Store + hasher *password.Hasher + ttl time.Duration + now func() time.Time + + dummyHash string +} + +func NewAuth(users store.UserStore, sessions session.Store, hasher *password.Hasher, ttl time.Duration) (*Auth, error) { + dummy, err := hasher.Hash(context.Background(), "dummy-password-for-timing") + if err != nil { + return nil, fmt.Errorf("auth: dummy hash: %w", err) + } + return &Auth{ + users: users, + sessions: sessions, + hasher: hasher, + ttl: ttl, + now: time.Now, + dummyHash: dummy, + }, nil +} + +func (a *Auth) Login(ctx context.Context, username, plainPassword string) (domain.Session, error) { + user, hash, err := a.users.CredentialsByUsername(ctx, username) + switch { + case errors.Is(err, domain.ErrNotFound): + _, _ = a.hasher.Verify(ctx, plainPassword, a.dummyHash) + return domain.Session{}, domain.ErrUnauthorized + case err != nil: + return domain.Session{}, err + } + + ok, err := a.hasher.Verify(ctx, plainPassword, hash) + if err != nil { + if errors.Is(err, password.ErrMalformedHash) { + return domain.Session{}, domain.ErrUnauthorized + } + return domain.Session{}, err + } + if !ok { + return domain.Session{}, domain.ErrUnauthorized + } + + plain, tokenHash, err := token.New() + if err != nil { + return domain.Session{}, err + } + expiresAt := a.now().Add(a.ttl).UTC().Truncate(time.Second) + if err := a.sessions.Save(ctx, tokenHash, session.Session{UserID: user.ID, ExpiresAt: expiresAt}); err != nil { + return domain.Session{}, err + } + return domain.Session{Token: plain, ExpiresAt: expiresAt, User: user}, nil +} + +func (a *Auth) Authenticate(ctx context.Context, plainToken string) (string, error) { + tokenHash, err := token.Parse(plainToken) + if err != nil { + return "", domain.ErrUnauthorized + } + s, err := a.sessions.Get(ctx, tokenHash) + if errors.Is(err, session.ErrNotFound) { + return "", domain.ErrUnauthorized + } + if err != nil { + return "", err + } + if !a.now().Before(s.ExpiresAt) { + return "", domain.ErrUnauthorized + } + return s.UserID, nil +} + +func (a *Auth) Logout(ctx context.Context, plainToken string) error { + tokenHash, err := token.Parse(plainToken) + if err != nil { + return domain.ErrUnauthorized + } + return a.sessions.Delete(ctx, tokenHash) +} diff --git a/app/internal/service/chats.go b/app/internal/service/chats.go new file mode 100644 index 0000000..b3db00c --- /dev/null +++ b/app/internal/service/chats.go @@ -0,0 +1,47 @@ +package service + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +var ( + _ ChatsService = (*Chats)(nil) +) + +type Chats struct { + store store.ChatStore +} + +func NewChats(s store.ChatStore) *Chats { + return &Chats{store: s} +} + +func (c *Chats) Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) { + if err := validate.ChatTitle(title); err != nil { + return domain.Chat{}, err + } + memberIDs, err := validate.MemberIDs(memberIDs, callerID) + if err != nil { + return domain.Chat{}, err + } + return c.store.CreateChat(ctx, callerID, title, memberIDs) +} + +func (c *Chats) Get(ctx context.Context, callerID, chatID string) (domain.Chat, error) { + chatID, err := validate.CanonicalUUID("chat_id", chatID) + if err != nil { + return domain.Chat{}, err + } + return c.store.ChatByID(ctx, callerID, chatID) +} + +func (c *Chats) List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) { + if err := validate.Limit(limit); err != nil { + return domain.Page[domain.Chat]{}, err + } + return c.store.ListChats(ctx, callerID, cursor, limit) +} diff --git a/app/internal/service/messages.go b/app/internal/service/messages.go new file mode 100644 index 0000000..bc40c92 --- /dev/null +++ b/app/internal/service/messages.go @@ -0,0 +1,43 @@ +package service + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +var ( + _ MessagesService = (*Messages)(nil) +) + +type Messages struct { + store store.MessageStore +} + +func NewMessages(s store.MessageStore) *Messages { + return &Messages{store: s} +} + +func (m *Messages) Send(ctx context.Context, callerID, chatID, text string) (domain.Message, error) { + chatID, err := validate.CanonicalUUID("chat_id", chatID) + if err != nil { + return domain.Message{}, err + } + if err := validate.MessageText(text); err != nil { + return domain.Message{}, err + } + return m.store.AddMessage(ctx, callerID, chatID, text) +} + +func (m *Messages) List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + chatID, err := validate.CanonicalUUID("chat_id", chatID) + if err != nil { + return domain.Page[domain.Message]{}, err + } + if err := validate.Limit(limit); err != nil { + return domain.Page[domain.Message]{}, err + } + return m.store.ListMessages(ctx, callerID, chatID, cursor, limit) +} diff --git a/app/internal/service/service.go b/app/internal/service/service.go new file mode 100644 index 0000000..9181083 --- /dev/null +++ b/app/internal/service/service.go @@ -0,0 +1,29 @@ +package service + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type UsersService interface { + Register(ctx context.Context, username, displayName, password string) (domain.User, error) + Me(ctx context.Context, callerID string) (domain.User, error) +} + +type ChatsService interface { + Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) + Get(ctx context.Context, callerID, chatID string) (domain.Chat, error) + List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) +} + +type MessagesService interface { + Send(ctx context.Context, callerID, chatID, text string) (domain.Message, error) + List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) +} + +type AuthService interface { + Login(ctx context.Context, username, password string) (domain.Session, error) + Authenticate(ctx context.Context, token string) (userID string, err error) + Logout(ctx context.Context, token string) error +} diff --git a/app/internal/service/users.go b/app/internal/service/users.go new file mode 100644 index 0000000..297938c --- /dev/null +++ b/app/internal/service/users.go @@ -0,0 +1,44 @@ +package service + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +var ( + _ UsersService = (*Users)(nil) +) + +type Users struct { + store store.UserStore + hasher *password.Hasher +} + +func NewUsers(s store.UserStore, h *password.Hasher) *Users { + return &Users{store: s, hasher: h} +} + +func (u *Users) Register(ctx context.Context, username, displayName, plainPassword string) (domain.User, error) { + if err := validate.Username(username); err != nil { + return domain.User{}, err + } + if err := validate.DisplayName(displayName); err != nil { + return domain.User{}, err + } + if err := validate.Password(plainPassword); err != nil { + return domain.User{}, err + } + hash, err := u.hasher.Hash(ctx, plainPassword) + if err != nil { + return domain.User{}, err + } + return u.store.CreateUser(ctx, username, displayName, hash) +} + +func (u *Users) Me(ctx context.Context, callerID string) (domain.User, error) { + return u.store.UserByID(ctx, callerID) +} diff --git a/app/internal/session/memory.go b/app/internal/session/memory.go new file mode 100644 index 0000000..b6896df --- /dev/null +++ b/app/internal/session/memory.go @@ -0,0 +1,49 @@ +package session + +import ( + "context" + "sync" + "time" +) + +var _ Store = (*Memory)(nil) + +type Memory struct { + mu sync.Mutex + sessions map[string]Session + now func() time.Time +} + +func NewMemory() *Memory { + return &Memory{sessions: make(map[string]Session), now: time.Now} +} + +func (m *Memory) Save(_ context.Context, tokenHash []byte, s Session) error { + m.mu.Lock() + defer m.mu.Unlock() + m.sessions[string(tokenHash)] = s + return nil +} + +func (m *Memory) Get(_ context.Context, tokenHash []byte) (Session, error) { + m.mu.Lock() + defer m.mu.Unlock() + s, ok := m.sessions[string(tokenHash)] + if !ok { + return Session{}, ErrNotFound + } + if !m.now().Before(s.ExpiresAt) { + delete(m.sessions, string(tokenHash)) + return Session{}, ErrNotFound + } + return s, nil +} + +func (m *Memory) Delete(_ context.Context, tokenHash []byte) error { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.sessions, string(tokenHash)) + return nil +} + +func (m *Memory) Ping(context.Context) error { return nil } diff --git a/app/internal/session/session.go b/app/internal/session/session.go new file mode 100644 index 0000000..7e3047c --- /dev/null +++ b/app/internal/session/session.go @@ -0,0 +1,21 @@ +package session + +import ( + "context" + "errors" + "time" +) + +type Session struct { + UserID string `json:"user_id"` + ExpiresAt time.Time `json:"expires_at"` +} + +var ErrNotFound = errors.New("session: not found") + +type Store interface { + Save(ctx context.Context, tokenHash []byte, s Session) error + Get(ctx context.Context, tokenHash []byte) (Session, error) + Delete(ctx context.Context, tokenHash []byte) error + Ping(ctx context.Context) error +} diff --git a/app/internal/session/valkey.go b/app/internal/session/valkey.go new file mode 100644 index 0000000..9deddbd --- /dev/null +++ b/app/internal/session/valkey.go @@ -0,0 +1,120 @@ +package session + +import ( + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "time" + + "github.com/redis/go-redis/v9" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +var _ Store = (*Valkey)(nil) + +const keyPrefix = "session:" + +type Valkey struct { + client *redis.Client +} + +func NewValkey(client *redis.Client) *Valkey { + return &Valkey{client: client} +} + +func Connect(ctx context.Context, cfg config.Cache) (*redis.Client, error) { + url, err := urlFrom(cfg) + if err != nil { + return nil, err + } + opts, err := redis.ParseURL(url) + if err != nil { + return nil, errors.New("session: invalid CACHE_URL") + } + timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond + opts.PoolSize = cfg.PoolSize + opts.DialTimeout = timeout + opts.ReadTimeout = timeout + opts.WriteTimeout = timeout + opts.PoolTimeout = timeout + opts.MaxRetries = 1 + + client := redis.NewClient(opts) + pingCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + if err := client.Ping(pingCtx).Err(); err != nil { + _ = client.Close() + return nil, fmt.Errorf("session: ping: %w", err) + } + return client, nil +} + +func urlFrom(cfg config.Cache) (string, error) { + if cfg.URLFile != "" { + b, err := os.ReadFile(cfg.URLFile) + if err != nil { + return "", fmt.Errorf("session: read CACHE_URL_FILE: %w", err) + } + return strings.TrimSpace(string(b)), nil + } + if cfg.URL != "" { + return cfg.URL, nil + } + return "", errors.New("session: CACHE_URL_FILE or CACHE_URL is required") +} + +func key(tokenHash []byte) string { + return keyPrefix + hex.EncodeToString(tokenHash) +} + +func (v *Valkey) Save(ctx context.Context, tokenHash []byte, s Session) error { + val, err := json.Marshal(s) + if err != nil { + return err + } + // NX: 256-битный токен не совпадёт, но перезаписать чужую сессию нельзя даже теоретически. + err = v.client.SetArgs(ctx, key(tokenHash), val, redis.SetArgs{ + Mode: "NX", + ExpireAt: s.ExpiresAt, + }).Err() + if errors.Is(err, redis.Nil) { + return fmt.Errorf("session: token collision") + } + return unavailable(err) +} + +func (v *Valkey) Get(ctx context.Context, tokenHash []byte) (Session, error) { + val, err := v.client.Get(ctx, key(tokenHash)).Bytes() + if errors.Is(err, redis.Nil) { + return Session{}, ErrNotFound + } + if err != nil { + return Session{}, unavailable(err) + } + var s Session + if err := json.Unmarshal(val, &s); err != nil { + return Session{}, fmt.Errorf("session: corrupt value: %w", err) + } + return s, nil +} + +func (v *Valkey) Delete(ctx context.Context, tokenHash []byte) error { + return unavailable(v.client.Del(ctx, key(tokenHash)).Err()) +} + +func (v *Valkey) Ping(ctx context.Context) error { + return unavailable(v.client.Ping(ctx).Err()) +} + +func unavailable(err error) error { + if err == nil { + return nil + } + return fmt.Errorf("%w: session store: %v", domain.ErrUnavailable, err) +} diff --git a/app/internal/store/db/chats.go b/app/internal/store/db/chats.go new file mode 100644 index 0000000..1cae9e3 --- /dev/null +++ b/app/internal/store/db/chats.go @@ -0,0 +1,163 @@ +package db + +import ( + "context" + "strings" + "time" + + "github.com/jackc/pgx/v5" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type Chats struct { + conn +} + +func (c *Chats) CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) { + if strings.TrimSpace(title) == "" { + return domain.Chat{}, domain.ErrInvalidArgument + } + if len(memberIDs) == 0 || len(memberIDs) > 100 { + return domain.Chat{}, domain.ErrInvalidArgument + } + seen := make(map[string]struct{}, len(memberIDs)) + callerInMembers := false + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return domain.Chat{}, domain.ErrInvalidArgument + } + seen[id] = struct{}{} + if id == callerID { + callerInMembers = true + } + } + if !callerInMembers { + return domain.Chat{}, domain.ErrInvalidArgument + } + + ctx, cancel := c.withTimeout(ctx) + defer cancel() + + tx, err := c.pool.Begin(ctx) + if err != nil { + return domain.Chat{}, mapErr(err) + } + defer tx.Rollback(ctx) + + chat := domain.Chat{Title: title} + err = tx.QueryRow(ctx, ` + INSERT INTO chats (title) + VALUES ($1) + RETURNING id::text, created_at`, + title, + ).Scan(&chat.ID, &chat.CreatedAt) + if err != nil { + return domain.Chat{}, mapErr(err) + } + + _, err = tx.Exec(ctx, ` + INSERT INTO chat_members (chat_id, user_id) + SELECT $1, unnest($2::uuid[])`, + chat.ID, memberIDs, + ) + if err != nil { + return domain.Chat{}, mapErr(err) + } + + if err := tx.Commit(ctx); err != nil { + return domain.Chat{}, mapErr(err) + } + + chat.MemberIDs = append([]string(nil), memberIDs...) + chat.CreatedAt = chat.CreatedAt.UTC() + return chat, nil +} + +func (c *Chats) ChatByID(ctx context.Context, callerID, chatID string) (domain.Chat, error) { + ctx, cancel := c.withTimeout(ctx) + defer cancel() + + chat := domain.Chat{} + err := c.pool.QueryRow(ctx, ` + SELECT c.id::text, c.title, c.created_at, + (SELECT array_agg(m.user_id::text ORDER BY m.user_id) + FROM chat_members m WHERE m.chat_id = c.id) + FROM chats c + JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2 + WHERE c.id = $1`, + chatID, callerID, + ).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs) + if err != nil { + err = mapErr(err) + if err == domain.ErrInvalidArgument { + return domain.Chat{}, domain.ErrNotFound + } + return domain.Chat{}, err + } + chat.CreatedAt = chat.CreatedAt.UTC() + return chat, nil +} + +func (c *Chats) ListChats(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) { + if limit <= 0 || limit > 100 { + return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument + } + cur, err := domain.DecodeCursor(cursor) + if err != nil { + return domain.Page[domain.Chat]{}, err + } + scope := "chats:" + callerID + if cursor != "" && cur.Scope != scope { + return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument + } + afterTime, afterID := cursorArgs(cur) + + ctx, cancel := c.withTimeout(ctx) + defer cancel() + + rows, err := c.pool.Query(ctx, ` + SELECT c.id::text, c.title, c.created_at, + (SELECT array_agg(m.user_id::text ORDER BY m.user_id) + FROM chat_members m WHERE m.chat_id = c.id) + FROM chat_members me + JOIN chats c ON c.id = me.chat_id + WHERE me.user_id = $1 + AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid)) + ORDER BY c.created_at, c.id + LIMIT $4`, + callerID, afterTime, afterID, limit+1, + ) + if err != nil { + return domain.Page[domain.Chat]{}, mapErr(err) + } + out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Chat, error) { + var ch domain.Chat + err := r.Scan(&ch.ID, &ch.Title, &ch.CreatedAt, &ch.MemberIDs) + ch.CreatedAt = ch.CreatedAt.UTC() + return ch, err + }) + if err != nil { + return domain.Page[domain.Chat]{}, mapErr(err) + } + + page := domain.Page[domain.Chat]{} + if len(out) > limit { + last := out[limit-1] + page.NextCursor = domain.EncodeCursor(domain.Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + Scope: scope, + }) + out = out[:limit] + } + page.Items = out + return page, nil +} + +func cursorArgs(c domain.Cursor) (*time.Time, *string) { + if c.IsZero() { + return nil, nil + } + return &c.CreatedAt, &c.ID +} diff --git a/app/internal/store/db/db.go b/app/internal/store/db/db.go new file mode 100644 index 0000000..cb30e3c --- /dev/null +++ b/app/internal/store/db/db.go @@ -0,0 +1,132 @@ +package db + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +var _ store.Store = (*DB)(nil) + +type DB struct { + *Users + *Chats + *Messages + + pool *pgxpool.Pool +} + +func New(pool *pgxpool.Pool, queryTimeout time.Duration) *DB { + c := conn{pool: pool, timeout: queryTimeout} + return &DB{ + Users: &Users{conn: c}, + Chats: &Chats{conn: c}, + Messages: &Messages{conn: c}, + pool: pool, + } +} + +func Connect(ctx context.Context, cfg config.Database) (*pgxpool.Pool, error) { + dsn, err := dsnFrom(cfg) + if err != nil { + return nil, err + } + pcfg, err := pgxpool.ParseConfig(dsn) + if err != nil { + return nil, errors.New("db: invalid DSN") + } + pcfg.MaxConns = cfg.MaxConns + pcfg.ConnConfig.ConnectTimeout = time.Duration(cfg.ConnectTimeoutMs) * time.Millisecond + + pool, err := pgxpool.NewWithConfig(ctx, pcfg) + if err != nil { + return nil, fmt.Errorf("db: pool: %w", err) + } + + pingCtx, cancel := context.WithTimeout(ctx, pcfg.ConnConfig.ConnectTimeout) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("db: ping: %w", err) + } + return pool, nil +} + +func dsnFrom(cfg config.Database) (string, error) { + if cfg.URLFile != "" { + b, err := os.ReadFile(cfg.URLFile) + if err != nil { + return "", fmt.Errorf("db: read DATABASE_URL_FILE: %w", err) + } + return strings.TrimSpace(string(b)), nil + } + if cfg.URL != "" { + return cfg.URL, nil + } + return "", errors.New("db: DATABASE_URL_FILE or DATABASE_URL is required") +} + +func (d *DB) Ping(ctx context.Context) error { + return d.pool.Ping(ctx) +} + +func (d *DB) Close() { + d.pool.Close() +} + +type conn struct { + pool *pgxpool.Pool + timeout time.Duration +} + +func (c conn) withTimeout(parent context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(parent, c.timeout) +} + + +const ( + codeUniqueViolation = "23505" + codeForeignKeyViolation = "23503" + codeCheckViolation = "23514" + codeInvalidTextRepr = "22P02" +) + +func mapErr(err error) error { + if err == nil { + return nil + } + if errors.Is(err, pgx.ErrNoRows) { + return domain.ErrNotFound + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + switch pgErr.Code { + case codeUniqueViolation: + return domain.ErrConflict + case codeForeignKeyViolation, codeCheckViolation, codeInvalidTextRepr: + return domain.ErrInvalidArgument + } + switch pgErr.Code[:2] { + case "08", "53", "57": + return fmt.Errorf("%w: db: %s", domain.ErrUnavailable, pgErr.Code) + } + return fmt.Errorf("db: %s: %w", pgErr.Code, err) + } + return fmt.Errorf("%w: db: %v", domain.ErrUnavailable, err) +} + +func isFKViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == codeForeignKeyViolation +} diff --git a/app/internal/store/db/db_test.go b/app/internal/store/db/db_test.go new file mode 100644 index 0000000..5fe65db --- /dev/null +++ b/app/internal/store/db/db_test.go @@ -0,0 +1,46 @@ +package db + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +func TestMapErr(t *testing.T) { + pg := func(code string) error { return &pgconn.PgError{Code: code} } + cases := []struct { + name string + err error + want error + }{ + {"no rows", pgx.ErrNoRows, domain.ErrNotFound}, + {"unique", pg("23505"), domain.ErrConflict}, + {"fk", pg("23503"), domain.ErrInvalidArgument}, + {"check", pg("23514"), domain.ErrInvalidArgument}, + {"bad uuid text", pg("22P02"), domain.ErrInvalidArgument}, + {"admin shutdown (postgres stop)", pg("57P01"), domain.ErrUnavailable}, + {"cannot connect now (starting up)", pg("57P03"), domain.ErrUnavailable}, + {"connection failure", pg("08006"), domain.ErrUnavailable}, + {"too many connections", pg("53300"), domain.ErrUnavailable}, + {"timeout", fmt.Errorf("query: %w", context.DeadlineExceeded), domain.ErrUnavailable}, + {"dial refused", errors.New("dial tcp: connection refused"), domain.ErrUnavailable}, + } + for _, tc := range cases { + if got := mapErr(tc.err); !errors.Is(got, tc.want) { + t.Errorf("%s: mapErr = %v, want %v", tc.name, got, tc.want) + } + } + + if got := mapErr(pg("42601")); errors.Is(got, domain.ErrUnavailable) || errors.Is(got, domain.ErrInvalidArgument) { + t.Errorf("syntax error mapped to %v", got) + } + if mapErr(nil) != nil { + t.Error("mapErr(nil) != nil") + } +} diff --git a/app/internal/store/db/integration_test.go b/app/internal/store/db/integration_test.go new file mode 100644 index 0000000..65904ec --- /dev/null +++ b/app/internal/store/db/integration_test.go @@ -0,0 +1,130 @@ +package db + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "os" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +func testDB(t *testing.T) (*DB, *pgxpool.Pool) { + t.Helper() + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL не задан (scripts/integration-tests.sh)") + } + pool, err := pgxpool.New(context.Background(), dsn) + if err != nil { + t.Fatal("bad TEST_DATABASE_URL") + } + t.Cleanup(pool.Close) + return New(pool, 5*time.Second), pool +} + +func suffix() string { + b := make([]byte, 4) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func TestUsernameRace(t *testing.T) { + d, pool := testDB(t) + ctx := context.Background() + username := "race_" + suffix() + + const n = 20 + var wg sync.WaitGroup + errs := make([]error, n) + start := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + _, errs[i] = d.CreateUser(ctx, username, "Гонка", "$argon2id$test") + }() + } + close(start) + wg.Wait() + + ok, conflict := 0, 0 + for _, err := range errs { + switch { + case err == nil: + ok++ + case errors.Is(err, domain.ErrConflict): + conflict++ + default: + t.Fatalf("неожиданная ошибка: %v", err) + } + } + var rows int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM users WHERE username = $1`, username).Scan(&rows); err != nil { + t.Fatal(err) + } + if ok != 1 || conflict != n-1 || rows != 1 { + t.Fatalf("ok=%d conflict=%d rows=%d, ожидалось 1/%d/1", ok, conflict, rows, n-1) + } + t.Logf("%d параллельных регистраций: 1 created, %d conflict, строк в users: %d", n, conflict, rows) +} + + +func TestCreateChatRollback(t *testing.T) { + d, pool := testDB(t) + ctx := context.Background() + u, err := d.CreateUser(ctx, "rb_"+suffix(), "Откат", "$argon2id$test") + if err != nil { + t.Fatal(err) + } + title := "rollback-" + suffix() + unknown := uuid.NewString() + + _, err = d.CreateChat(ctx, u.ID, title, []string{u.ID, unknown}) + if !errors.Is(err, domain.ErrInvalidArgument) { + t.Fatalf("err = %v, want ErrInvalidArgument (→ 400)", err) + } + var chats, members int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&chats); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `SELECT count(*) FROM chat_members WHERE user_id = $1`, u.ID).Scan(&members); err != nil { + t.Fatal(err) + } + if chats != 0 || members != 0 { + t.Fatalf("после отката осталось chats=%d chat_members=%d", chats, members) + } + + if _, err := d.CreateChat(ctx, u.ID, title, []string{u.ID}); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&chats); err != nil { + t.Fatal(err) + } + if chats != 1 { + t.Fatalf("контрольный чат не создан: %d", chats) + } + t.Log("неизвестный участник → 400, chats/chat_members без изменений; валидный вызов создаёт 1 чат") +} + +func TestMessageRequiresMembership(t *testing.T) { + d, _ := testDB(t) + ctx := context.Background() + a, _ := d.CreateUser(ctx, "ma_"+suffix(), "A", "$argon2id$test") + b, _ := d.CreateUser(ctx, "mb_"+suffix(), "B", "$argon2id$test") + chat, err := d.CreateChat(ctx, a.ID, "fk-"+suffix(), []string{a.ID}) + if err != nil { + t.Fatal(err) + } + if _, err := d.AddMessage(ctx, b.ID, chat.ID, "чужой"); !errors.Is(err, domain.ErrNotFound) { + t.Fatalf("err = %v, want ErrNotFound (→ 404)", err) + } +} diff --git a/app/internal/store/db/messages.go b/app/internal/store/db/messages.go new file mode 100644 index 0000000..6ca8088 --- /dev/null +++ b/app/internal/store/db/messages.go @@ -0,0 +1,129 @@ +package db + +import ( + "context" + "strings" + + "github.com/jackc/pgx/v5" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type Messages struct { + conn +} + +func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, text string) (domain.Message, error) { + if strings.TrimSpace(text) == "" { + return domain.Message{}, domain.ErrInvalidArgument + } + + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + msg := domain.Message{ChatID: chatID, AuthorID: callerID, Text: text} + err := m.pool.QueryRow(ctx, ` + INSERT INTO messages (chat_id, sender_id, text) + VALUES ($1, $2, $3) + RETURNING id::text, created_at`, + chatID, callerID, text, + ).Scan(&msg.ID, &msg.CreatedAt) + if err != nil { + if isFKViolation(err) { + return domain.Message{}, domain.ErrNotFound + } + return domain.Message{}, mapErr(err) + } + msg.CreatedAt = msg.CreatedAt.UTC() + return msg, nil +} + +func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + member, err := m.IsMember(ctx, chatID, callerID) + if err != nil { + return domain.Page[domain.Message]{}, err + } + if !member { + return domain.Page[domain.Message]{}, domain.ErrNotFound + } + return m.HistoryPage(ctx, chatID, cursor, limit) +} + + +func (m *Messages) IsMember(ctx context.Context, chatID, userID string) (bool, error) { + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + var member bool + err := m.pool.QueryRow(ctx, + `SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, + chatID, userID, + ).Scan(&member) + if err != nil { + return false, mapErr(err) + } + return member, nil +} + +func (m *Messages) HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + if limit <= 0 || limit > 100 { + return domain.Page[domain.Message]{}, domain.ErrInvalidArgument + } + cur, err := domain.DecodeCursor(cursor) + if err != nil { + return domain.Page[domain.Message]{}, err + } + scope := "chat:" + chatID + if cursor != "" && cur.Scope != scope { + return domain.Page[domain.Message]{}, domain.ErrInvalidArgument + } + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + var rows pgx.Rows + if cur.IsZero() { + rows, err = m.pool.Query(ctx, ` + SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at + FROM messages m + WHERE m.chat_id = $1 + ORDER BY m.created_at, m.id + LIMIT $2`, + chatID, limit+1, + ) + } else { + rows, err = m.pool.Query(ctx, ` + SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at + FROM messages m + WHERE m.chat_id = $1 + AND (m.created_at, m.id) > ($2, $3::uuid) + ORDER BY m.created_at, m.id + LIMIT $4`, + chatID, cur.CreatedAt, cur.ID, limit+1, + ) + } + if err != nil { + return domain.Page[domain.Message]{}, mapErr(err) + } + out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Message, error) { + var msg domain.Message + err := r.Scan(&msg.ID, &msg.ChatID, &msg.AuthorID, &msg.Text, &msg.CreatedAt) + msg.CreatedAt = msg.CreatedAt.UTC() + return msg, err + }) + if err != nil { + return domain.Page[domain.Message]{}, mapErr(err) + } + + page := domain.Page[domain.Message]{} + if len(out) > limit { + last := out[limit-1] + page.NextCursor = domain.EncodeCursor(domain.Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + Scope: scope, + }) + out = out[:limit] + } + page.Items = out + return page, nil +} diff --git a/app/internal/store/db/users.go b/app/internal/store/db/users.go new file mode 100644 index 0000000..1ce69d3 --- /dev/null +++ b/app/internal/store/db/users.go @@ -0,0 +1,87 @@ +package db + +import ( + "context" + "strings" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type Users struct { + conn +} + +func (u *Users) CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) { + if strings.TrimSpace(username) == "" || strings.TrimSpace(displayName) == "" || passwordHash == "" { + return domain.User{}, domain.ErrInvalidArgument + } + + ctx, cancel := u.withTimeout(ctx) + defer cancel() + + user := domain.User{Username: username, DisplayName: displayName} + err := u.pool.QueryRow(ctx, ` + INSERT INTO users (username, display_name, password_hash) + VALUES ($1, $2, $3) + RETURNING id::text, created_at`, + username, displayName, passwordHash, + ).Scan(&user.ID, &user.CreatedAt) + if err != nil { + return domain.User{}, mapErr(err) + } + user.CreatedAt = user.CreatedAt.UTC() + return user, nil +} + +func (u *Users) UserByID(ctx context.Context, id string) (domain.User, error) { + ctx, cancel := u.withTimeout(ctx) + defer cancel() + + user := domain.User{} + err := u.pool.QueryRow(ctx, ` + SELECT id::text, username, display_name, created_at + FROM users + WHERE id = $1`, + id, + ).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + if err != nil { + err = mapErr(err) + if err == domain.ErrInvalidArgument { + return domain.User{}, domain.ErrNotFound + } + return domain.User{}, err + } + user.CreatedAt = user.CreatedAt.UTC() + return user, nil +} + +func (u *Users) CredentialsByUsername(ctx context.Context, username string) (domain.User, string, error) { + ctx, cancel := u.withTimeout(ctx) + defer cancel() + + user := domain.User{} + var hash string + err := u.pool.QueryRow(ctx, ` + SELECT id::text, username, display_name, created_at, password_hash + FROM users + WHERE username = $1`, + username, + ).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash) + if err != nil { + return domain.User{}, "", mapErr(err) + } + user.CreatedAt = user.CreatedAt.UTC() + return user, hash, nil +} + +func (u *Users) UsernameExists(ctx context.Context, username string) bool { + ctx, cancel := u.withTimeout(ctx) + defer cancel() + + var exists bool + err := u.pool.QueryRow(ctx, + `SELECT EXISTS (SELECT 1 FROM users WHERE username = $1)`, + username, + ).Scan(&exists) + return err == nil && exists +} diff --git a/app/internal/store/memory.go b/app/internal/store/memory.go new file mode 100644 index 0000000..4d76c01 --- /dev/null +++ b/app/internal/store/memory.go @@ -0,0 +1,311 @@ +package store + +import ( + "context" + "strings" + "sync" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "github.com/google/uuid" +) + +var _ Store = (*Memory)(nil) + +type Memory struct { + mu sync.RWMutex + + users map[string]domain.User + byName map[string]string + hashes map[string]string + + chats map[string]*chatBucket + chatOrder []string + + lastTime time.Time + + maxMessages int + messagesTotal int +} + +type chatBucket struct { + chat domain.Chat + members map[string]struct{} + messages []domain.Message +} + +func New() *Memory { + return NewWithLimit(0) +} + +func NewWithLimit(maxMessages int) *Memory { + return &Memory{ + users: make(map[string]domain.User), + byName: make(map[string]string), + hashes: make(map[string]string), + chats: make(map[string]*chatBucket), + maxMessages: maxMessages, + } +} + +func (m *Memory) MessagesTotal() int { + m.mu.RLock() + defer m.mu.RUnlock() + return m.messagesTotal +} + +func (m *Memory) now() time.Time { + t := time.Now().UTC() + if !t.After(m.lastTime) { + t = m.lastTime.Add(time.Nanosecond) + } + m.lastTime = t + return t +} + +func (m *Memory) CreateUser(_ context.Context, username, displayName, passwordHash string) (domain.User, error) { + if strings.TrimSpace(username) == "" || strings.TrimSpace(displayName) == "" { + return domain.User{}, domain.ErrInvalidArgument + } + + m.mu.Lock() + defer m.mu.Unlock() + + if _, taken := m.byName[username]; taken { + return domain.User{}, domain.ErrConflict + } + + u := domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + CreatedAt: m.now(), + } + m.users[u.ID] = u + m.byName[username] = u.ID + m.hashes[u.ID] = passwordHash + return u, nil +} + +func (m *Memory) UserByID(_ context.Context, id string) (domain.User, error) { + m.mu.RLock() + defer m.mu.RUnlock() + u, ok := m.users[id] + if !ok { + return domain.User{}, domain.ErrNotFound + } + return u, nil +} + +func (m *Memory) CredentialsByUsername(_ context.Context, username string) (domain.User, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + id, ok := m.byName[username] + if !ok { + return domain.User{}, "", domain.ErrNotFound + } + return m.users[id], m.hashes[id], nil +} + +func (m *Memory) UsernameExists(_ context.Context, username string) bool { + m.mu.RLock() + defer m.mu.RUnlock() + _, taken := m.byName[username] + return taken +} + +func (m *Memory) CreateChat(_ context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) { + if strings.TrimSpace(title) == "" { + return domain.Chat{}, domain.ErrInvalidArgument + } + if len(memberIDs) == 0 || len(memberIDs) > 100 { + return domain.Chat{}, domain.ErrInvalidArgument + } + + seen := make(map[string]struct{}, len(memberIDs)) + callerInMembers := false + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return domain.Chat{}, domain.ErrInvalidArgument + } + seen[id] = struct{}{} + if id == callerID { + callerInMembers = true + } + } + if !callerInMembers { + return domain.Chat{}, domain.ErrInvalidArgument + } + + m.mu.Lock() + defer m.mu.Unlock() + + for _, id := range memberIDs { + if _, ok := m.users[id]; !ok { + return domain.Chat{}, domain.ErrInvalidArgument + } + } + + members := append([]string(nil), memberIDs...) + + chat := domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: members, + CreatedAt: m.now(), + } + m.chats[chat.ID] = &chatBucket{ + chat: chat, + members: seen, + } + m.chatOrder = append(m.chatOrder, chat.ID) + return cloneChat(chat), nil +} + +func (m *Memory) ChatByID(_ context.Context, callerID, chatID string) (domain.Chat, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + b, ok := m.chats[chatID] + if !ok { + return domain.Chat{}, domain.ErrNotFound + } + if _, member := b.members[callerID]; !member { + return domain.Chat{}, domain.ErrNotFound + } + return cloneChat(b.chat), nil +} + +func (m *Memory) ListChats(_ context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) { + if limit <= 0 || limit > 100 { + return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument + } + c, err := domain.DecodeCursor(cursor) + if err != nil { + return domain.Page[domain.Chat]{}, err + } + if cursor != "" && c.Scope != "chats:"+callerID { + return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument + } + + m.mu.RLock() + defer m.mu.RUnlock() + + out := make([]domain.Chat, 0, limit+1) + for _, id := range m.chatOrder { + b := m.chats[id] + if _, member := b.members[callerID]; !member { + continue + } + if !c.Less(b.chat.CreatedAt, b.chat.ID) { + continue + } + out = append(out, cloneChat(b.chat)) + if len(out) > limit { + break + } + } + + page := domain.Page[domain.Chat]{} + if len(out) > limit { + last := out[limit-1] + page.NextCursor = domain.EncodeCursor(domain.Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + Scope: "chats:" + callerID, + }) + out = out[:limit] + } + page.Items = out + return page, nil +} + +func (m *Memory) AddMessage(_ context.Context, callerID, chatID, text string) (domain.Message, error) { + if strings.TrimSpace(text) == "" { + return domain.Message{}, domain.ErrInvalidArgument + } + + m.mu.Lock() + defer m.mu.Unlock() + + b, ok := m.chats[chatID] + if !ok { + return domain.Message{}, domain.ErrNotFound + } + if _, member := b.members[callerID]; !member { + return domain.Message{}, domain.ErrNotFound + } + + if m.maxMessages > 0 && m.messagesTotal >= m.maxMessages { + return domain.Message{}, domain.ErrUnavailable + } + + msg := domain.Message{ + ID: uuid.NewString(), + ChatID: chatID, + AuthorID: callerID, + Text: text, + CreatedAt: m.now(), + } + b.messages = append(b.messages, msg) + m.messagesTotal++ + return msg, nil +} + +func (m *Memory) ListMessages(_ context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + if limit <= 0 || limit > 100 { + return domain.Page[domain.Message]{}, domain.ErrInvalidArgument + } + c, err := domain.DecodeCursor(cursor) + if err != nil { + return domain.Page[domain.Message]{}, err + } + + if cursor != "" && c.Scope != "chat:"+chatID { + return domain.Page[domain.Message]{}, domain.ErrInvalidArgument + } + + m.mu.RLock() + defer m.mu.RUnlock() + + b, ok := m.chats[chatID] + if !ok { + return domain.Page[domain.Message]{}, domain.ErrNotFound + } + if _, member := b.members[callerID]; !member { + return domain.Page[domain.Message]{}, domain.ErrNotFound + } + + start := 0 + for ; start < len(b.messages); start++ { + if c.Less(b.messages[start].CreatedAt, b.messages[start].ID) { + break + } + } + + end := start + limit + hasMore := end < len(b.messages) + if end > len(b.messages) { + end = len(b.messages) + } + + out := make([]domain.Message, end-start) + copy(out, b.messages[start:end]) + + page := domain.Page[domain.Message]{Items: out} + if hasMore && len(out) > 0 { + last := out[len(out)-1] + page.NextCursor = domain.EncodeCursor(domain.Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + Scope: "chat:" + chatID, + }) + } + return page, nil +} + +func cloneChat(c domain.Chat) domain.Chat { + out := c + out.MemberIDs = append([]string(nil), c.MemberIDs...) + return out +} diff --git a/app/internal/store/store.go b/app/internal/store/store.go new file mode 100644 index 0000000..eff1cc9 --- /dev/null +++ b/app/internal/store/store.go @@ -0,0 +1,32 @@ +package store + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + + +type UserStore interface { + CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) + UserByID(ctx context.Context, id string) (domain.User, error) + CredentialsByUsername(ctx context.Context, username string) (domain.User, string, error) + UsernameExists(ctx context.Context, username string) bool +} + +type ChatStore interface { + CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) + ChatByID(ctx context.Context, callerID, chatID string) (domain.Chat, error) + ListChats(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) +} + +type MessageStore interface { + AddMessage(ctx context.Context, callerID, chatID, text string) (domain.Message, error) + ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) +} + +type Store interface { + UserStore + ChatStore + MessageStore +} diff --git a/app/internal/token/token.go b/app/internal/token/token.go new file mode 100644 index 0000000..eb4cd80 --- /dev/null +++ b/app/internal/token/token.go @@ -0,0 +1,43 @@ +package token + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + "fmt" +) + +const Bytes = 32 + +var encoding = base64.RawURLEncoding + +var EncodedLen = encoding.EncodedLen(Bytes) + +var ErrMalformed = errors.New("token: malformed") + +func New() (plain string, hash []byte, err error) { + buf := make([]byte, Bytes) + if _, err := rand.Read(buf); err != nil { + return "", nil, fmt.Errorf("token: rand: %w", err) + } + plain = encoding.EncodeToString(buf) + return plain, Hash(plain), nil +} + +func Hash(plain string) []byte { + sum := sha256.Sum256([]byte(plain)) + return sum[:] +} + + +func Parse(plain string) ([]byte, error) { + if len(plain) != EncodedLen { + return nil, ErrMalformed + } + raw, err := encoding.DecodeString(plain) + if err != nil || len(raw) != Bytes { + return nil, ErrMalformed + } + return Hash(plain), nil +} diff --git a/app/internal/token/token_test.go b/app/internal/token/token_test.go new file mode 100644 index 0000000..c3f14c3 --- /dev/null +++ b/app/internal/token/token_test.go @@ -0,0 +1,65 @@ +package token + +import ( + "bytes" + "errors" + "testing" +) + +func TestNew_FormatAndHash(t *testing.T) { + plain, hash, err := New() + if err != nil { + t.Fatal(err) + } + if len(plain) != EncodedLen || len(plain) < 32 { + t.Errorf("len(token) = %d, want %d", len(plain), EncodedLen) + } + if len(hash) != 32 { + t.Errorf("len(hash) = %d, want 32", len(hash)) + } + if !bytes.Equal(hash, Hash(plain)) { + t.Error("hash from New differs from Hash(token)") + } +} + +func TestNew_Unique(t *testing.T) { + seen := make(map[string]struct{}, 1000) + for i := 0; i < 1000; i++ { + plain, _, err := New() + if err != nil { + t.Fatal(err) + } + if _, ok := seen[plain]; ok { + t.Fatalf("duplicate token %q", plain) + } + seen[plain] = struct{}{} + } +} + +func TestParse(t *testing.T) { + plain, hash, err := New() + if err != nil { + t.Fatal(err) + } + got, err := Parse(plain) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, hash) { + t.Error("Parse hash differs from New hash") + } + + bad := []string{ + "", + "short", + plain[:EncodedLen-1], + plain + "A", + "+" + plain[1:], // символ не из base64url + "00000000-0000-0000-0000-000000000000", + } + for _, s := range bad { + if _, err := Parse(s); !errors.Is(err, ErrMalformed) { + t.Errorf("Parse(%q) err = %v, want ErrMalformed", s, err) + } + } +} diff --git a/app/internal/validate/chat.go b/app/internal/validate/chat.go new file mode 100644 index 0000000..62bf3f6 --- /dev/null +++ b/app/internal/validate/chat.go @@ -0,0 +1,42 @@ +package validate + +import "fmt" + +func ChatTitle(s string) error { + if !notOnlyWhitespace(s) { + return newError("title", "must not be empty or whitespace only") + } + if !codePointsBetween(s, ChatTitleMinLen, ChatTitleMaxLen) { + return newError("title", fmt.Sprintf("length must be in [%d, %d] code points", ChatTitleMinLen, ChatTitleMaxLen)) + } + return nil +} + +func MemberIDs(ids []string, callerID string) ([]string, error) { + if len(ids) < MemberIDsMin || len(ids) > MemberIDsMax { + return nil, newError("member_ids", fmt.Sprintf("count must be in [%d, %d]", MemberIDsMin, MemberIDsMax)) + } + + out := make([]string, 0, len(ids)) + seen := make(map[string]struct{}, len(ids)) + callerIn := false + for i, raw := range ids { + id, err := CanonicalUUID(fmt.Sprintf("member_ids[%d]", i), raw) + if err != nil { + return nil, err + } + if _, dup := seen[id]; dup { + return nil, newError("member_ids", "must not contain duplicates") + } + seen[id] = struct{}{} + if id == callerID { + callerIn = true + } + out = append(out, id) + } + + if !callerIn { + return nil, newError("member_ids", "must contain caller") + } + return out, nil +} diff --git a/app/internal/validate/message.go b/app/internal/validate/message.go new file mode 100644 index 0000000..acb0c70 --- /dev/null +++ b/app/internal/validate/message.go @@ -0,0 +1,13 @@ +package validate + +import "fmt" + +func MessageText(s string) error { + if !notOnlyWhitespace(s) { + return newError("text", "must not be empty or whitespace only") + } + if !codePointsBetween(s, MessageTextMinLen, MessageTextMaxLen) { + return newError("text", fmt.Sprintf("length must be in [%d, %d] code points", MessageTextMinLen, MessageTextMaxLen)) + } + return nil +} diff --git a/app/internal/validate/rules.go b/app/internal/validate/rules.go new file mode 100644 index 0000000..68de9d9 --- /dev/null +++ b/app/internal/validate/rules.go @@ -0,0 +1,87 @@ +package validate + +import ( + "fmt" + "regexp" + "strings" + "unicode/utf8" + + "github.com/google/uuid" +) + +const ( + UsernameMinLen = 3 + UsernameMaxLen = 32 + + DisplayNameMinLen = 1 + DisplayNameMaxLen = 100 + + PasswordMinLen = 12 + PasswordMaxLen = 128 + + ChatTitleMinLen = 1 + ChatTitleMaxLen = 100 + + MessageTextMinLen = 1 + MessageTextMaxLen = 4000 + + MemberIDsMin = 1 + MemberIDsMax = 100 + + LimitMin = 1 + LimitMax = 100 + LimitDefault = 50 +) + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +func UUID(field, s string) error { + _, err := CanonicalUUID(field, s) + return err +} + + +func CanonicalUUID(field, s string) (string, error) { + if len(s) != 36 { + return "", newError(field, "must be a valid UUID") + } + u, err := uuid.Parse(s) + if err != nil { + return "", newError(field, "must be a valid UUID") + } + return u.String(), nil +} + +func Limit(n int) error { + if n < LimitMin || n > LimitMax { + return newError("limit", fmt.Sprintf("must be in [%d, %d]", LimitMin, LimitMax)) + } + return nil +} + +func codePointsBetween(s string, min, max int) bool { + n := utf8.RuneCountInString(s) + return n >= min && n <= max +} + +func notOnlyWhitespace(s string) bool { + return strings.TrimSpace(s) != "" +} + +type Error struct { + Field string + Reason string +} + +func (e *Error) Error() string { + return e.Field + ": " + e.Reason +} + +func (e *Error) Is(target error) bool { + _, ok := target.(*Error) + return ok +} + +func newError(field, reason string) *Error { + return &Error{Field: field, Reason: reason} +} diff --git a/app/internal/validate/user.go b/app/internal/validate/user.go new file mode 100644 index 0000000..cf97468 --- /dev/null +++ b/app/internal/validate/user.go @@ -0,0 +1,30 @@ +package validate + +import "fmt" + +func Username(s string) error { + if !usernamePattern.MatchString(s) { + return newError("username", fmt.Sprintf("must match [a-z0-9_]{%d,%d}", UsernameMinLen, UsernameMaxLen)) + } + return nil +} + +func DisplayName(s string) error { + if !notOnlyWhitespace(s) { + return newError("display_name", "must not be empty or whitespace only") + } + if !codePointsBetween(s, DisplayNameMinLen, DisplayNameMaxLen) { + return newError("display_name", fmt.Sprintf("length must be in [%d, %d] code points", DisplayNameMinLen, DisplayNameMaxLen)) + } + return nil +} + +func Password(s string) error { + if !notOnlyWhitespace(s) { + return newError("password", "must not be empty or whitespace only") + } + if !codePointsBetween(s, PasswordMinLen, PasswordMaxLen) { + return newError("password", fmt.Sprintf("length must be in [%d, %d] code points", PasswordMinLen, PasswordMaxLen)) + } + return nil +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..c870d06 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,148 @@ +name: mtusi-lab2 + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + valkey_password: + file: ./secrets/valkey_password + cache_url: + file: ./secrets/cache_url + valkey_cache_password: + file: ./secrets/valkey_cache_password + history_cache_url: + file: ./secrets/history_cache_url + +services: + postgres: + image: postgres:17.6-alpine + command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements"] + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - pgdata:/var/lib/postgresql/data + ports: + - "127.0.0.1:${POSTGRES_PORT:-5432}:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 10s + restart: unless-stopped + + valkey: + image: valkey/valkey:8.1.3-alpine + command: + - /bin/sh + - -c + - >- + exec valkey-server + --appendonly yes + --appendfsync everysec + --maxmemory 128mb + --maxmemory-policy noeviction + --requirepass "$$(cat /run/secrets/valkey_password)" + secrets: + - valkey_password + volumes: + - valkeydata:/data + ports: + - "127.0.0.1:${VALKEY_PORT:-6379}:6379" + healthcheck: + test: + - CMD-SHELL + - 'valkey-cli -a "$$(cat /run/secrets/valkey_password)" ping 2>/dev/null | grep -q PONG' + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + + valkey-cache: + image: valkey/valkey:8.1.3-alpine + command: + - /bin/sh + - -c + - >- + exec valkey-server + --save "" + --appendonly no + --maxmemory 64mb + --maxmemory-policy allkeys-lru + --requirepass "$$(cat /run/secrets/valkey_cache_password)" + secrets: + - valkey_cache_password + ports: + - "127.0.0.1:${VALKEY_CACHE_PORT:-6380}:6379" + healthcheck: + test: + - CMD-SHELL + - 'valkey-cli -a "$$(cat /run/secrets/valkey_cache_password)" ping 2>/dev/null | grep -q PONG' + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + + + migrate: + build: + context: . + target: migrate + environment: + DATABASE_URL_FILE: /run/secrets/database_url + secrets: + - database_url + depends_on: + postgres: + condition: service_healthy + restart: "no" + + api: + build: . + env_file: .env + environment: + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + HISTORY_CACHE: ${HISTORY_CACHE:-safe} + HISTORY_CACHE_URL_FILE: /run/secrets/history_cache_url + HISTORY_CACHE_TTL_SECONDS: ${HISTORY_CACHE_TTL_SECONDS:-30} + HISTORY_CACHE_FILL_DELAY_MS: ${HISTORY_CACHE_FILL_DELAY_MS:-0} + secrets: + - database_url + - cache_url + - history_cache_url + ports: + - "${API_PUBLISH_PORT:-8080}:8080" + depends_on: + postgres: + condition: service_healthy + valkey: + condition: service_healthy + migrate: + condition: service_completed_successfully + valkey-cache: + condition: service_started + required: false + restart: unless-stopped + + cachebench: + profiles: ["bench"] + build: + context: . + target: cachebench + secrets: + - database_url + - history_cache_url + volumes: + - ./evidence:/evidence + restart: "no" + +volumes: + pgdata: + valkeydata: diff --git a/evidence/checks.txt b/evidence/checks.txt new file mode 100644 index 0000000..452017d --- /dev/null +++ b/evidence/checks.txt @@ -0,0 +1,17 @@ +# Проверки (2026-10-29T07:01:34Z), Windows 10 + Docker Desktop 27.2.0 +## make check (Windows: PYTHONUTF8=1 — скрипт skeleton читает .py в кодировке ОС) +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +## make test (smoke) +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. +## go test ./... (unit/HTTP, без инфраструктуры; интеграционные пропускаются) +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http 3.444s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/cache 0.731s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config 0.411s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password 0.401s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db 0.917s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token 0.365s +## secrets/.env вне Git +.gitignore:2:.env .env +.gitignore:5:secrets/ secrets/x +## формат хеша пароля в БД пользователей, зарегистрированных через API (только префикс параметров) +$argon2id$v=19$m=19456,t=2,p=1$$ diff --git a/evidence/explain.txt b/evidence/explain.txt new file mode 100644 index 0000000..1856d45 --- /dev/null +++ b/evidence/explain.txt @@ -0,0 +1,131 @@ +# EXPLAIN (ANALYZE, BUFFERS) истории сообщений +date_utc: 2026-10-29T06:44:11Z +postgres: 17.6 +messages total: 54682 +target chat (explain_seed_0) messages: 12000 +indexes on messages: CREATE UNIQUE INDEX messages_pkey ON public.messages USING btree (id); CREATE INDEX messages_chat_id_created_at_id_idx ON public.messages USING btree (chat_id, created_at, id) + +Pager usage is off. +PREPARE +PREPARE +PREPARE +=== 1. Проверка членства (PK chat_members), generic plan +SET + QUERY PLAN +-------------------------------------------------------------------------------------------------------------- + Result (cost=1.72..1.73 rows=1 width=1) (actual time=0.024..0.025 rows=1 loops=1) + Buffers: shared hit=1 + InitPlan 1 + -> Seq Scan on chat_members (cost=0.00..1.72 rows=1 width=0) (actual time=0.021..0.022 rows=1 loops=1) + Filter: ((chat_id = $1) AND (user_id = $2)) + Rows Removed by Filter: 39 + Buffers: shared hit=1 + Planning: + Buffers: shared hit=40 + Planning Time: 1.240 ms + Execution Time: 0.079 ms +(11 rows) + +=== 2. Первая страница, limit 51 (50 + 1 для next_cursor), custom plan +SET + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=0.41..21.35 rows=51 width=181) (actual time=0.072..0.136 rows=51 loops=1) + Buffers: shared hit=10 + -> Index Scan using messages_chat_id_created_at_id_idx on messages m (cost=0.41..4907.70 rows=11955 width=181) (actual time=0.071..0.128 rows=51 loops=1) + Index Cond: (chat_id = '7123ea42-c7c8-4598-b6af-37cec6e4e6b0'::uuid) + Buffers: shared hit=10 + Planning: + Buffers: shared hit=12 + Planning Time: 0.508 ms + Execution Time: 0.184 ms +(9 rows) + +=== 2g. Первая страница, generic plan (так её выполняет pgx после 5 повторов) +SET + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=0.41..419.97 rows=342 width=181) (actual time=0.044..0.086 rows=51 loops=1) + Buffers: shared hit=10 + -> Index Scan using messages_chat_id_created_at_id_idx on messages m (cost=0.41..4193.54 rows=3418 width=181) (actual time=0.042..0.077 rows=51 loops=1) + Index Cond: (chat_id = $1) + Buffers: shared hit=10 + Planning Time: 0.155 ms + Execution Time: 0.138 ms +(7 rows) + +=== 3. Глубокая страница после 10 000 сообщений, custom plan +SET + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Limit (cost=0.41..136.69 rows=51 width=181) (actual time=0.066..0.106 rows=51 loops=1) + Buffers: shared hit=5 + -> Index Scan using messages_chat_id_created_at_id_idx on messages m (cost=0.41..2840.87 rows=1063 width=181) (actual time=0.065..0.098 rows=51 loops=1) + Index Cond: ((chat_id = '7123ea42-c7c8-4598-b6af-37cec6e4e6b0'::uuid) AND (ROW(created_at, id) > ROW('2026-10-28 06:42:20.06342+00'::timestamp with time zone, '522a8c8d-5115-4b9a-b0c9-0038ba42a7f9'::uuid))) + Buffers: shared hit=5 + Planning Time: 0.175 ms + Execution Time: 0.311 ms +(7 rows) + +=== 3g. Глубокая страница, generic plan: граница курсора остаётся в Index Cond +SET + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=0.41..297.73 rows=114 width=181) (actual time=0.064..0.102 rows=51 loops=1) + Buffers: shared hit=5 + -> Index Scan using messages_chat_id_created_at_id_idx on messages m (cost=0.41..2970.95 rows=1139 width=181) (actual time=0.062..0.093 rows=51 loops=1) + Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3))) + Buffers: shared hit=5 + Planning Time: 0.159 ms + Execution Time: 0.202 ms +(7 rows) + +=== 3x. Было до исправления: один SQL с «$2 IS NULL OR ...», generic plan — курсор в Filter +PREPARE + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=0.41..417.67 rows=115 width=181) (actual time=2.282..2.322 rows=51 loops=1) + Buffers: shared hit=324 + -> Index Scan using messages_chat_id_created_at_id_idx on messages m (cost=0.41..4176.62 rows=1151 width=181) (actual time=2.279..2.313 rows=51 loops=1) + Index Cond: (chat_id = $1) + Filter: (($2 IS NULL) OR (ROW(created_at, id) > ROW($2, $3))) + Rows Removed by Filter: 10000 + Buffers: shared hit=324 + Planning Time: 0.187 ms + Execution Time: 2.393 ms +(9 rows) + +=== 4. Контроль: та же глубокая страница через OFFSET 10000 (так делать нельзя) + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=707.35..710.95 rows=51 width=24) (actual time=2.656..2.669 rows=51 loops=1) + Buffers: shared hit=135 + -> Index Only Scan using messages_chat_id_created_at_id_idx on messages m (cost=0.41..845.55 rows=11955 width=24) (actual time=0.050..1.982 rows=10051 loops=1) + Index Cond: (chat_id = '7123ea42-c7c8-4598-b6af-37cec6e4e6b0'::uuid) + Heap Fetches: 40 + Buffers: shared hit=135 + Planning Time: 0.200 ms + Execution Time: 2.720 ms +(8 rows) + +=== 5. Контроль: без индекса (enable_indexscan/bitmapscan off) — полный scan и сортировка +SET +SET +SET +SET + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=1988.34..1988.47 rows=51 width=181) (actual time=11.196..11.208 rows=51 loops=1) + Buffers: shared hit=986 + -> Sort (cost=1988.34..1991.00 rows=1063 width=181) (actual time=11.195..11.199 rows=51 loops=1) + Sort Key: created_at, id + Sort Method: top-N heapsort Memory: 38kB + Buffers: shared hit=986 + -> Seq Scan on messages m (cost=0.00..1952.88 rows=1063 width=181) (actual time=1.877..10.115 rows=2000 loops=1) + Filter: ((chat_id = '7123ea42-c7c8-4598-b6af-37cec6e4e6b0'::uuid) AND (ROW(created_at, id) > ROW('2026-10-28 06:42:20.06342+00'::timestamp with time zone, '522a8c8d-5115-4b9a-b0c9-0038ba42a7f9'::uuid))) + Rows Removed by Filter: 52682 + Buffers: shared hit=980 + Planning Time: 0.181 ms + Execution Time: 11.292 ms +(12 rows) + diff --git a/evidence/failures.txt b/evidence/failures.txt new file mode 100644 index 0000000..55f55da --- /dev/null +++ b/evidence/failures.txt @@ -0,0 +1,38 @@ +# sh scripts/failures-tests.sh (2026-10-29T07:49:41Z, Darwin arm64, Docker 29.2.1) +=== RUN TestFailures +=== RUN TestFailures/неверный_пароль_→_401_Basic,_неотличим_от_неизвестного_username + failures_test.go:180: статусы 401/401, challenge "Basic realm=\"messenger\", charset=\"UTF-8\"" +=== RUN TestFailures/X-User-Id_без_Bearer_→_401 + failures_test.go:192: status 401 +=== RUN TestFailures/Basic_на_бизнес-endpoint_→_401 + failures_test.go:200: status 401 +=== RUN TestFailures/logout_→_204,_тот_же_токен_→_401,_повторный_logout_→_401,_другая_сессия_жива + failures_test.go:214: статусы [204 401 401 200] +=== RUN TestFailures/expiry_при_SESSION_TTL_SECONDS=2:_200_сразу,_401_через_3_с + failures_test.go:243: expires_at через 1.5 с, статусы 200 → 401 +=== RUN TestFailures/Valkey_сессий_остановлен:_Bearer_→_503,_без_токена_→_401,_вход_→_503,_ready_→_503 + failures_test.go:258: me 503, anon 401, login 503, ready 503 +=== RUN TestFailures/Valkey_сессий_восстановлен:_прежний_токен_снова_действителен_(AOF) + failures_test.go:269: ready через 0.1 с после start, me 200 +=== RUN TestFailures/PostgreSQL_остановлен:_чтение/запись_→_503_без_деталей,_ready_→_503 + failures_test.go:287: list 503 (кэш может отдать страницу), send 503, ready 503, утечка деталей: false +=== RUN TestFailures/PostgreSQL_восстановлен:_запись_201_тем_же_токеном + failures_test.go:300: ready через 0.6 с после start, send 201 +=== RUN TestFailures/Valkey-кэш_остановлен:_ready_200,_запись_201,_чтение_200_из_PostgreSQL_с_новым_сообщением + failures_test.go:316: ready 200, send 201, list 200, сообщений 2 +=== RUN TestFailures/Valkey-кэш_восстановлен:_история_полная_и_одинаковая_при_промахе_и_попадании + failures_test.go:329: статусы 200/200, сообщений 2 +--- PASS: TestFailures (28.04s) + --- PASS: TestFailures/неверный_пароль_→_401_Basic,_неотличим_от_неизвестного_username (0.04s) + --- PASS: TestFailures/X-User-Id_без_Bearer_→_401 (0.00s) + --- PASS: TestFailures/Basic_на_бизнес-endpoint_→_401 (0.00s) + --- PASS: TestFailures/logout_→_204,_тот_же_токен_→_401,_повторный_logout_→_401,_другая_сессия_жива (0.02s) + --- PASS: TestFailures/expiry_при_SESSION_TTL_SECONDS=2:_200_сразу,_401_через_3_с (17.30s) + --- PASS: TestFailures/Valkey_сессий_остановлен:_Bearer_→_503,_без_токена_→_401,_вход_→_503,_ready_→_503 (0.43s) + --- PASS: TestFailures/Valkey_сессий_восстановлен:_прежний_токен_снова_действителен_(AOF) (0.14s) + --- PASS: TestFailures/PostgreSQL_остановлен:_чтение/запись_→_503_без_деталей,_ready_→_503 (0.25s) + --- PASS: TestFailures/PostgreSQL_восстановлен:_запись_201_тем_же_токеном (0.64s) + --- PASS: TestFailures/Valkey-кэш_остановлен:_ready_200,_запись_201,_чтение_200_из_PostgreSQL_с_новым_сообщением (0.33s) + --- PASS: TestFailures/Valkey-кэш_восстановлен:_история_полная_и_одинаковая_при_промахе_и_попадании (7.15s) +PASS +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/e2e 28.195s diff --git a/evidence/integration-tests.txt b/evidence/integration-tests.txt new file mode 100644 index 0000000..7c09c6d --- /dev/null +++ b/evidence/integration-tests.txt @@ -0,0 +1,34 @@ +=== RUN TestUsernameRace + integration_test.go:83: 20 параллельных регистраций: 1 created, 19 conflict, строк в users: 1 +--- PASS: TestUsernameRace (0.03s) +=== RUN TestCreateChatRollback + integration_test.go:123: неизвестный участник → 400, chats/chat_members без изменений; валидный вызов создаёт 1 чат +--- PASS: TestCreateChatRollback (0.03s) +=== RUN TestMessageRequiresMembership +--- PASS: TestMessageRequiresMembership (0.02s) +PASS +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db 0.973s +=== RUN TestReadAfterWrite_FillRace +=== RUN TestReadAfterWrite_FillRace/naive + history_test.go:150: naive: чтение после подтверждённой записи stale=true +=== RUN TestReadAfterWrite_FillRace/safe + history_test.go:150: safe: чтение после подтверждённой записи stale=false +--- PASS: TestReadAfterWrite_FillRace (0.32s) + --- PASS: TestReadAfterWrite_FillRace/naive (0.11s) + --- PASS: TestReadAfterWrite_FillRace/safe (0.21s) +=== RUN TestStampede_SQLCount +=== RUN TestStampede_SQLCount/naive + history_test.go:195: naive: 50 одновременных промахов → 50 запросов страницы в БД +=== RUN TestStampede_SQLCount/safe + history_test.go:195: safe: 50 одновременных промахов → 1 запросов страницы в БД +--- PASS: TestStampede_SQLCount (0.16s) + --- PASS: TestStampede_SQLCount/naive (0.09s) + --- PASS: TestStampede_SQLCount/safe (0.07s) +=== RUN TestAccessCheckedBeforeCache +--- PASS: TestAccessCheckedBeforeCache (0.01s) +=== RUN TestCacheLossIsOnlyMiss +--- PASS: TestCacheLossIsOnlyMiss (0.01s) +=== RUN TestCacheDown_Bypass +--- PASS: TestCacheDown_Bypass (0.03s) +PASS +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/cache 1.197s diff --git a/evidence/migrations.txt b/evidence/migrations.txt new file mode 100644 index 0000000..28983e1 --- /dev/null +++ b/evidence/migrations.txt @@ -0,0 +1,34 @@ +# Миграции (2026-10-29T07:04:02Z) + +## 1. С нуля (проект mtusi-lab2-fresh, пустой volume) + Container mtusi-lab2-fresh-postgres-1 Healthy +volume: mtusi-lab2-fresh_pgdata +2026/10/29 07:04:09 OK 00001_create_users_table.sql (14.67ms) +2026/10/29 07:04:09 OK 00002_create_chats_table.sql (6.31ms) +2026/10/29 07:04:09 OK 00003_create_chat_members_table.sql (9.24ms) +2026/10/29 07:04:09 OK 00004_create_messages_table.sql (10.81ms) +2026/10/29 07:04:09 goose: successfully migrated database to version: 4 + List of relations + Schema | Name | Type | Owner +--------+------------------+-------+----------- + public | chat_members | table | messenger + public | chats | table | messenger + public | goose_db_version | table | messenger + public | messages | table | messenger + public | users | table | messenger +(5 rows) + +0|t +1|t +2|t +3|t +4|t +### повторный migrate на том же свежем volume +2026/10/29 07:04:11 goose: no migrations to run. current version: 4 + Volume mtusi-lab2-fresh_pgdata Removed + Network mtusi-lab2-fresh_default Removed + +## 2. Повторный migrate на рабочем стенде (volume mtusi-lab2_pgdata сохраняется) +до: 136 54 125 69369 +2026/10/29 07:04:14 goose: no migrations to run. current version: 4 +после: 136 54 125 69369 diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 0000000..6baa4e4 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,17 @@ +# Persistence (2026-10-29T07:04:40Z), hook: scripts/restart.cmd -> scripts/restart.sh +## до +api running started=2026-10-29T07:04:32.717094139Z restarts=0 mounts= +postgres running started=2026-10-29T07:04:25.352390132Z restarts=0 mounts= mtusi-lab2_pgdata +valkey running started=2026-10-29T07:04:25.369531149Z restarts=0 mounts=mtusi-lab2_valkeydata +valkey-cache running started=2026-10-29T07:04:25.347946376Z restarts=0 mounts= f01d8591cce3dd7e8d85ff09ae7b10fdd601afbe5e3895c1abb1534a44053e5c +## тест +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +## после +api running started=2026-10-29T07:04:52.234778059Z restarts=0 mounts= +postgres running started=2026-10-29T07:04:45.042964873Z restarts=0 mounts= mtusi-lab2_pgdata +valkey running started=2026-10-29T07:04:45.036034143Z restarts=0 mounts=mtusi-lab2_valkeydata +valkey-cache running started=2026-10-29T07:04:45.047757956Z restarts=0 mounts=f01d8591cce3dd7e8d85ff09ae7b10fdd601afbe5e3895c1abb1534a44053e5c +## volumes +mtusi-lab2_pgdata created=2026-10-29T06:20:03Z +mtusi-lab2_valkeydata created=2026-10-29T06:20:03Z diff --git a/evidence/track1/env.txt b/evidence/track1/env.txt new file mode 100644 index 0000000..4a865fa --- /dev/null +++ b/evidence/track1/env.txt @@ -0,0 +1,11 @@ +date_utc: 2026-10-29T07:00:31Z +commit: 65003b6 (+ рабочее дерево) +docker: 27.2.0 ncpu=12 mem_bytes=1994612736 +limits: CPU/RAM-лимиты контейнерам не заданы; DB_MAX_CONNS=10, APP_MAX_INFLIGHT=64 +CONTAINER REPOSITORY TAG IMAGE ID SIZE +mtusi-lab2-api-1 mtusi-lab2-api latest 923ab3590f15 20.8MB +mtusi-lab2-migrate-1 mtusi-lab2-migrate latest 378380d8d69c 20.4MB +mtusi-lab2-postgres-1 postgres 17.6-alpine d741b3768746 278MB +mtusi-lab2-valkey-1 valkey/valkey 8.1.3-alpine 49292cc259b2 47.9MB +mtusi-lab2-valkey-cache-1 valkey/valkey 8.1.3-alpine 49292cc259b2 47.9MB +profile: readers=32 writers=2 write_interval=100ms duration=30s warmup=3s seed=150 repeats=3 diff --git a/evidence/track1/naive-d0-r1.json b/evidence/track1/naive-d0-r1.json new file mode 100644 index 0000000..fb9e0ae --- /dev/null +++ b/evidence/track1/naive-d0-r1.json @@ -0,0 +1,351 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 160470, + "keyspace_misses": 3568 + }, + "date_utc": "2026-10-29T06:52:16Z", + "duration_s": 30, + "error_statuses": {}, + "label": "naive-d0-r1", + "raw_checks": 456, + "raw_violations": 6, + "read_errors": 0, + "read_p50_ms": 9.883, + "read_p95_ms": 25.477, + "read_p99_ms": 36.004, + "read_rps": 2711.5666666666666, + "readers": 32, + "reads_ok": 81347, + "seed_messages": 150, + "sql": { + "history_page_calls": 3535, + "history_page_total_ms": 871.9389290000001, + "insert_message_calls": 456, + "membership_calls": 0, + "total_calls": 3991 + }, + "sql_history_per_read": 0.04345581275277515, + "sql_read_path_per_read": 0.04345581275277515, + "stale_checks": 81187, + "stale_reads": 1369, + "timeline": [ + { + "s": 0, + "reads": 3074, + "read_errors": 0, + "read_p95_ms": 28.362, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 3292, + "read_errors": 0, + "read_p95_ms": 19.858, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 2693, + "read_errors": 0, + "read_p95_ms": 23.112, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 2485, + "read_errors": 0, + "read_p95_ms": 23.91, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 2291, + "read_errors": 0, + "read_p95_ms": 26.044, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 2 + }, + { + "s": 5, + "reads": 2042, + "read_errors": 0, + "read_p95_ms": 28.304, + "writes": 15, + "write_errors": 0, + "raw_violations": 2, + "stale_reads": 468 + }, + { + "s": 6, + "reads": 1710, + "read_errors": 0, + "read_p95_ms": 34.561, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 3380, + "read_errors": 0, + "read_p95_ms": 25.831, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 3398, + "read_errors": 0, + "read_p95_ms": 17.932, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 2858, + "read_errors": 0, + "read_p95_ms": 20.627, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 2470, + "read_errors": 0, + "read_p95_ms": 24.714, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 2264, + "read_errors": 0, + "read_p95_ms": 26.168, + "writes": 16, + "write_errors": 0, + "raw_violations": 1, + "stale_reads": 318 + }, + { + "s": 12, + "reads": 1509, + "read_errors": 0, + "read_p95_ms": 43.243, + "writes": 14, + "write_errors": 0, + "raw_violations": 2, + "stale_reads": 4 + }, + { + "s": 13, + "reads": 1592, + "read_errors": 0, + "read_p95_ms": 38.36, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 174 + }, + { + "s": 14, + "reads": 4711, + "read_errors": 0, + "read_p95_ms": 12.877, + "writes": 16, + "write_errors": 0, + "raw_violations": 1, + "stale_reads": 400 + }, + { + "s": 15, + "reads": 3065, + "read_errors": 0, + "read_p95_ms": 18.022, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 2807, + "read_errors": 0, + "read_p95_ms": 20.752, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 3 + }, + { + "s": 17, + "reads": 2388, + "read_errors": 0, + "read_p95_ms": 26.059, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 1697, + "read_errors": 0, + "read_p95_ms": 35.49, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 1925, + "read_errors": 0, + "read_p95_ms": 30.222, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 3579, + "read_errors": 0, + "read_p95_ms": 22.95, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 3890, + "read_errors": 0, + "read_p95_ms": 14.984, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 3334, + "read_errors": 0, + "read_p95_ms": 17.698, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 2174, + "read_errors": 0, + "read_p95_ms": 27.826, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 2167, + "read_errors": 0, + "read_p95_ms": 26.961, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 2115, + "read_errors": 0, + "read_p95_ms": 27.228, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 2028, + "read_errors": 0, + "read_p95_ms": 28.105, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 4507, + "read_errors": 0, + "read_p95_ms": 13.739, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 3190, + "read_errors": 0, + "read_p95_ms": 19.737, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 2710, + "read_errors": 0, + "read_p95_ms": 21.027, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 30, + "reads": 2, + "read_errors": 0, + "read_p95_ms": 6.796, + "writes": 0, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 14.544, + "write_p95_ms": 27.795, + "writers": 2, + "writes_ok": 456 +} \ No newline at end of file diff --git a/evidence/track1/naive-d0-r1.stats.txt b/evidence/track1/naive-d0-r1.stats.txt new file mode 100644 index 0000000..d4d6aac --- /dev/null +++ b/evidence/track1/naive-d0-r1.stats.txt @@ -0,0 +1,64 @@ +mtusi-lab2-api-1;12.18%;43.08MiB / 1.858GiB +mtusi-lab2-postgres-1;59.23%;67.64MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;14.16%;5.043MiB / 1.858GiB +mtusi-lab2-valkey-1;6.68%;6.832MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;66.83%;9.887MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;321.48%;9.895MiB / 1.858GiB +mtusi-lab2-api-1;528.33%;15.71MiB / 1.858GiB +mtusi-lab2-postgres-1;12.43%;69.35MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.11%;5.48MiB / 1.858GiB +mtusi-lab2-valkey-1;17.72%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;266.95%;9.965MiB / 1.858GiB +mtusi-lab2-api-1;473.53%;15.47MiB / 1.858GiB +mtusi-lab2-postgres-1;14.02%;69.58MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.88%;5.59MiB / 1.858GiB +mtusi-lab2-valkey-1;25.46%;6.859MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;335.81%;10.09MiB / 1.858GiB +mtusi-lab2-api-1;508.21%;16.8MiB / 1.858GiB +mtusi-lab2-postgres-1;12.51%;69.92MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.09%;5.742MiB / 1.858GiB +mtusi-lab2-valkey-1;20.89%;6.832MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;332.47%;9.734MiB / 1.858GiB +mtusi-lab2-api-1;487.97%;16.41MiB / 1.858GiB +mtusi-lab2-postgres-1;17.56%;69.69MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;62.83%;6.043MiB / 1.858GiB +mtusi-lab2-valkey-1;16.78%;6.875MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;320.87%;10.12MiB / 1.858GiB +mtusi-lab2-api-1;498.67%;17MiB / 1.858GiB +mtusi-lab2-postgres-1;7.39%;69.72MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.30%;5.797MiB / 1.858GiB +mtusi-lab2-valkey-1;21.58%;7.066MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;294.14%;9.758MiB / 1.858GiB +mtusi-lab2-api-1;466.43%;14.83MiB / 1.858GiB +mtusi-lab2-postgres-1;44.78%;69.77MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;50.09%;5.961MiB / 1.858GiB +mtusi-lab2-valkey-1;18.39%;6.836MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;317.88%;10.77MiB / 1.858GiB +mtusi-lab2-api-1;499.77%;16.26MiB / 1.858GiB +mtusi-lab2-postgres-1;10.12%;69.79MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;44.61%;6.219MiB / 1.858GiB +mtusi-lab2-valkey-1;20.77%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;329.67%;11.08MiB / 1.858GiB +mtusi-lab2-api-1;512.69%;17.55MiB / 1.858GiB +mtusi-lab2-postgres-1;10.93%;69.89MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;36.82%;5.895MiB / 1.858GiB +mtusi-lab2-valkey-1;18.32%;6.875MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;279.54%;10.97MiB / 1.858GiB +mtusi-lab2-api-1;494.85%;16.71MiB / 1.858GiB +mtusi-lab2-postgres-1;16.57%;69.89MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;43.70%;5.895MiB / 1.858GiB +mtusi-lab2-valkey-1;23.47%;6.734MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;332.31%;14.08MiB / 1.858GiB +mtusi-lab2-api-1;521.40%;19.5MiB / 1.858GiB +mtusi-lab2-postgres-1;9.87%;69.9MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.74%;6.066MiB / 1.858GiB +mtusi-lab2-valkey-1;17.29%;6.734MiB / 1.858GiB +mtusi-lab2-cachebench-run-3e7d7377799c;268.46%;11.76MiB / 1.858GiB +mtusi-lab2-api-1;501.55%;17.06MiB / 1.858GiB +mtusi-lab2-postgres-1;10.65%;69.92MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;51.40%;5.098MiB / 1.858GiB +mtusi-lab2-valkey-1;23.57%;6.766MiB / 1.858GiB +mtusi-lab2-api-1;0.81%;16.73MiB / 1.858GiB +mtusi-lab2-postgres-1;0.03%;68.39MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.00%;5.094MiB / 1.858GiB +mtusi-lab2-valkey-1;0.38%;6.691MiB / 1.858GiB diff --git a/evidence/track1/naive-d0-r2.json b/evidence/track1/naive-d0-r2.json new file mode 100644 index 0000000..6158dd4 --- /dev/null +++ b/evidence/track1/naive-d0-r2.json @@ -0,0 +1,351 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 122199, + "keyspace_misses": 955 + }, + "date_utc": "2026-10-29T06:52:53Z", + "duration_s": 30, + "error_statuses": {}, + "label": "naive-d0-r2", + "raw_checks": 444, + "raw_violations": 354, + "read_errors": 0, + "read_p50_ms": 13.902, + "read_p95_ms": 31.327, + "read_p99_ms": 41.109, + "read_rps": 2031.1666666666667, + "readers": 32, + "reads_ok": 60935, + "seed_messages": 150, + "sql": { + "history_page_calls": 588, + "history_page_total_ms": 157.68475300000014, + "insert_message_calls": 444, + "membership_calls": 0, + "total_calls": 1032 + }, + "sql_history_per_read": 0.009649626651349798, + "sql_read_path_per_read": 0.009649626651349798, + "stale_checks": 60903, + "stale_reads": 44661, + "timeline": [ + { + "s": 0, + "reads": 3460, + "read_errors": 0, + "read_p95_ms": 27.585, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 4133, + "read_errors": 0, + "read_p95_ms": 14.324, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 3014, + "read_errors": 0, + "read_p95_ms": 20.027, + "writes": 16, + "write_errors": 0, + "raw_violations": 1, + "stale_reads": 383 + }, + { + "s": 3, + "reads": 2061, + "read_errors": 0, + "read_p95_ms": 30.657, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 2056, + "read_errors": 0, + "read_p95_ms": 28.392, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 1989, + "read_errors": 0, + "read_p95_ms": 28.419, + "writes": 16, + "write_errors": 0, + "raw_violations": 2, + "stale_reads": 56 + }, + { + "s": 6, + "reads": 1842, + "read_errors": 0, + "read_p95_ms": 32.519, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1842 + }, + { + "s": 7, + "reads": 1749, + "read_errors": 0, + "read_p95_ms": 34.802, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1749 + }, + { + "s": 8, + "reads": 1586, + "read_errors": 0, + "read_p95_ms": 39.847, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1586 + }, + { + "s": 9, + "reads": 1755, + "read_errors": 0, + "read_p95_ms": 33.759, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 1755 + }, + { + "s": 10, + "reads": 1751, + "read_errors": 0, + "read_p95_ms": 33.467, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 1751 + }, + { + "s": 11, + "reads": 1885, + "read_errors": 0, + "read_p95_ms": 31.783, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1885 + }, + { + "s": 12, + "reads": 1898, + "read_errors": 0, + "read_p95_ms": 31.432, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 1898 + }, + { + "s": 13, + "reads": 1682, + "read_errors": 0, + "read_p95_ms": 36.67, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1682 + }, + { + "s": 14, + "reads": 1698, + "read_errors": 0, + "read_p95_ms": 34.403, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1698 + }, + { + "s": 15, + "reads": 1840, + "read_errors": 0, + "read_p95_ms": 31.447, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 1840 + }, + { + "s": 16, + "reads": 1868, + "read_errors": 0, + "read_p95_ms": 33.06, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1868 + }, + { + "s": 17, + "reads": 1867, + "read_errors": 0, + "read_p95_ms": 33.45, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1867 + }, + { + "s": 18, + "reads": 2033, + "read_errors": 0, + "read_p95_ms": 28.093, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 2033 + }, + { + "s": 19, + "reads": 1557, + "read_errors": 0, + "read_p95_ms": 40.4, + "writes": 13, + "write_errors": 0, + "raw_violations": 13, + "stale_reads": 1557 + }, + { + "s": 20, + "reads": 1843, + "read_errors": 0, + "read_p95_ms": 31.513, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 1843 + }, + { + "s": 21, + "reads": 1996, + "read_errors": 0, + "read_p95_ms": 29.231, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 1996 + }, + { + "s": 22, + "reads": 1952, + "read_errors": 0, + "read_p95_ms": 30.378, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 1952 + }, + { + "s": 23, + "reads": 2048, + "read_errors": 0, + "read_p95_ms": 29.033, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 2048 + }, + { + "s": 24, + "reads": 1834, + "read_errors": 0, + "read_p95_ms": 33.234, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1834 + }, + { + "s": 25, + "reads": 1656, + "read_errors": 0, + "read_p95_ms": 36.668, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 1656 + }, + { + "s": 26, + "reads": 1919, + "read_errors": 0, + "read_p95_ms": 31.381, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 1919 + }, + { + "s": 27, + "reads": 1953, + "read_errors": 0, + "read_p95_ms": 30.687, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 1953 + }, + { + "s": 28, + "reads": 1899, + "read_errors": 0, + "read_p95_ms": 30.171, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 1899 + }, + { + "s": 29, + "reads": 2109, + "read_errors": 0, + "read_p95_ms": 26.965, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 2109 + }, + { + "s": 30, + "reads": 2, + "read_errors": 0, + "read_p95_ms": 4.941, + "writes": 0, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 2 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 15.291, + "write_p95_ms": 33.75, + "writers": 2, + "writes_ok": 444 +} \ No newline at end of file diff --git a/evidence/track1/naive-d0-r2.stats.txt b/evidence/track1/naive-d0-r2.stats.txt new file mode 100644 index 0000000..e981d84 --- /dev/null +++ b/evidence/track1/naive-d0-r2.stats.txt @@ -0,0 +1,63 @@ +mtusi-lab2-api-1;36.60%;69.11MiB / 1.858GiB +mtusi-lab2-postgres-1;3.03%;69.97MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.33%;5.07MiB / 1.858GiB +mtusi-lab2-valkey-1;0.48%;6.691MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;72.01%;9.832MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;323.38%;10.06MiB / 1.858GiB +mtusi-lab2-api-1;492.28%;18.88MiB / 1.858GiB +mtusi-lab2-postgres-1;8.81%;70.17MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.71%;5.629MiB / 1.858GiB +mtusi-lab2-valkey-1;16.64%;6.711MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;295.24%;9.836MiB / 1.858GiB +mtusi-lab2-api-1;472.34%;16.76MiB / 1.858GiB +mtusi-lab2-postgres-1;7.36%;70.18MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;42.71%;6.043MiB / 1.858GiB +mtusi-lab2-valkey-1;29.65%;6.984MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;344.94%;11.41MiB / 1.858GiB +mtusi-lab2-api-1;481.90%;18.24MiB / 1.858GiB +mtusi-lab2-postgres-1;4.81%;70.19MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;33.08%;5.887MiB / 1.858GiB +mtusi-lab2-valkey-1;18.19%;6.723MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;342.13%;12.32MiB / 1.858GiB +mtusi-lab2-api-1;475.56%;17.17MiB / 1.858GiB +mtusi-lab2-postgres-1;1.13%;70.19MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;31.20%;5.633MiB / 1.858GiB +mtusi-lab2-valkey-1;15.61%;6.73MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;336.86%;11.32MiB / 1.858GiB +mtusi-lab2-api-1;495.66%;19.32MiB / 1.858GiB +mtusi-lab2-postgres-1;5.09%;70.21MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.59%;5.027MiB / 1.858GiB +mtusi-lab2-valkey-1;16.92%;6.73MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;345.50%;11.57MiB / 1.858GiB +mtusi-lab2-api-1;478.78%;18.33MiB / 1.858GiB +mtusi-lab2-postgres-1;1.54%;70.21MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;33.73%;4.926MiB / 1.858GiB +mtusi-lab2-valkey-1;16.32%;6.641MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;314.05%;11.34MiB / 1.858GiB +mtusi-lab2-api-1;481.30%;18.9MiB / 1.858GiB +mtusi-lab2-postgres-1;1.17%;70.23MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;35.73%;5.066MiB / 1.858GiB +mtusi-lab2-valkey-1;16.79%;6.621MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;347.93%;12.16MiB / 1.858GiB +mtusi-lab2-api-1;510.72%;19MiB / 1.858GiB +mtusi-lab2-postgres-1;1.14%;70.24MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.20%;4.918MiB / 1.858GiB +mtusi-lab2-valkey-1;16.87%;6.637MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;339.39%;12.18MiB / 1.858GiB +mtusi-lab2-api-1;522.35%;17.63MiB / 1.858GiB +mtusi-lab2-postgres-1;1.66%;70.24MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.22%;4.641MiB / 1.858GiB +mtusi-lab2-valkey-1;17.08%;6.625MiB / 1.858GiB +mtusi-lab2-cachebench-run-dce66eaf820e;318.56%;12.42MiB / 1.858GiB +mtusi-lab2-api-1;490.49%;19.01MiB / 1.858GiB +mtusi-lab2-postgres-1;1.97%;70.66MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.63%;5.547MiB / 1.858GiB +mtusi-lab2-valkey-1;17.49%;6.406MiB / 1.858GiB +mtusi-lab2-api-1;514.27%;18.54MiB / 1.858GiB +mtusi-lab2-postgres-1;1.25%;70.28MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;35.06%;4.648MiB / 1.858GiB +mtusi-lab2-valkey-1;17.29%;6.402MiB / 1.858GiB +mtusi-lab2-api-1;0.92%;17.48MiB / 1.858GiB +mtusi-lab2-postgres-1;0.05%;68.75MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.14%;4.645MiB / 1.858GiB +mtusi-lab2-valkey-1;0.37%;6.355MiB / 1.858GiB diff --git a/evidence/track1/naive-d0-r3.json b/evidence/track1/naive-d0-r3.json new file mode 100644 index 0000000..c5efeb7 --- /dev/null +++ b/evidence/track1/naive-d0-r3.json @@ -0,0 +1,351 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 211940, + "keyspace_misses": 1443 + }, + "date_utc": "2026-10-29T06:53:30Z", + "duration_s": 30, + "error_statuses": {}, + "label": "naive-d0-r3", + "raw_checks": 479, + "raw_violations": 352, + "read_errors": 0, + "read_p50_ms": 7.716, + "read_p95_ms": 18.089, + "read_p99_ms": 27.944, + "read_rps": 3532.9, + "readers": 32, + "reads_ok": 105987, + "seed_messages": 150, + "sql": { + "history_page_calls": 1087, + "history_page_total_ms": 258.45237099999986, + "insert_message_calls": 479, + "membership_calls": 0, + "total_calls": 1566 + }, + "sql_history_per_read": 0.01025597478936096, + "sql_read_path_per_read": 0.01025597478936096, + "stale_checks": 105923, + "stale_reads": 82701, + "timeline": [ + { + "s": 0, + "reads": 3508, + "read_errors": 0, + "read_p95_ms": 27, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 3764, + "read_errors": 0, + "read_p95_ms": 16.303, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 3135, + "read_errors": 0, + "read_p95_ms": 18.589, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 2558, + "read_errors": 0, + "read_p95_ms": 23.218, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 1755, + "read_errors": 0, + "read_p95_ms": 36.698, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 1809, + "read_errors": 0, + "read_p95_ms": 33.076, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 1719, + "read_errors": 0, + "read_p95_ms": 35.265, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 4116, + "read_errors": 0, + "read_p95_ms": 15.261, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 3864, + "read_errors": 0, + "read_p95_ms": 15.018, + "writes": 16, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 2942 + }, + { + "s": 9, + "reads": 3394, + "read_errors": 0, + "read_p95_ms": 18.364, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3394 + }, + { + "s": 10, + "reads": 3123, + "read_errors": 0, + "read_p95_ms": 18.738, + "writes": 14, + "write_errors": 0, + "raw_violations": 14, + "stale_reads": 3123 + }, + { + "s": 11, + "reads": 3581, + "read_errors": 0, + "read_p95_ms": 16.863, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3581 + }, + { + "s": 12, + "reads": 3908, + "read_errors": 0, + "read_p95_ms": 14.857, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3908 + }, + { + "s": 13, + "reads": 3710, + "read_errors": 0, + "read_p95_ms": 15.222, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3710 + }, + { + "s": 14, + "reads": 3905, + "read_errors": 0, + "read_p95_ms": 14.509, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3905 + }, + { + "s": 15, + "reads": 3258, + "read_errors": 0, + "read_p95_ms": 18.751, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3258 + }, + { + "s": 16, + "reads": 3398, + "read_errors": 0, + "read_p95_ms": 17.497, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3398 + }, + { + "s": 17, + "reads": 4084, + "read_errors": 0, + "read_p95_ms": 13.763, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 4084 + }, + { + "s": 18, + "reads": 4216, + "read_errors": 0, + "read_p95_ms": 12.8, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 4216 + }, + { + "s": 19, + "reads": 3794, + "read_errors": 0, + "read_p95_ms": 14.786, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3794 + }, + { + "s": 20, + "reads": 3223, + "read_errors": 0, + "read_p95_ms": 18.75, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3223 + }, + { + "s": 21, + "reads": 3687, + "read_errors": 0, + "read_p95_ms": 15.439, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3687 + }, + { + "s": 22, + "reads": 3927, + "read_errors": 0, + "read_p95_ms": 14.229, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 3927 + }, + { + "s": 23, + "reads": 4139, + "read_errors": 0, + "read_p95_ms": 13.118, + "writes": 16, + "write_errors": 0, + "raw_violations": 16, + "stale_reads": 4139 + }, + { + "s": 24, + "reads": 4179, + "read_errors": 0, + "read_p95_ms": 13.024, + "writes": 17, + "write_errors": 0, + "raw_violations": 17, + "stale_reads": 4179 + }, + { + "s": 25, + "reads": 4076, + "read_errors": 0, + "read_p95_ms": 13.464, + "writes": 17, + "write_errors": 0, + "raw_violations": 17, + "stale_reads": 4076 + }, + { + "s": 26, + "reads": 3367, + "read_errors": 0, + "read_p95_ms": 17.454, + "writes": 15, + "write_errors": 0, + "raw_violations": 15, + "stale_reads": 3367 + }, + { + "s": 27, + "reads": 4215, + "read_errors": 0, + "read_p95_ms": 12.85, + "writes": 17, + "write_errors": 0, + "raw_violations": 17, + "stale_reads": 4215 + }, + { + "s": 28, + "reads": 4238, + "read_errors": 0, + "read_p95_ms": 12.851, + "writes": 17, + "write_errors": 0, + "raw_violations": 17, + "stale_reads": 4238 + }, + { + "s": 29, + "reads": 4328, + "read_errors": 0, + "read_p95_ms": 12.247, + "writes": 17, + "write_errors": 0, + "raw_violations": 17, + "stale_reads": 4328 + }, + { + "s": 30, + "reads": 9, + "read_errors": 0, + "read_p95_ms": 7.266, + "writes": 0, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 9 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 13.452, + "write_p95_ms": 25.88, + "writers": 2, + "writes_ok": 479 +} \ No newline at end of file diff --git a/evidence/track1/naive-d0-r3.stats.txt b/evidence/track1/naive-d0-r3.stats.txt new file mode 100644 index 0000000..e685370 --- /dev/null +++ b/evidence/track1/naive-d0-r3.stats.txt @@ -0,0 +1,59 @@ +mtusi-lab2-api-1;41.68%;73.59MiB / 1.858GiB +mtusi-lab2-postgres-1;4.99%;70.71MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;1.05%;5.062MiB / 1.858GiB +mtusi-lab2-valkey-1;1.58%;6.668MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;95.87%;9.938MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;298.14%;9.77MiB / 1.858GiB +mtusi-lab2-api-1;481.04%;18.96MiB / 1.858GiB +mtusi-lab2-postgres-1;9.45%;70.5MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;33.73%;5.914MiB / 1.858GiB +mtusi-lab2-valkey-1;16.69%;6.387MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;292.10%;9.969MiB / 1.858GiB +mtusi-lab2-api-1;480.61%;17.53MiB / 1.858GiB +mtusi-lab2-postgres-1;10.88%;70.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.22%;5.812MiB / 1.858GiB +mtusi-lab2-valkey-1;27.25%;6.434MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;335.04%;10.03MiB / 1.858GiB +mtusi-lab2-api-1;479.19%;18.24MiB / 1.858GiB +mtusi-lab2-postgres-1;9.43%;70.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;33.58%;5.754MiB / 1.858GiB +mtusi-lab2-valkey-1;16.21%;6.41MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;297.39%;10.52MiB / 1.858GiB +mtusi-lab2-api-1;480.80%;16.8MiB / 1.858GiB +mtusi-lab2-postgres-1;1.29%;70.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;51.41%;6.195MiB / 1.858GiB +mtusi-lab2-valkey-1;27.30%;6.43MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;295.13%;10.75MiB / 1.858GiB +mtusi-lab2-api-1;477.55%;15.57MiB / 1.858GiB +mtusi-lab2-postgres-1;5.24%;70.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;51.74%;5.965MiB / 1.858GiB +mtusi-lab2-valkey-1;27.16%;6.434MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;309.16%;10.45MiB / 1.858GiB +mtusi-lab2-api-1;481.57%;16.22MiB / 1.858GiB +mtusi-lab2-postgres-1;1.46%;70.55MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;52.81%;4.871MiB / 1.858GiB +mtusi-lab2-valkey-1;28.22%;6.664MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;293.75%;11.71MiB / 1.858GiB +mtusi-lab2-api-1;496.79%;16.17MiB / 1.858GiB +mtusi-lab2-postgres-1;5.43%;70.79MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;52.76%;5.156MiB / 1.858GiB +mtusi-lab2-valkey-1;28.96%;6.434MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;276.12%;11.39MiB / 1.858GiB +mtusi-lab2-api-1;507.63%;15.82MiB / 1.858GiB +mtusi-lab2-postgres-1;1.35%;70.56MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;55.64%;5.141MiB / 1.858GiB +mtusi-lab2-valkey-1;29.29%;6.434MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;281.89%;12.79MiB / 1.858GiB +mtusi-lab2-api-1;529.48%;15.98MiB / 1.858GiB +mtusi-lab2-postgres-1;1.22%;70.59MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;53.84%;4.465MiB / 1.858GiB +mtusi-lab2-valkey-1;30.64%;6.434MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d7de0ca6122;270.17%;12.36MiB / 1.858GiB +mtusi-lab2-api-1;491.23%;15.61MiB / 1.858GiB +mtusi-lab2-postgres-1;1.53%;70.59MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;56.31%;5.418MiB / 1.858GiB +mtusi-lab2-valkey-1;31.75%;6.418MiB / 1.858GiB +mtusi-lab2-api-1;61.10%;14.52MiB / 1.858GiB +mtusi-lab2-postgres-1;1.33%;70.61MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;6.33%;4.406MiB / 1.858GiB +mtusi-lab2-valkey-1;30.45%;6.434MiB / 1.858GiB diff --git a/evidence/track1/naive-d20-r1.json b/evidence/track1/naive-d20-r1.json new file mode 100644 index 0000000..78d2e82 --- /dev/null +++ b/evidence/track1/naive-d20-r1.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 130704, + "keyspace_misses": 7012 + }, + "date_utc": "2026-10-29T06:54:16Z", + "duration_s": 30, + "error_statuses": {}, + "label": "naive-d20-r1", + "raw_checks": 394, + "raw_violations": 2, + "read_errors": 0, + "read_p50_ms": 10.726, + "read_p95_ms": 34.8, + "read_p99_ms": 46.423, + "read_rps": 2275.9333333333334, + "readers": 32, + "reads_ok": 68278, + "seed_messages": 150, + "sql": { + "history_page_calls": 6833, + "history_page_total_ms": 1788.6577279999944, + "insert_message_calls": 394, + "membership_calls": 0, + "total_calls": 7227 + }, + "sql_history_per_read": 0.10007615923137761, + "sql_read_path_per_read": 0.10007615923137761, + "stale_checks": 68150, + "stale_reads": 3052, + "timeline": [ + { + "s": 0, + "reads": 1603, + "read_errors": 0, + "read_p95_ms": 43.79, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 51 + }, + { + "s": 1, + "reads": 3304, + "read_errors": 0, + "read_p95_ms": 28.68, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 2951, + "read_errors": 0, + "read_p95_ms": 30.196, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 10 + }, + { + "s": 3, + "reads": 2655, + "read_errors": 0, + "read_p95_ms": 31.09, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 354 + }, + { + "s": 4, + "reads": 1951, + "read_errors": 0, + "read_p95_ms": 36.784, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 310 + }, + { + "s": 5, + "reads": 2056, + "read_errors": 0, + "read_p95_ms": 34.99, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 5 + }, + { + "s": 6, + "reads": 1602, + "read_errors": 0, + "read_p95_ms": 44.449, + "writes": 14, + "write_errors": 0, + "raw_violations": 1, + "stale_reads": 20 + }, + { + "s": 7, + "reads": 1414, + "read_errors": 0, + "read_p95_ms": 43.69, + "writes": 12, + "write_errors": 0, + "raw_violations": 1, + "stale_reads": 41 + }, + { + "s": 8, + "reads": 2329, + "read_errors": 0, + "read_p95_ms": 36.26, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 2 + }, + { + "s": 9, + "reads": 3294, + "read_errors": 0, + "read_p95_ms": 27.431, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 31 + }, + { + "s": 10, + "reads": 2448, + "read_errors": 0, + "read_p95_ms": 33.802, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 27 + }, + { + "s": 11, + "reads": 2339, + "read_errors": 0, + "read_p95_ms": 32.399, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 365 + }, + { + "s": 12, + "reads": 1776, + "read_errors": 0, + "read_p95_ms": 39.543, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 153 + }, + { + "s": 13, + "reads": 1700, + "read_errors": 0, + "read_p95_ms": 40.911, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 314 + }, + { + "s": 14, + "reads": 1741, + "read_errors": 0, + "read_p95_ms": 39.572, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 257 + }, + { + "s": 15, + "reads": 1602, + "read_errors": 0, + "read_p95_ms": 41.002, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 10 + }, + { + "s": 16, + "reads": 3266, + "read_errors": 0, + "read_p95_ms": 27.498, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 75 + }, + { + "s": 17, + "reads": 2995, + "read_errors": 0, + "read_p95_ms": 30.031, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 9 + }, + { + "s": 18, + "reads": 2210, + "read_errors": 0, + "read_p95_ms": 34.145, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 10 + }, + { + "s": 19, + "reads": 2221, + "read_errors": 0, + "read_p95_ms": 32.375, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 26 + }, + { + "s": 20, + "reads": 2096, + "read_errors": 0, + "read_p95_ms": 33.7, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 147 + }, + { + "s": 21, + "reads": 1860, + "read_errors": 0, + "read_p95_ms": 37.709, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 183 + }, + { + "s": 22, + "reads": 1825, + "read_errors": 0, + "read_p95_ms": 36.748, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 535 + }, + { + "s": 23, + "reads": 1897, + "read_errors": 0, + "read_p95_ms": 41.151, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 40 + }, + { + "s": 24, + "reads": 3588, + "read_errors": 0, + "read_p95_ms": 26.465, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 6 + }, + { + "s": 25, + "reads": 2981, + "read_errors": 0, + "read_p95_ms": 29.954, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 3 + }, + { + "s": 26, + "reads": 2516, + "read_errors": 0, + "read_p95_ms": 32.096, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 19 + }, + { + "s": 27, + "reads": 2351, + "read_errors": 0, + "read_p95_ms": 32.056, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 6 + }, + { + "s": 28, + "reads": 1911, + "read_errors": 0, + "read_p95_ms": 37.207, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 26 + }, + { + "s": 29, + "reads": 1796, + "read_errors": 0, + "read_p95_ms": 38.318, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 17 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 15.712, + "write_p95_ms": 28.113, + "writers": 2, + "writes_ok": 394 +} \ No newline at end of file diff --git a/evidence/track1/naive-d20-r1.stats.txt b/evidence/track1/naive-d20-r1.stats.txt new file mode 100644 index 0000000..ddf7346 --- /dev/null +++ b/evidence/track1/naive-d20-r1.stats.txt @@ -0,0 +1,59 @@ +mtusi-lab2-api-1;11.35%;42.37MiB / 1.858GiB +mtusi-lab2-postgres-1;61.89%;68.41MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;13.66%;5.777MiB / 1.858GiB +mtusi-lab2-valkey-1;7.87%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;45.39%;9.82MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;291.38%;9.496MiB / 1.858GiB +mtusi-lab2-api-1;471.34%;17.3MiB / 1.858GiB +mtusi-lab2-postgres-1;17.46%;70.18MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;33.65%;5.848MiB / 1.858GiB +mtusi-lab2-valkey-1;15.45%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;215.18%;10.5MiB / 1.858GiB +mtusi-lab2-api-1;447.04%;15.98MiB / 1.858GiB +mtusi-lab2-postgres-1;15.86%;70.34MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.12%;5.934MiB / 1.858GiB +mtusi-lab2-valkey-1;23.21%;6.852MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;293.95%;11.02MiB / 1.858GiB +mtusi-lab2-api-1;435.75%;16.28MiB / 1.858GiB +mtusi-lab2-postgres-1;17.41%;70.4MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;35.20%;6.551MiB / 1.858GiB +mtusi-lab2-valkey-1;19.37%;6.836MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;250.64%;9.801MiB / 1.858GiB +mtusi-lab2-api-1;423.86%;14.89MiB / 1.858GiB +mtusi-lab2-postgres-1;17.09%;70.46MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;49.39%;6.266MiB / 1.858GiB +mtusi-lab2-valkey-1;14.71%;6.82MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;282.25%;10.56MiB / 1.858GiB +mtusi-lab2-api-1;427.32%;17.27MiB / 1.858GiB +mtusi-lab2-postgres-1;17.74%;70.46MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;36.41%;6.027MiB / 1.858GiB +mtusi-lab2-valkey-1;22.84%;7.238MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;295.03%;10.8MiB / 1.858GiB +mtusi-lab2-api-1;457.09%;18.95MiB / 1.858GiB +mtusi-lab2-postgres-1;19.96%;70.5MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;33.50%;6.113MiB / 1.858GiB +mtusi-lab2-valkey-1;15.52%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;256.90%;10.79MiB / 1.858GiB +mtusi-lab2-api-1;428.47%;15.58MiB / 1.858GiB +mtusi-lab2-postgres-1;12.82%;70.48MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;51.67%;5.984MiB / 1.858GiB +mtusi-lab2-valkey-1;26.62%;6.871MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;285.98%;12.07MiB / 1.858GiB +mtusi-lab2-api-1;447.60%;17.78MiB / 1.858GiB +mtusi-lab2-postgres-1;15.66%;70.48MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.13%;5.488MiB / 1.858GiB +mtusi-lab2-valkey-1;18.15%;6.84MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;302.31%;12.76MiB / 1.858GiB +mtusi-lab2-api-1;464.85%;18.56MiB / 1.858GiB +mtusi-lab2-postgres-1;17.72%;70.48MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;32.49%;6.141MiB / 1.858GiB +mtusi-lab2-valkey-1;15.65%;6.766MiB / 1.858GiB +mtusi-lab2-cachebench-run-32a6205ae240;266.98%;11.43MiB / 1.858GiB +mtusi-lab2-api-1;450.50%;15.41MiB / 1.858GiB +mtusi-lab2-postgres-1;19.29%;70.5MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.22%;6.371MiB / 1.858GiB +mtusi-lab2-valkey-1;24.59%;6.797MiB / 1.858GiB +mtusi-lab2-api-1;461.12%;16MiB / 1.858GiB +mtusi-lab2-postgres-1;19.36%;70.76MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.01%;5.359MiB / 1.858GiB +mtusi-lab2-valkey-1;19.00%;6.777MiB / 1.858GiB diff --git a/evidence/track1/naive-d20-r2.json b/evidence/track1/naive-d20-r2.json new file mode 100644 index 0000000..5c37cf7 --- /dev/null +++ b/evidence/track1/naive-d20-r2.json @@ -0,0 +1,351 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 282205, + "keyspace_misses": 7876 + }, + "date_utc": "2026-10-29T06:54:52Z", + "duration_s": 30, + "error_statuses": {}, + "label": "naive-d20-r2", + "raw_checks": 442, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 4.736, + "read_p95_ms": 23.289, + "read_p99_ms": 29.996, + "read_rps": 4812.766666666666, + "readers": 32, + "reads_ok": 144383, + "seed_messages": 150, + "sql": { + "history_page_calls": 7684, + "history_page_total_ms": 1039.2651270000042, + "insert_message_calls": 442, + "membership_calls": 0, + "total_calls": 8126 + }, + "sql_history_per_read": 0.053219561859775735, + "sql_read_path_per_read": 0.053219561859775735, + "stale_checks": 144223, + "stale_reads": 5673, + "timeline": [ + { + "s": 0, + "reads": 4946, + "read_errors": 0, + "read_p95_ms": 23.83, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 29 + }, + { + "s": 1, + "reads": 6673, + "read_errors": 0, + "read_p95_ms": 9.322, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 4837, + "read_errors": 0, + "read_p95_ms": 16.667, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 76 + }, + { + "s": 3, + "reads": 3979, + "read_errors": 0, + "read_p95_ms": 24.613, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 63 + }, + { + "s": 4, + "reads": 3926, + "read_errors": 0, + "read_p95_ms": 24.385, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 39 + }, + { + "s": 5, + "reads": 2992, + "read_errors": 0, + "read_p95_ms": 27.326, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 46 + }, + { + "s": 6, + "reads": 3053, + "read_errors": 0, + "read_p95_ms": 26.847, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 46 + }, + { + "s": 7, + "reads": 5410, + "read_errors": 0, + "read_p95_ms": 23.303, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 380 + }, + { + "s": 8, + "reads": 6445, + "read_errors": 0, + "read_p95_ms": 9.41, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 21 + }, + { + "s": 9, + "reads": 5156, + "read_errors": 0, + "read_p95_ms": 17.606, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 17 + }, + { + "s": 10, + "reads": 4471, + "read_errors": 0, + "read_p95_ms": 22.361, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 45 + }, + { + "s": 11, + "reads": 3889, + "read_errors": 0, + "read_p95_ms": 24.551, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 64 + }, + { + "s": 12, + "reads": 3514, + "read_errors": 0, + "read_p95_ms": 25.232, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 70 + }, + { + "s": 13, + "reads": 2599, + "read_errors": 0, + "read_p95_ms": 30.112, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 7 + }, + { + "s": 14, + "reads": 8501, + "read_errors": 0, + "read_p95_ms": 12.007, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 537 + }, + { + "s": 15, + "reads": 6988, + "read_errors": 0, + "read_p95_ms": 8.576, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 31 + }, + { + "s": 16, + "reads": 5868, + "read_errors": 0, + "read_p95_ms": 10.667, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 19 + }, + { + "s": 17, + "reads": 4865, + "read_errors": 0, + "read_p95_ms": 22.345, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 669 + }, + { + "s": 18, + "reads": 3584, + "read_errors": 0, + "read_p95_ms": 25.728, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 562 + }, + { + "s": 19, + "reads": 3346, + "read_errors": 0, + "read_p95_ms": 26.803, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 219 + }, + { + "s": 20, + "reads": 3649, + "read_errors": 0, + "read_p95_ms": 25.576, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 394 + }, + { + "s": 21, + "reads": 7493, + "read_errors": 0, + "read_p95_ms": 10.67, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 9 + }, + { + "s": 22, + "reads": 5935, + "read_errors": 0, + "read_p95_ms": 10.488, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 848 + }, + { + "s": 23, + "reads": 4659, + "read_errors": 0, + "read_p95_ms": 19.718, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 12 + }, + { + "s": 24, + "reads": 4522, + "read_errors": 0, + "read_p95_ms": 23.129, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 729 + }, + { + "s": 25, + "reads": 3231, + "read_errors": 0, + "read_p95_ms": 26.905, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 426 + }, + { + "s": 26, + "reads": 3460, + "read_errors": 0, + "read_p95_ms": 26.011, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 118 + }, + { + "s": 27, + "reads": 3856, + "read_errors": 0, + "read_p95_ms": 25.359, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 186 + }, + { + "s": 28, + "reads": 6815, + "read_errors": 0, + "read_p95_ms": 11.735, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 10 + }, + { + "s": 29, + "reads": 5720, + "read_errors": 0, + "read_p95_ms": 11.731, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 1 + }, + { + "s": 30, + "reads": 1, + "read_errors": 0, + "read_p95_ms": 2.964, + "writes": 0, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 6.77, + "write_p95_ms": 15.964, + "writers": 2, + "writes_ok": 442 +} \ No newline at end of file diff --git a/evidence/track1/naive-d20-r2.stats.txt b/evidence/track1/naive-d20-r2.stats.txt new file mode 100644 index 0000000..292e1bc --- /dev/null +++ b/evidence/track1/naive-d20-r2.stats.txt @@ -0,0 +1,90 @@ +mtusi-lab2-api-1;59.07%;53.97MiB / 1.858GiB +mtusi-lab2-postgres-1;7.18%;70.63MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;3.04%;5.516MiB / 1.858GiB +mtusi-lab2-valkey-1;2.22%;6.98MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;8.40%;7.16MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;246.68%;10.12MiB / 1.858GiB +mtusi-lab2-api-1;409.78%;19.13MiB / 1.858GiB +mtusi-lab2-postgres-1;11.65%;70.68MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;32.39%;5.844MiB / 1.858GiB +mtusi-lab2-valkey-1;14.58%;6.789MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;246.35%;9.676MiB / 1.858GiB +mtusi-lab2-api-1;414.89%;15.86MiB / 1.858GiB +mtusi-lab2-postgres-1;14.05%;71.02MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.16%;5.227MiB / 1.858GiB +mtusi-lab2-valkey-1;22.93%;6.805MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;252.82%;9.816MiB / 1.858GiB +mtusi-lab2-api-1;399.32%;16.46MiB / 1.858GiB +mtusi-lab2-postgres-1;10.21%;70.77MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;36.75%;5.488MiB / 1.858GiB +mtusi-lab2-valkey-1;19.15%;6.785MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;277.30%;11.01MiB / 1.858GiB +mtusi-lab2-api-1;405.39%;16.82MiB / 1.858GiB +mtusi-lab2-postgres-1;11.22%;70.78MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;31.92%;5.398MiB / 1.858GiB +mtusi-lab2-valkey-1;15.77%;6.766MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;286.20%;11.16MiB / 1.858GiB +mtusi-lab2-api-1;421.90%;16.9MiB / 1.858GiB +mtusi-lab2-postgres-1;11.30%;70.77MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;29.83%;5.676MiB / 1.858GiB +mtusi-lab2-valkey-1;13.84%;6.766MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;264.18%;11.99MiB / 1.858GiB +mtusi-lab2-api-1;418.57%;16.09MiB / 1.858GiB +mtusi-lab2-postgres-1;8.05%;70.78MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;43.91%;5.957MiB / 1.858GiB +mtusi-lab2-valkey-1;23.38%;6.801MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;259.10%;11.52MiB / 1.858GiB +mtusi-lab2-api-1;417.13%;16.77MiB / 1.858GiB +mtusi-lab2-postgres-1;11.82%;71.79MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.88%;5.594MiB / 1.858GiB +mtusi-lab2-valkey-1;18.41%;6.445MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;275.79%;12.32MiB / 1.858GiB +mtusi-lab2-api-1;432.51%;18.23MiB / 1.858GiB +mtusi-lab2-postgres-1;10.55%;70.79MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;31.32%;5.824MiB / 1.858GiB +mtusi-lab2-valkey-1;15.50%;6.441MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;225.15%;11.6MiB / 1.858GiB +mtusi-lab2-api-1;422.10%;16.51MiB / 1.858GiB +mtusi-lab2-postgres-1;8.73%;70.79MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;55.77%;5.93MiB / 1.858GiB +mtusi-lab2-valkey-1;29.84%;6.449MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;263.33%;12.09MiB / 1.858GiB +mtusi-lab2-api-1;444.85%;17.09MiB / 1.858GiB +mtusi-lab2-postgres-1;8.63%;70.84MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.92%;6.008MiB / 1.858GiB +mtusi-lab2-valkey-1;19.14%;6.453MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;266.38%;13.16MiB / 1.858GiB +mtusi-lab2-api-1;448.72%;17.26MiB / 1.858GiB +mtusi-lab2-postgres-1;12.59%;70.82MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;32.38%;6.016MiB / 1.858GiB +mtusi-lab2-valkey-1;16.33%;6.422MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;233.09%;12.31MiB / 1.858GiB +mtusi-lab2-api-1;423.85%;14.88MiB / 1.858GiB +mtusi-lab2-postgres-1;13.12%;70.85MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.86%;5.395MiB / 1.858GiB +mtusi-lab2-valkey-1;22.66%;6.426MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;232.89%;13.2MiB / 1.858GiB +mtusi-lab2-api-1;443.30%;15.92MiB / 1.858GiB +mtusi-lab2-postgres-1;9.95%;70.86MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.86%;5.352MiB / 1.858GiB +mtusi-lab2-valkey-1;21.50%;6.43MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;261.51%;13.83MiB / 1.858GiB +mtusi-lab2-api-1;454.20%;17.13MiB / 1.858GiB +mtusi-lab2-postgres-1;12.18%;71.69MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;35.96%;5.594MiB / 1.858GiB +mtusi-lab2-valkey-1;18.35%;6.418MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;277.04%;14.16MiB / 1.858GiB +mtusi-lab2-api-1;470.26%;18.12MiB / 1.858GiB +mtusi-lab2-postgres-1;12.27%;70.95MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;32.64%;5.918MiB / 1.858GiB +mtusi-lab2-valkey-1;15.78%;6.41MiB / 1.858GiB +mtusi-lab2-cachebench-run-14f8ed8a1ae8;193.62%;14.41MiB / 1.858GiB +mtusi-lab2-api-1;428.11%;16.61MiB / 1.858GiB +mtusi-lab2-postgres-1;9.73%;71.17MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.94%;5.98MiB / 1.858GiB +mtusi-lab2-valkey-1;24.80%;6.426MiB / 1.858GiB +mtusi-lab2-api-1;0.28%;16.31MiB / 1.858GiB +mtusi-lab2-postgres-1;3.02%;71.14MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.45%;5.191MiB / 1.858GiB +mtusi-lab2-valkey-1;1.25%;6.355MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;267.25%;10.21MiB / 1.858GiB diff --git a/evidence/track1/naive-d20-r3.json b/evidence/track1/naive-d20-r3.json new file mode 100644 index 0000000..89edccc --- /dev/null +++ b/evidence/track1/naive-d20-r3.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 291497, + "keyspace_misses": 8037 + }, + "date_utc": "2026-10-29T06:55:28Z", + "duration_s": 30, + "error_statuses": {}, + "label": "naive-d20-r3", + "raw_checks": 446, + "raw_violations": 1, + "read_errors": 0, + "read_p50_ms": 4.602, + "read_p95_ms": 22.516, + "read_p99_ms": 29.404, + "read_rps": 4970.4, + "readers": 32, + "reads_ok": 149112, + "seed_messages": 150, + "sql": { + "history_page_calls": 7847, + "history_page_total_ms": 1071.3626330000022, + "insert_message_calls": 445, + "membership_calls": 0, + "total_calls": 8292 + }, + "sql_history_per_read": 0.05262487257900102, + "sql_read_path_per_read": 0.05262487257900102, + "stale_checks": 148952, + "stale_reads": 4759, + "timeline": [ + { + "s": 0, + "reads": 6478, + "read_errors": 0, + "read_p95_ms": 18.947, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 622 + }, + { + "s": 1, + "reads": 6924, + "read_errors": 0, + "read_p95_ms": 9.073, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 118 + }, + { + "s": 2, + "reads": 4956, + "read_errors": 0, + "read_p95_ms": 15.775, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 39 + }, + { + "s": 3, + "reads": 4380, + "read_errors": 0, + "read_p95_ms": 23.679, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 543 + }, + { + "s": 4, + "reads": 3475, + "read_errors": 0, + "read_p95_ms": 25.073, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 112 + }, + { + "s": 5, + "reads": 3273, + "read_errors": 0, + "read_p95_ms": 25.869, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 77 + }, + { + "s": 6, + "reads": 3110, + "read_errors": 0, + "read_p95_ms": 27.12, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 580 + }, + { + "s": 7, + "reads": 6843, + "read_errors": 0, + "read_p95_ms": 14.725, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 12 + }, + { + "s": 8, + "reads": 6645, + "read_errors": 0, + "read_p95_ms": 9.258, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 12 + }, + { + "s": 9, + "reads": 4796, + "read_errors": 0, + "read_p95_ms": 15.629, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 4 + }, + { + "s": 10, + "reads": 4518, + "read_errors": 0, + "read_p95_ms": 23.522, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 23 + }, + { + "s": 11, + "reads": 3741, + "read_errors": 0, + "read_p95_ms": 24.397, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 132 + }, + { + "s": 12, + "reads": 3511, + "read_errors": 0, + "read_p95_ms": 25.902, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 908 + }, + { + "s": 13, + "reads": 3320, + "read_errors": 0, + "read_p95_ms": 25.918, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 12 + }, + { + "s": 14, + "reads": 8501, + "read_errors": 0, + "read_p95_ms": 7.738, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 2 + }, + { + "s": 15, + "reads": 6013, + "read_errors": 0, + "read_p95_ms": 10.62, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 15 + }, + { + "s": 16, + "reads": 5119, + "read_errors": 0, + "read_p95_ms": 12.948, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 56 + }, + { + "s": 17, + "reads": 3909, + "read_errors": 0, + "read_p95_ms": 25.218, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 8 + }, + { + "s": 18, + "reads": 4012, + "read_errors": 0, + "read_p95_ms": 24.46, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 5 + }, + { + "s": 19, + "reads": 3581, + "read_errors": 0, + "read_p95_ms": 25.123, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 7 + }, + { + "s": 20, + "reads": 3785, + "read_errors": 0, + "read_p95_ms": 29.056, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 33 + }, + { + "s": 21, + "reads": 7338, + "read_errors": 0, + "read_p95_ms": 9.553, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 37 + }, + { + "s": 22, + "reads": 6092, + "read_errors": 0, + "read_p95_ms": 9.907, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 23 + }, + { + "s": 23, + "reads": 4329, + "read_errors": 0, + "read_p95_ms": 24.171, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 93 + }, + { + "s": 24, + "reads": 4362, + "read_errors": 0, + "read_p95_ms": 23.268, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 21 + }, + { + "s": 25, + "reads": 3233, + "read_errors": 0, + "read_p95_ms": 26.44, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 16 + }, + { + "s": 26, + "reads": 3184, + "read_errors": 0, + "read_p95_ms": 28.288, + "writes": 16, + "write_errors": 0, + "raw_violations": 1, + "stale_reads": 393 + }, + { + "s": 27, + "reads": 6024, + "read_errors": 0, + "read_p95_ms": 17.267, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 7148, + "read_errors": 0, + "read_p95_ms": 7.983, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 801 + }, + { + "s": 29, + "reads": 6512, + "read_errors": 0, + "read_p95_ms": 8.782, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 55 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 6.507, + "write_p95_ms": 13.202, + "writers": 2, + "writes_ok": 446 +} \ No newline at end of file diff --git a/evidence/track1/naive-d20-r3.stats.txt b/evidence/track1/naive-d20-r3.stats.txt new file mode 100644 index 0000000..175005d --- /dev/null +++ b/evidence/track1/naive-d20-r3.stats.txt @@ -0,0 +1,83 @@ +mtusi-lab2-api-1;212.31%;16.98MiB / 1.858GiB +mtusi-lab2-postgres-1;12.32%;71.1MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;16.13%;5.695MiB / 1.858GiB +mtusi-lab2-valkey-1;7.70%;6.414MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;267.25%;10.21MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;287.86%;10.88MiB / 1.858GiB +mtusi-lab2-api-1;430.97%;19.68MiB / 1.858GiB +mtusi-lab2-postgres-1;11.17%;71.22MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;30.16%;6.238MiB / 1.858GiB +mtusi-lab2-valkey-1;14.64%;6.406MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;258.61%;10.13MiB / 1.858GiB +mtusi-lab2-api-1;420.17%;16.07MiB / 1.858GiB +mtusi-lab2-postgres-1;7.78%;71.26MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;42.75%;6.059MiB / 1.858GiB +mtusi-lab2-valkey-1;22.87%;6.438MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;276.91%;10.73MiB / 1.858GiB +mtusi-lab2-api-1;414.64%;17.73MiB / 1.858GiB +mtusi-lab2-postgres-1;11.21%;71.54MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.81%;6.109MiB / 1.858GiB +mtusi-lab2-valkey-1;17.09%;6.402MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;290.72%;10.9MiB / 1.858GiB +mtusi-lab2-api-1;424.91%;18.95MiB / 1.858GiB +mtusi-lab2-postgres-1;14.13%;71.8MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;31.11%;5.527MiB / 1.858GiB +mtusi-lab2-valkey-1;15.59%;6.391MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;248.41%;10.21MiB / 1.858GiB +mtusi-lab2-api-1;406.73%;15.97MiB / 1.858GiB +mtusi-lab2-postgres-1;7.98%;71.32MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.63%;5.629MiB / 1.858GiB +mtusi-lab2-valkey-1;25.89%;6.438MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;272.60%;11.7MiB / 1.858GiB +mtusi-lab2-api-1;433.83%;19.27MiB / 1.858GiB +mtusi-lab2-postgres-1;9.91%;71.32MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;36.06%;5.625MiB / 1.858GiB +mtusi-lab2-valkey-1;18.32%;6.41MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;275.68%;11.82MiB / 1.858GiB +mtusi-lab2-api-1;429.50%;18.42MiB / 1.858GiB +mtusi-lab2-postgres-1;11.84%;71.29MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;31.31%;6.379MiB / 1.858GiB +mtusi-lab2-valkey-1;15.45%;6.406MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;222.12%;11.79MiB / 1.858GiB +mtusi-lab2-api-1;402.90%;15.91MiB / 1.858GiB +mtusi-lab2-postgres-1;10.95%;71.3MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.08%;5.969MiB / 1.858GiB +mtusi-lab2-valkey-1;25.05%;6.438MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;252.03%;12.53MiB / 1.858GiB +mtusi-lab2-api-1;426.42%;19MiB / 1.858GiB +mtusi-lab2-postgres-1;10.69%;71.3MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;39.65%;5.289MiB / 1.858GiB +mtusi-lab2-valkey-1;21.41%;6.438MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;269.93%;12.99MiB / 1.858GiB +mtusi-lab2-api-1;456.92%;17.66MiB / 1.858GiB +mtusi-lab2-postgres-1;11.04%;71.31MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;35.02%;5.781MiB / 1.858GiB +mtusi-lab2-valkey-1;17.04%;6.414MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;271.81%;13.13MiB / 1.858GiB +mtusi-lab2-api-1;428.44%;21.82MiB / 1.858GiB +mtusi-lab2-postgres-1;12.15%;71.32MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;31.97%;6.227MiB / 1.858GiB +mtusi-lab2-valkey-1;15.19%;6.406MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;231.59%;12.84MiB / 1.858GiB +mtusi-lab2-api-1;446.04%;16.91MiB / 1.858GiB +mtusi-lab2-postgres-1;10.63%;71.32MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;46.10%;6.168MiB / 1.858GiB +mtusi-lab2-valkey-1;24.04%;6.422MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;250.61%;14.43MiB / 1.858GiB +mtusi-lab2-api-1;448.25%;19.53MiB / 1.858GiB +mtusi-lab2-postgres-1;11.98%;71.33MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;35.09%;6.059MiB / 1.858GiB +mtusi-lab2-valkey-1;17.66%;6.426MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;256.28%;14.21MiB / 1.858GiB +mtusi-lab2-api-1;426.66%;20.66MiB / 1.858GiB +mtusi-lab2-postgres-1;18.53%;71.38MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;32.10%;5.746MiB / 1.858GiB +mtusi-lab2-valkey-1;16.20%;6.426MiB / 1.858GiB +mtusi-lab2-cachebench-run-dc276938af2a;205.16%;14.46MiB / 1.858GiB +mtusi-lab2-api-1;439.88%;16.6MiB / 1.858GiB +mtusi-lab2-postgres-1;10.64%;71.36MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;53.13%;5.816MiB / 1.858GiB +mtusi-lab2-valkey-1;28.65%;6.438MiB / 1.858GiB +mtusi-lab2-postgres-1;9.73%;48.59MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;4.45%;5.695MiB / 1.858GiB +mtusi-lab2-valkey-1;2.18%;6.324MiB / 1.858GiB diff --git a/evidence/track1/off-d0-r1.json b/evidence/track1/off-d0-r1.json new file mode 100644 index 0000000..61e819c --- /dev/null +++ b/evidence/track1/off-d0-r1.json @@ -0,0 +1,351 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 0, + "keyspace_misses": 0 + }, + "date_utc": "2026-10-29T06:50:17Z", + "duration_s": 30, + "error_statuses": {}, + "label": "off-d0-r1", + "raw_checks": 452, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 12.156, + "read_p95_ms": 28.596, + "read_p99_ms": 39.004, + "read_rps": 2252.133333333333, + "readers": 32, + "reads_ok": 67564, + "seed_messages": 150, + "sql": { + "history_page_calls": 68042, + "history_page_total_ms": 17791.330189999782, + "insert_message_calls": 452, + "membership_calls": 68040, + "total_calls": 136534 + }, + "sql_history_per_read": 1.0070747735480434, + "sql_read_path_per_read": 2.0141199455331242, + "stale_checks": 67404, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 2516, + "read_errors": 0, + "read_p95_ms": 27.495, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 2232, + "read_errors": 0, + "read_p95_ms": 26.429, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 2411, + "read_errors": 0, + "read_p95_ms": 22.937, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 2322, + "read_errors": 0, + "read_p95_ms": 24.609, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 1923, + "read_errors": 0, + "read_p95_ms": 30.574, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 1744, + "read_errors": 0, + "read_p95_ms": 33.67, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 1482, + "read_errors": 0, + "read_p95_ms": 42.939, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 2612, + "read_errors": 0, + "read_p95_ms": 23.566, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 2988, + "read_errors": 0, + "read_p95_ms": 18.665, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 2302, + "read_errors": 0, + "read_p95_ms": 26.31, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 2125, + "read_errors": 0, + "read_p95_ms": 27.154, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 1974, + "read_errors": 0, + "read_p95_ms": 30.079, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 1371, + "read_errors": 0, + "read_p95_ms": 43.245, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 1716, + "read_errors": 0, + "read_p95_ms": 36.93, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 3463, + "read_errors": 0, + "read_p95_ms": 15.679, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 2895, + "read_errors": 0, + "read_p95_ms": 19.014, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 2191, + "read_errors": 0, + "read_p95_ms": 26.205, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 1897, + "read_errors": 0, + "read_p95_ms": 34.407, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 1607, + "read_errors": 0, + "read_p95_ms": 36.338, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 1706, + "read_errors": 0, + "read_p95_ms": 34.758, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 2521, + "read_errors": 0, + "read_p95_ms": 27.623, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 3268, + "read_errors": 0, + "read_p95_ms": 16.956, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 2415, + "read_errors": 0, + "read_p95_ms": 26.119, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 2042, + "read_errors": 0, + "read_p95_ms": 28.005, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 2088, + "read_errors": 0, + "read_p95_ms": 28.238, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 1906, + "read_errors": 0, + "read_p95_ms": 30.103, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 1806, + "read_errors": 0, + "read_p95_ms": 30.244, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 3381, + "read_errors": 0, + "read_p95_ms": 17.136, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 2393, + "read_errors": 0, + "read_p95_ms": 25.665, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 2255, + "read_errors": 0, + "read_p95_ms": 25.271, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 30, + "reads": 12, + "read_errors": 0, + "read_p95_ms": 9.764, + "writes": 0, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 13.592, + "write_p95_ms": 30.415, + "writers": 2, + "writes_ok": 452 +} \ No newline at end of file diff --git a/evidence/track1/off-d0-r1.stats.txt b/evidence/track1/off-d0-r1.stats.txt new file mode 100644 index 0000000..36f3586 --- /dev/null +++ b/evidence/track1/off-d0-r1.stats.txt @@ -0,0 +1,59 @@ +mtusi-lab2-api-1;173.26%;14.39MiB / 1.858GiB +mtusi-lab2-postgres-1;107.84%;67.63MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.38%;4.629MiB / 1.858GiB +mtusi-lab2-valkey-1;0.47%;6.34MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;103.38%;10.75MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;310.72%;11.75MiB / 1.858GiB +mtusi-lab2-api-1;390.64%;17.65MiB / 1.858GiB +mtusi-lab2-postgres-1;181.59%;69.17MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.38%;4.637MiB / 1.858GiB +mtusi-lab2-valkey-1;18.19%;6.824MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;264.10%;12.05MiB / 1.858GiB +mtusi-lab2-api-1;396.95%;14.87MiB / 1.858GiB +mtusi-lab2-postgres-1;195.21%;69.39MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.37%;4.637MiB / 1.858GiB +mtusi-lab2-valkey-1;24.35%;6.832MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;319.60%;12.38MiB / 1.858GiB +mtusi-lab2-api-1;379.38%;17.19MiB / 1.858GiB +mtusi-lab2-postgres-1;184.06%;69.92MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.34%;4.652MiB / 1.858GiB +mtusi-lab2-valkey-1;16.88%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;265.06%;11.96MiB / 1.858GiB +mtusi-lab2-api-1;385.63%;14.97MiB / 1.858GiB +mtusi-lab2-postgres-1;197.98%;69.41MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.83%;4.652MiB / 1.858GiB +mtusi-lab2-valkey-1;25.50%;6.824MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;303.54%;12.06MiB / 1.858GiB +mtusi-lab2-api-1;382.01%;17.09MiB / 1.858GiB +mtusi-lab2-postgres-1;196.58%;69.51MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.43%;4.652MiB / 1.858GiB +mtusi-lab2-valkey-1;18.00%;6.836MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;215.75%;11.52MiB / 1.858GiB +mtusi-lab2-api-1;406.68%;15.72MiB / 1.858GiB +mtusi-lab2-postgres-1;216.60%;69.45MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.34%;4.652MiB / 1.858GiB +mtusi-lab2-valkey-1;23.91%;6.84MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;285.61%;13.02MiB / 1.858GiB +mtusi-lab2-api-1;387.08%;16.71MiB / 1.858GiB +mtusi-lab2-postgres-1;191.91%;69.76MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.38%;4.652MiB / 1.858GiB +mtusi-lab2-valkey-1;18.93%;6.848MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;291.03%;11.96MiB / 1.858GiB +mtusi-lab2-api-1;391.36%;14.93MiB / 1.858GiB +mtusi-lab2-postgres-1;199.34%;69.74MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.32%;4.418MiB / 1.858GiB +mtusi-lab2-valkey-1;26.35%;6.852MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;268.86%;12.65MiB / 1.858GiB +mtusi-lab2-api-1;384.13%;17.45MiB / 1.858GiB +mtusi-lab2-postgres-1;203.07%;69.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.76%;4.418MiB / 1.858GiB +mtusi-lab2-valkey-1;20.95%;6.754MiB / 1.858GiB +mtusi-lab2-cachebench-run-e1b884d77b53;306.43%;14.24MiB / 1.858GiB +mtusi-lab2-api-1;404.32%;15.28MiB / 1.858GiB +mtusi-lab2-postgres-1;245.75%;69.75MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.41%;4.418MiB / 1.858GiB +mtusi-lab2-valkey-1;16.06%;6.77MiB / 1.858GiB +mtusi-lab2-api-1;0.81%;16.34MiB / 1.858GiB +mtusi-lab2-postgres-1;0.03%;67.83MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;1.75%;4.699MiB / 1.858GiB +mtusi-lab2-valkey-1;16.11%;6.723MiB / 1.858GiB diff --git a/evidence/track1/off-d0-r2.json b/evidence/track1/off-d0-r2.json new file mode 100644 index 0000000..a6acfca --- /dev/null +++ b/evidence/track1/off-d0-r2.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 0, + "keyspace_misses": 0 + }, + "date_utc": "2026-10-29T06:50:54Z", + "duration_s": 30, + "error_statuses": {}, + "label": "off-d0-r2", + "raw_checks": 453, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 12.033, + "read_p95_ms": 28.455, + "read_p99_ms": 39.82, + "read_rps": 2267.266666666667, + "readers": 32, + "reads_ok": 68018, + "seed_messages": 150, + "sql": { + "history_page_calls": 68479, + "history_page_total_ms": 17907.471168999946, + "insert_message_calls": 453, + "membership_calls": 68479, + "total_calls": 137411 + }, + "sql_history_per_read": 1.0067776176894352, + "sql_read_path_per_read": 2.0135552353788704, + "stale_checks": 67858, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 2732, + "read_errors": 0, + "read_p95_ms": 27.344, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 3139, + "read_errors": 0, + "read_p95_ms": 17.384, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 2497, + "read_errors": 0, + "read_p95_ms": 25.062, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 1912, + "read_errors": 0, + "read_p95_ms": 32.3, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 1959, + "read_errors": 0, + "read_p95_ms": 28.989, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 1798, + "read_errors": 0, + "read_p95_ms": 33.173, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 1743, + "read_errors": 0, + "read_p95_ms": 33.597, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 2990, + "read_errors": 0, + "read_p95_ms": 21.477, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 2276, + "read_errors": 0, + "read_p95_ms": 24.991, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 2350, + "read_errors": 0, + "read_p95_ms": 24.969, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 2135, + "read_errors": 0, + "read_p95_ms": 28.001, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 1955, + "read_errors": 0, + "read_p95_ms": 29.79, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 1784, + "read_errors": 0, + "read_p95_ms": 32.428, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 1548, + "read_errors": 0, + "read_p95_ms": 46.25, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 3062, + "read_errors": 0, + "read_p95_ms": 16.948, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 2640, + "read_errors": 0, + "read_p95_ms": 20.512, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 2222, + "read_errors": 0, + "read_p95_ms": 24.863, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 2226, + "read_errors": 0, + "read_p95_ms": 25.011, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 1869, + "read_errors": 0, + "read_p95_ms": 32.819, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 1566, + "read_errors": 0, + "read_p95_ms": 39.816, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 2286, + "read_errors": 0, + "read_p95_ms": 34.109, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 3292, + "read_errors": 0, + "read_p95_ms": 15.858, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 2623, + "read_errors": 0, + "read_p95_ms": 21.659, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 2243, + "read_errors": 0, + "read_p95_ms": 25.431, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 1804, + "read_errors": 0, + "read_p95_ms": 33.922, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 1672, + "read_errors": 0, + "read_p95_ms": 35.096, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 1742, + "read_errors": 0, + "read_p95_ms": 34.782, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 3373, + "read_errors": 0, + "read_p95_ms": 18.063, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 2807, + "read_errors": 0, + "read_p95_ms": 22.074, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 1773, + "read_errors": 0, + "read_p95_ms": 33.287, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 13.956, + "write_p95_ms": 28.72, + "writers": 2, + "writes_ok": 453 +} \ No newline at end of file diff --git a/evidence/track1/off-d0-r2.stats.txt b/evidence/track1/off-d0-r2.stats.txt new file mode 100644 index 0000000..a5cecd4 --- /dev/null +++ b/evidence/track1/off-d0-r2.stats.txt @@ -0,0 +1,59 @@ +mtusi-lab2-api-1;72.69%;48.74MiB / 1.858GiB +mtusi-lab2-postgres-1;12.78%;69.51MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.36%;4.418MiB / 1.858GiB +mtusi-lab2-valkey-1;2.58%;6.727MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;252.54%;9.367MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;274.78%;9.332MiB / 1.858GiB +mtusi-lab2-api-1;379.18%;17.38MiB / 1.858GiB +mtusi-lab2-postgres-1;208.75%;70.47MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.44%;4.379MiB / 1.858GiB +mtusi-lab2-valkey-1;21.64%;6.777MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;258.70%;10.46MiB / 1.858GiB +mtusi-lab2-api-1;402.01%;16.59MiB / 1.858GiB +mtusi-lab2-postgres-1;192.99%;70.02MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;4.06%;4.395MiB / 1.858GiB +mtusi-lab2-valkey-1;22.35%;6.762MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;330.10%;10.97MiB / 1.858GiB +mtusi-lab2-api-1;380.68%;17.13MiB / 1.858GiB +mtusi-lab2-postgres-1;181.09%;69.77MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.38%;4.398MiB / 1.858GiB +mtusi-lab2-valkey-1;15.91%;6.75MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;277.05%;10.27MiB / 1.858GiB +mtusi-lab2-api-1;396.17%;15.52MiB / 1.858GiB +mtusi-lab2-postgres-1;199.22%;69.73MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.38%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;24.37%;6.766MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;302.85%;10.92MiB / 1.858GiB +mtusi-lab2-api-1;395.36%;16.66MiB / 1.858GiB +mtusi-lab2-postgres-1;184.27%;70.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.39%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;16.75%;6.379MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;265.18%;11.05MiB / 1.858GiB +mtusi-lab2-api-1;400.68%;15.89MiB / 1.858GiB +mtusi-lab2-postgres-1;228.01%;70.05MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.33%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;22.58%;6.391MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;297.80%;11.43MiB / 1.858GiB +mtusi-lab2-api-1;390.36%;17.04MiB / 1.858GiB +mtusi-lab2-postgres-1;186.36%;70.11MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.34%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;18.43%;6.395MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;227.54%;10.46MiB / 1.858GiB +mtusi-lab2-api-1;404.66%;15.62MiB / 1.858GiB +mtusi-lab2-postgres-1;222.53%;69.89MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.30%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;24.02%;6.41MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;266.07%;11.75MiB / 1.858GiB +mtusi-lab2-api-1;392.47%;16.47MiB / 1.858GiB +mtusi-lab2-postgres-1;196.78%;69.85MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.43%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;17.60%;6.398MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb4fa5c8071c;213.13%;10.95MiB / 1.858GiB +mtusi-lab2-api-1;405.74%;15.27MiB / 1.858GiB +mtusi-lab2-postgres-1;237.29%;70.11MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.32%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;20.93%;6.418MiB / 1.858GiB +mtusi-lab2-api-1;0.85%;16.71MiB / 1.858GiB +mtusi-lab2-postgres-1;0.04%;68.29MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;1.93%;4.383MiB / 1.858GiB +mtusi-lab2-valkey-1;9.65%;6.602MiB / 1.858GiB diff --git a/evidence/track1/off-d0-r3.json b/evidence/track1/off-d0-r3.json new file mode 100644 index 0000000..00eb163 --- /dev/null +++ b/evidence/track1/off-d0-r3.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 0, + "keyspace_misses": 0 + }, + "date_utc": "2026-10-29T06:51:30Z", + "duration_s": 30, + "error_statuses": {}, + "label": "off-d0-r3", + "raw_checks": 453, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 11.788, + "read_p95_ms": 28.085, + "read_p99_ms": 39.551, + "read_rps": 2310.5333333333333, + "readers": 32, + "reads_ok": 69316, + "seed_messages": 150, + "sql": { + "history_page_calls": 69764, + "history_page_total_ms": 17971.081124999993, + "insert_message_calls": 453, + "membership_calls": 69763, + "total_calls": 139980 + }, + "sql_history_per_read": 1.006463154250101, + "sql_read_path_per_read": 2.012911881816608, + "stale_checks": 69156, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 1853, + "read_errors": 0, + "read_p95_ms": 44.713, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 3462, + "read_errors": 0, + "read_p95_ms": 14.847, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 2733, + "read_errors": 0, + "read_p95_ms": 21.841, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 2320, + "read_errors": 0, + "read_p95_ms": 25.412, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 1696, + "read_errors": 0, + "read_p95_ms": 38.269, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 1816, + "read_errors": 0, + "read_p95_ms": 32.06, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 1680, + "read_errors": 0, + "read_p95_ms": 34.924, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 3094, + "read_errors": 0, + "read_p95_ms": 23.68, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 2924, + "read_errors": 0, + "read_p95_ms": 19.387, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 2234, + "read_errors": 0, + "read_p95_ms": 30.402, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 1910, + "read_errors": 0, + "read_p95_ms": 31.668, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 2006, + "read_errors": 0, + "read_p95_ms": 28.529, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 1787, + "read_errors": 0, + "read_p95_ms": 34.772, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 1780, + "read_errors": 0, + "read_p95_ms": 33.823, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 3726, + "read_errors": 0, + "read_p95_ms": 14.421, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 2330, + "read_errors": 0, + "read_p95_ms": 24.511, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 2203, + "read_errors": 0, + "read_p95_ms": 25.459, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 2301, + "read_errors": 0, + "read_p95_ms": 24.182, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 2018, + "read_errors": 0, + "read_p95_ms": 28.521, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 1799, + "read_errors": 0, + "read_p95_ms": 32.304, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 2026, + "read_errors": 0, + "read_p95_ms": 31.429, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 2605, + "read_errors": 0, + "read_p95_ms": 19.969, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 2555, + "read_errors": 0, + "read_p95_ms": 21.539, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 2331, + "read_errors": 0, + "read_p95_ms": 24.845, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 2261, + "read_errors": 0, + "read_p95_ms": 26.563, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 1776, + "read_errors": 0, + "read_p95_ms": 36.03, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 1433, + "read_errors": 0, + "read_p95_ms": 45.814, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 3215, + "read_errors": 0, + "read_p95_ms": 21.816, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 2642, + "read_errors": 0, + "read_p95_ms": 23.893, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 2800, + "read_errors": 0, + "read_p95_ms": 18.648, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 13.407, + "write_p95_ms": 30.629, + "writers": 2, + "writes_ok": 453 +} \ No newline at end of file diff --git a/evidence/track1/off-d0-r3.stats.txt b/evidence/track1/off-d0-r3.stats.txt new file mode 100644 index 0000000..c70276c --- /dev/null +++ b/evidence/track1/off-d0-r3.stats.txt @@ -0,0 +1,59 @@ +mtusi-lab2-api-1;86.29%;18.39MiB / 1.858GiB +mtusi-lab2-postgres-1;19.59%;70.58MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.31%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;3.96%;6.395MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;30.63%;9.723MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;309.93%;10.25MiB / 1.858GiB +mtusi-lab2-api-1;381.63%;17MiB / 1.858GiB +mtusi-lab2-postgres-1;175.23%;70.14MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.37%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;17.95%;6.406MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;270.66%;9.809MiB / 1.858GiB +mtusi-lab2-api-1;396.10%;15.76MiB / 1.858GiB +mtusi-lab2-postgres-1;233.92%;70.19MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.60%;4.379MiB / 1.858GiB +mtusi-lab2-valkey-1;24.02%;6.414MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;322.56%;11.52MiB / 1.858GiB +mtusi-lab2-api-1;385.97%;17.44MiB / 1.858GiB +mtusi-lab2-postgres-1;178.84%;70.16MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.44%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;18.70%;6.391MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;204.60%;10.53MiB / 1.858GiB +mtusi-lab2-api-1;389.98%;14.92MiB / 1.858GiB +mtusi-lab2-postgres-1;245.59%;70.96MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.54%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;22.29%;6.398MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;312.38%;11.57MiB / 1.858GiB +mtusi-lab2-api-1;397.64%;16.4MiB / 1.858GiB +mtusi-lab2-postgres-1;191.88%;70.22MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.43%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;18.50%;6.387MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;266.83%;9.793MiB / 1.858GiB +mtusi-lab2-api-1;392.85%;15.48MiB / 1.858GiB +mtusi-lab2-postgres-1;222.21%;70.22MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.49%;4.379MiB / 1.858GiB +mtusi-lab2-valkey-1;22.43%;6.43MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;292.89%;14.04MiB / 1.858GiB +mtusi-lab2-api-1;401.36%;16.23MiB / 1.858GiB +mtusi-lab2-postgres-1;204.76%;70.27MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.44%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;20.50%;6.414MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;312.57%;14.36MiB / 1.858GiB +mtusi-lab2-api-1;363.18%;14.95MiB / 1.858GiB +mtusi-lab2-postgres-1;182.57%;70.93MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.64%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;16.15%;6.422MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;268.28%;12.76MiB / 1.858GiB +mtusi-lab2-api-1;402.59%;18.25MiB / 1.858GiB +mtusi-lab2-postgres-1;197.66%;70.56MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.39%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;22.26%;6.434MiB / 1.858GiB +mtusi-lab2-cachebench-run-63dc3f9d5854;264.37%;11.06MiB / 1.858GiB +mtusi-lab2-api-1;378.25%;17.9MiB / 1.858GiB +mtusi-lab2-postgres-1;218.57%;71.11MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.34%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;14.67%;6.398MiB / 1.858GiB +mtusi-lab2-api-1;403.42%;16.16MiB / 1.858GiB +mtusi-lab2-postgres-1;61.18%;68.8MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.39%;4.375MiB / 1.858GiB +mtusi-lab2-valkey-1;22.00%;6.391MiB / 1.858GiB diff --git a/evidence/track1/safe-d0-r1.json b/evidence/track1/safe-d0-r1.json new file mode 100644 index 0000000..e165370 --- /dev/null +++ b/evidence/track1/safe-d0-r1.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 397053, + "keyspace_misses": 9897 + }, + "date_utc": "2026-10-29T06:56:11Z", + "duration_s": 30, + "error_statuses": {}, + "label": "safe-d0-r1", + "raw_checks": 512, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 6.157, + "read_p95_ms": 14.681, + "read_p99_ms": 20.176, + "read_rps": 4477.9, + "readers": 32, + "reads_ok": 134337, + "seed_messages": 150, + "sql": { + "history_page_calls": 512, + "history_page_total_ms": 93.43737800000007, + "insert_message_calls": 512, + "membership_calls": 0, + "total_calls": 1024 + }, + "sql_history_per_read": 0.0038113103612556483, + "sql_read_path_per_read": 0.0038113103612556483, + "stale_checks": 134145, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 6740, + "read_errors": 0, + "read_p95_ms": 10.226, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 6084, + "read_errors": 0, + "read_p95_ms": 9.618, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 3620, + "read_errors": 0, + "read_p95_ms": 17.678, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 3436, + "read_errors": 0, + "read_p95_ms": 17.945, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 2950, + "read_errors": 0, + "read_p95_ms": 20.547, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 2801, + "read_errors": 0, + "read_p95_ms": 20.626, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 6438, + "read_errors": 0, + "read_p95_ms": 9.833, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 5213, + "read_errors": 0, + "read_p95_ms": 11.025, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 3524, + "read_errors": 0, + "read_p95_ms": 16.832, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 3999, + "read_errors": 0, + "read_p95_ms": 14.457, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 3506, + "read_errors": 0, + "read_p95_ms": 16.809, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 3469, + "read_errors": 0, + "read_p95_ms": 17.444, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 6989, + "read_errors": 0, + "read_p95_ms": 8.203, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 4242, + "read_errors": 0, + "read_p95_ms": 14.216, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 4361, + "read_errors": 0, + "read_p95_ms": 13.243, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 4004, + "read_errors": 0, + "read_p95_ms": 14.063, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 3666, + "read_errors": 0, + "read_p95_ms": 15.606, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 4049, + "read_errors": 0, + "read_p95_ms": 16.995, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 5939, + "read_errors": 0, + "read_p95_ms": 10.69, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 4782, + "read_errors": 0, + "read_p95_ms": 12.265, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 4718, + "read_errors": 0, + "read_p95_ms": 12.178, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 3776, + "read_errors": 0, + "read_p95_ms": 15.303, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 3640, + "read_errors": 0, + "read_p95_ms": 15.56, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 4157, + "read_errors": 0, + "read_p95_ms": 17.485, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 5965, + "read_errors": 0, + "read_p95_ms": 9.642, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 5190, + "read_errors": 0, + "read_p95_ms": 10.763, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 4711, + "read_errors": 0, + "read_p95_ms": 12.084, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 3925, + "read_errors": 0, + "read_p95_ms": 14.659, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 3613, + "read_errors": 0, + "read_p95_ms": 16.518, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 4830, + "read_errors": 0, + "read_p95_ms": 18.316, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 7.592, + "write_p95_ms": 15.396, + "writers": 2, + "writes_ok": 512 +} \ No newline at end of file diff --git a/evidence/track1/safe-d0-r1.stats.txt b/evidence/track1/safe-d0-r1.stats.txt new file mode 100644 index 0000000..c234b81 --- /dev/null +++ b/evidence/track1/safe-d0-r1.stats.txt @@ -0,0 +1,84 @@ +mtusi-lab2-api-1;85.77%;13.94MiB / 1.858GiB +mtusi-lab2-postgres-1;5.80%;56.36MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;44.76%;5.578MiB / 1.858GiB +mtusi-lab2-valkey-1;3.68%;6.875MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;261.78%;10.05MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;305.42%;9.211MiB / 1.858GiB +mtusi-lab2-api-1;491.46%;13.14MiB / 1.858GiB +mtusi-lab2-postgres-1;3.78%;56.46MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;39.75%;6.441MiB / 1.858GiB +mtusi-lab2-valkey-1;15.36%;6.871MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;272.07%;10.14MiB / 1.858GiB +mtusi-lab2-api-1;494.05%;15.09MiB / 1.858GiB +mtusi-lab2-postgres-1;1.97%;56.46MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;55.53%;5.957MiB / 1.858GiB +mtusi-lab2-valkey-1;22.50%;6.859MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;304.93%;9.992MiB / 1.858GiB +mtusi-lab2-api-1;479.42%;15.55MiB / 1.858GiB +mtusi-lab2-postgres-1;2.51%;56.48MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;44.86%;6.32MiB / 1.858GiB +mtusi-lab2-valkey-1;17.54%;6.863MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;301.17%;9.727MiB / 1.858GiB +mtusi-lab2-api-1;489.79%;12.61MiB / 1.858GiB +mtusi-lab2-postgres-1;2.15%;56.48MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.27%;6.801MiB / 1.858GiB +mtusi-lab2-valkey-1;17.44%;6.875MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;265.27%;11.25MiB / 1.858GiB +mtusi-lab2-api-1;450.36%;14.9MiB / 1.858GiB +mtusi-lab2-postgres-1;4.96%;56.5MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;53.03%;8.219MiB / 1.858GiB +mtusi-lab2-valkey-1;22.36%;6.855MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;309.94%;11.98MiB / 1.858GiB +mtusi-lab2-api-1;503.94%;16.09MiB / 1.858GiB +mtusi-lab2-postgres-1;2.38%;56.5MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.55%;7.457MiB / 1.858GiB +mtusi-lab2-valkey-1;18.13%;6.848MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;263.29%;10.33MiB / 1.858GiB +mtusi-lab2-api-1;492.82%;13MiB / 1.858GiB +mtusi-lab2-postgres-1;2.21%;56.51MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;52.58%;8.035MiB / 1.858GiB +mtusi-lab2-valkey-1;21.11%;6.879MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;267.65%;12.72MiB / 1.858GiB +mtusi-lab2-api-1;483.72%;15.02MiB / 1.858GiB +mtusi-lab2-postgres-1;1.99%;56.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;51.50%;8.465MiB / 1.858GiB +mtusi-lab2-valkey-1;21.30%;6.879MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;297.80%;12.63MiB / 1.858GiB +mtusi-lab2-api-1;507.67%;16.29MiB / 1.858GiB +mtusi-lab2-postgres-1;2.36%;56.55MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;44.47%;9.004MiB / 1.858GiB +mtusi-lab2-valkey-1;17.30%;6.855MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;228.70%;11.72MiB / 1.858GiB +mtusi-lab2-api-1;491.85%;14.44MiB / 1.858GiB +mtusi-lab2-postgres-1;4.43%;56.55MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;58.31%;9.309MiB / 1.858GiB +mtusi-lab2-valkey-1;24.68%;6.879MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;272.55%;12.81MiB / 1.858GiB +mtusi-lab2-api-1;514.37%;15.19MiB / 1.858GiB +mtusi-lab2-postgres-1;1.92%;56.55MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;52.22%;9.387MiB / 1.858GiB +mtusi-lab2-valkey-1;21.01%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;296.82%;14.02MiB / 1.858GiB +mtusi-lab2-api-1;514.81%;16.43MiB / 1.858GiB +mtusi-lab2-postgres-1;1.74%;56.57MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;44.72%;10.12MiB / 1.858GiB +mtusi-lab2-valkey-1;17.70%;6.789MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;198.62%;12.81MiB / 1.858GiB +mtusi-lab2-api-1;496.52%;14.41MiB / 1.858GiB +mtusi-lab2-postgres-1;2.76%;56.58MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;63.23%;10.38MiB / 1.858GiB +mtusi-lab2-valkey-1;27.21%;6.812MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;265.22%;13.73MiB / 1.858GiB +mtusi-lab2-api-1;512.59%;15.11MiB / 1.858GiB +mtusi-lab2-postgres-1;1.93%;56.59MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;51.15%;10.57MiB / 1.858GiB +mtusi-lab2-valkey-1;20.66%;6.801MiB / 1.858GiB +mtusi-lab2-cachebench-run-eb802acc74bc;292.07%;14.84MiB / 1.858GiB +mtusi-lab2-api-1;505.42%;16.64MiB / 1.858GiB +mtusi-lab2-postgres-1;4.92%;56.8MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.10%;11.05MiB / 1.858GiB +mtusi-lab2-valkey-1;18.38%;6.809MiB / 1.858GiB +mtusi-lab2-api-1;171.34%;13.67MiB / 1.858GiB +mtusi-lab2-postgres-1;1.41%;55.07MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;24.75%;11.41MiB / 1.858GiB +mtusi-lab2-valkey-1;10.79%;6.734MiB / 1.858GiB diff --git a/evidence/track1/safe-d0-r2.json b/evidence/track1/safe-d0-r2.json new file mode 100644 index 0000000..e4cbde5 --- /dev/null +++ b/evidence/track1/safe-d0-r2.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 411138, + "keyspace_misses": 9225 + }, + "date_utc": "2026-10-29T06:56:46Z", + "duration_s": 30, + "error_statuses": {}, + "label": "safe-d0-r2", + "raw_checks": 466, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 5.886, + "read_p95_ms": 14.445, + "read_p99_ms": 20.813, + "read_rps": 4631.166666666667, + "readers": 32, + "reads_ok": 138935, + "seed_messages": 150, + "sql": { + "history_page_calls": 477, + "history_page_total_ms": 82.85485599999994, + "insert_message_calls": 466, + "membership_calls": 0, + "total_calls": 943 + }, + "sql_history_per_read": 0.0034332601576276675, + "sql_read_path_per_read": 0.0034332601576276675, + "stale_checks": 138775, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 5886, + "read_errors": 0, + "read_p95_ms": 12.462, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 5272, + "read_errors": 0, + "read_p95_ms": 11.171, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 4069, + "read_errors": 0, + "read_p95_ms": 14.663, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 3547, + "read_errors": 0, + "read_p95_ms": 17.019, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 2614, + "read_errors": 0, + "read_p95_ms": 25.904, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 2536, + "read_errors": 0, + "read_p95_ms": 22.987, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 5467, + "read_errors": 0, + "read_p95_ms": 13.084, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 5180, + "read_errors": 0, + "read_p95_ms": 10.93, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 4193, + "read_errors": 0, + "read_p95_ms": 14.117, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 3878, + "read_errors": 0, + "read_p95_ms": 15.62, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 2829, + "read_errors": 0, + "read_p95_ms": 21.438, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 3237, + "read_errors": 0, + "read_p95_ms": 17.894, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 6178, + "read_errors": 0, + "read_p95_ms": 12.361, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 5755, + "read_errors": 0, + "read_p95_ms": 10.084, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 4967, + "read_errors": 0, + "read_p95_ms": 11.865, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 3847, + "read_errors": 0, + "read_p95_ms": 15.598, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 3744, + "read_errors": 0, + "read_p95_ms": 15.532, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 4037, + "read_errors": 0, + "read_p95_ms": 16.354, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 6862, + "read_errors": 0, + "read_p95_ms": 8.859, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 5965, + "read_errors": 0, + "read_p95_ms": 9.309, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 4277, + "read_errors": 0, + "read_p95_ms": 14.675, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 3985, + "read_errors": 0, + "read_p95_ms": 14.309, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 3241, + "read_errors": 0, + "read_p95_ms": 17.924, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 5030, + "read_errors": 0, + "read_p95_ms": 15.927, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 6826, + "read_errors": 0, + "read_p95_ms": 8.35, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 5816, + "read_errors": 0, + "read_p95_ms": 10.144, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 4584, + "read_errors": 0, + "read_p95_ms": 12.019, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 5346, + "read_errors": 0, + "read_p95_ms": 10.399, + "writes": 4, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 4910, + "read_errors": 0, + "read_p95_ms": 11.519, + "writes": 3, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 4857, + "read_errors": 0, + "read_p95_ms": 11.811, + "writes": 4, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 7.453, + "write_p95_ms": 20.688, + "writers": 2, + "writes_ok": 466 +} \ No newline at end of file diff --git a/evidence/track1/safe-d0-r2.stats.txt b/evidence/track1/safe-d0-r2.stats.txt new file mode 100644 index 0000000..e4f03bf --- /dev/null +++ b/evidence/track1/safe-d0-r2.stats.txt @@ -0,0 +1,90 @@ +mtusi-lab2-api-1;346.61%;16.1MiB / 1.858GiB +mtusi-lab2-postgres-1;5.62%;56.77MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;30.84%;11.38MiB / 1.858GiB +mtusi-lab2-valkey-1;13.33%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;185.86%;10.27MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;297.49%;10.29MiB / 1.858GiB +mtusi-lab2-api-1;468.54%;16.14MiB / 1.858GiB +mtusi-lab2-postgres-1;3.33%;56.77MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.22%;11.38MiB / 1.858GiB +mtusi-lab2-valkey-1;15.21%;6.816MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;251.70%;10.12MiB / 1.858GiB +mtusi-lab2-api-1;473.88%;14.7MiB / 1.858GiB +mtusi-lab2-postgres-1;2.26%;56.84MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;59.08%;11.61MiB / 1.858GiB +mtusi-lab2-valkey-1;23.95%;6.836MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;291.72%;10.2MiB / 1.858GiB +mtusi-lab2-api-1;471.61%;14.9MiB / 1.858GiB +mtusi-lab2-postgres-1;5.52%;57.12MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;47.75%;11.88MiB / 1.858GiB +mtusi-lab2-valkey-1;20.07%;7.137MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;300.26%;11.26MiB / 1.858GiB +mtusi-lab2-api-1;454.36%;17.78MiB / 1.858GiB +mtusi-lab2-postgres-1;2.89%;56.9MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.80%;8.375MiB / 1.858GiB +mtusi-lab2-valkey-1;15.26%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;270.00%;10.92MiB / 1.858GiB +mtusi-lab2-api-1;483.36%;14.36MiB / 1.858GiB +mtusi-lab2-postgres-1;2.52%;56.92MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;57.95%;9.305MiB / 1.858GiB +mtusi-lab2-valkey-1;23.89%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;304.72%;10.95MiB / 1.858GiB +mtusi-lab2-api-1;506.51%;14.32MiB / 1.858GiB +mtusi-lab2-postgres-1;2.29%;56.93MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.26%;8.883MiB / 1.858GiB +mtusi-lab2-valkey-1;19.32%;6.82MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;311.28%;12.36MiB / 1.858GiB +mtusi-lab2-api-1;500.77%;17.27MiB / 1.858GiB +mtusi-lab2-postgres-1;2.16%;56.95MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.61%;9.371MiB / 1.858GiB +mtusi-lab2-valkey-1;15.97%;6.812MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;256.03%;11.78MiB / 1.858GiB +mtusi-lab2-api-1;472.08%;14.94MiB / 1.858GiB +mtusi-lab2-postgres-1;3.95%;57.2MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;58.70%;10.52MiB / 1.858GiB +mtusi-lab2-valkey-1;24.91%;7.027MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;285.07%;12.62MiB / 1.858GiB +mtusi-lab2-api-1;497.24%;16.81MiB / 1.858GiB +mtusi-lab2-postgres-1;2.23%;56.98MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.24%;10.46MiB / 1.858GiB +mtusi-lab2-valkey-1;19.12%;6.852MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;291.83%;11.32MiB / 1.858GiB +mtusi-lab2-api-1;492.81%;13.91MiB / 1.858GiB +mtusi-lab2-postgres-1;2.01%;57MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;42.62%;11.05MiB / 1.858GiB +mtusi-lab2-valkey-1;16.74%;6.84MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;257.86%;13.17MiB / 1.858GiB +mtusi-lab2-api-1;511.50%;15.07MiB / 1.858GiB +mtusi-lab2-postgres-1;1.67%;57.01MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;58.23%;11.11MiB / 1.858GiB +mtusi-lab2-valkey-1;23.05%;6.836MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;284.80%;13.27MiB / 1.858GiB +mtusi-lab2-api-1;507.50%;17.21MiB / 1.858GiB +mtusi-lab2-postgres-1;2.28%;57.03MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;46.39%;11.47MiB / 1.858GiB +mtusi-lab2-valkey-1;18.24%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;262.53%;12.66MiB / 1.858GiB +mtusi-lab2-api-1;500.04%;13.9MiB / 1.858GiB +mtusi-lab2-postgres-1;4.17%;57.26MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;54.88%;12.54MiB / 1.858GiB +mtusi-lab2-valkey-1;23.42%;6.859MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;247.46%;13.66MiB / 1.858GiB +mtusi-lab2-api-1;524.43%;15.68MiB / 1.858GiB +mtusi-lab2-postgres-1;1.68%;57.05MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;56.32%;12.07MiB / 1.858GiB +mtusi-lab2-valkey-1;22.85%;6.855MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;277.48%;14.12MiB / 1.858GiB +mtusi-lab2-api-1;552.82%;15.29MiB / 1.858GiB +mtusi-lab2-postgres-1;0.58%;57.05MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;52.30%;12.53MiB / 1.858GiB +mtusi-lab2-valkey-1;20.84%;6.855MiB / 1.858GiB +mtusi-lab2-cachebench-run-e479c75dfd51;248.57%;13.54MiB / 1.858GiB +mtusi-lab2-api-1;473.42%;15.1MiB / 1.858GiB +mtusi-lab2-postgres-1;0.48%;57.05MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;43.95%;12.27MiB / 1.858GiB +mtusi-lab2-valkey-1;17.29%;6.781MiB / 1.858GiB +mtusi-lab2-api-1;0.38%;14.74MiB / 1.858GiB +mtusi-lab2-postgres-1;0.10%;55.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;1.06%;12.25MiB / 1.858GiB +mtusi-lab2-valkey-1;0.22%;6.777MiB / 1.858GiB +--;0.00%;0B / 0B diff --git a/evidence/track1/safe-d0-r3.json b/evidence/track1/safe-d0-r3.json new file mode 100644 index 0000000..c34710e --- /dev/null +++ b/evidence/track1/safe-d0-r3.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 461651, + "keyspace_misses": 8250 + }, + "date_utc": "2026-10-29T06:57:22Z", + "duration_s": 30, + "error_statuses": {}, + "label": "safe-d0-r3", + "raw_checks": 439, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 5.302, + "read_p95_ms": 12.651, + "read_p99_ms": 17.479, + "read_rps": 5183.833333333333, + "readers": 32, + "reads_ok": 155515, + "seed_messages": 150, + "sql": { + "history_page_calls": 437, + "history_page_total_ms": 66.76269700000006, + "insert_message_calls": 439, + "membership_calls": 0, + "total_calls": 876 + }, + "sql_history_per_read": 0.002810018326206475, + "sql_read_path_per_read": 0.002810018326206475, + "stale_checks": 155355, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 6513, + "read_errors": 0, + "read_p95_ms": 9.912, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 5828, + "read_errors": 0, + "read_p95_ms": 10.238, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 4798, + "read_errors": 0, + "read_p95_ms": 12.063, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 4263, + "read_errors": 0, + "read_p95_ms": 13.58, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 3615, + "read_errors": 0, + "read_p95_ms": 16.419, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 2918, + "read_errors": 0, + "read_p95_ms": 20.54, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 6848, + "read_errors": 0, + "read_p95_ms": 8.717, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 5062, + "read_errors": 0, + "read_p95_ms": 11.502, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 4578, + "read_errors": 0, + "read_p95_ms": 12.631, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 4171, + "read_errors": 0, + "read_p95_ms": 13.71, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 3325, + "read_errors": 0, + "read_p95_ms": 17.898, + "writes": 13, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 3378, + "read_errors": 0, + "read_p95_ms": 17.311, + "writes": 8, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 4818, + "read_errors": 0, + "read_p95_ms": 14.452, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 7457, + "read_errors": 0, + "read_p95_ms": 7.613, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 5485, + "read_errors": 0, + "read_p95_ms": 10.339, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 4854, + "read_errors": 0, + "read_p95_ms": 12.15, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 4030, + "read_errors": 0, + "read_p95_ms": 14.238, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 3932, + "read_errors": 0, + "read_p95_ms": 14.149, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 5224, + "read_errors": 0, + "read_p95_ms": 14.177, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 7740, + "read_errors": 0, + "read_p95_ms": 7.148, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 5934, + "read_errors": 0, + "read_p95_ms": 9.611, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 4345, + "read_errors": 0, + "read_p95_ms": 13.563, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 4480, + "read_errors": 0, + "read_p95_ms": 12.943, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 3882, + "read_errors": 0, + "read_p95_ms": 15.043, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 6529, + "read_errors": 0, + "read_p95_ms": 12.051, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 7387, + "read_errors": 0, + "read_p95_ms": 7.579, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 5667, + "read_errors": 0, + "read_p95_ms": 10.321, + "writes": 5, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 6156, + "read_errors": 0, + "read_p95_ms": 9.157, + "writes": 1, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 6059, + "read_errors": 0, + "read_p95_ms": 9.298, + "writes": 3, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 6239, + "read_errors": 0, + "read_p95_ms": 8.908, + "writes": 1, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 8.779, + "write_p95_ms": 25.259, + "writers": 2, + "writes_ok": 439 +} \ No newline at end of file diff --git a/evidence/track1/safe-d0-r3.stats.txt b/evidence/track1/safe-d0-r3.stats.txt new file mode 100644 index 0000000..6b21993 --- /dev/null +++ b/evidence/track1/safe-d0-r3.stats.txt @@ -0,0 +1,84 @@ +mtusi-lab2-api-1;50.95%;16.55MiB / 1.858GiB +mtusi-lab2-postgres-1;4.97%;57.08MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.37%;12.29MiB / 1.858GiB +mtusi-lab2-valkey-1;1.72%;6.812MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;286.50%;9.73MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;310.31%;10.45MiB / 1.858GiB +mtusi-lab2-api-1;494.34%;16.55MiB / 1.858GiB +mtusi-lab2-postgres-1;1.90%;57.16MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.14%;11.46MiB / 1.858GiB +mtusi-lab2-valkey-1;15.12%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;276.50%;10.88MiB / 1.858GiB +mtusi-lab2-api-1;485.16%;15.14MiB / 1.858GiB +mtusi-lab2-postgres-1;1.54%;57.17MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;57.15%;11.82MiB / 1.858GiB +mtusi-lab2-valkey-1;22.84%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;294.18%;11.5MiB / 1.858GiB +mtusi-lab2-api-1;479.00%;16.07MiB / 1.858GiB +mtusi-lab2-postgres-1;2.88%;57.43MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;44.72%;11.59MiB / 1.858GiB +mtusi-lab2-valkey-1;17.99%;6.824MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;311.53%;10.48MiB / 1.858GiB +mtusi-lab2-api-1;468.19%;13.38MiB / 1.858GiB +mtusi-lab2-postgres-1;2.25%;57.19MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.35%;11.8MiB / 1.858GiB +mtusi-lab2-valkey-1;16.23%;6.855MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;273.19%;11.32MiB / 1.858GiB +mtusi-lab2-api-1;473.73%;14.41MiB / 1.858GiB +mtusi-lab2-postgres-1;4.25%;61.13MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;54.80%;12.64MiB / 1.858GiB +mtusi-lab2-valkey-1;22.87%;7.246MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;308.24%;10.95MiB / 1.858GiB +mtusi-lab2-api-1;504.19%;16.78MiB / 1.858GiB +mtusi-lab2-postgres-1;2.16%;57.24MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;47.34%;9.82MiB / 1.858GiB +mtusi-lab2-valkey-1;18.74%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;308.24%;12.18MiB / 1.858GiB +mtusi-lab2-api-1;485.93%;18.05MiB / 1.858GiB +mtusi-lab2-postgres-1;1.53%;57.24MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.91%;9.949MiB / 1.858GiB +mtusi-lab2-valkey-1;15.74%;6.852MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;236.46%;10.89MiB / 1.858GiB +mtusi-lab2-api-1;480.16%;15.3MiB / 1.858GiB +mtusi-lab2-postgres-1;3.67%;57.24MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;63.83%;10.33MiB / 1.858GiB +mtusi-lab2-valkey-1;25.65%;6.836MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;281.68%;11.43MiB / 1.858GiB +mtusi-lab2-api-1;511.79%;15.44MiB / 1.858GiB +mtusi-lab2-postgres-1;1.83%;57.26MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;49.61%;10.66MiB / 1.858GiB +mtusi-lab2-valkey-1;20.13%;6.852MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;301.91%;12.49MiB / 1.858GiB +mtusi-lab2-api-1;500.33%;17.73MiB / 1.858GiB +mtusi-lab2-postgres-1;1.65%;57.26MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.79%;12.02MiB / 1.858GiB +mtusi-lab2-valkey-1;16.05%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;227.04%;12.9MiB / 1.858GiB +mtusi-lab2-api-1;500.08%;15.54MiB / 1.858GiB +mtusi-lab2-postgres-1;1.50%;57.27MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;61.67%;11.39MiB / 1.858GiB +mtusi-lab2-valkey-1;24.50%;6.855MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;281.83%;13.62MiB / 1.858GiB +mtusi-lab2-api-1;520.88%;15.3MiB / 1.858GiB +mtusi-lab2-postgres-1;1.75%;57.27MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;49.35%;11.81MiB / 1.858GiB +mtusi-lab2-valkey-1;19.34%;6.496MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;291.90%;14.06MiB / 1.858GiB +mtusi-lab2-api-1;524.20%;16.94MiB / 1.858GiB +mtusi-lab2-postgres-1;3.77%;57.28MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;43.49%;12.2MiB / 1.858GiB +mtusi-lab2-valkey-1;17.47%;6.5MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;227.28%;14.25MiB / 1.858GiB +mtusi-lab2-api-1;519.56%;15.12MiB / 1.858GiB +mtusi-lab2-postgres-1;1.20%;57.29MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;61.11%;12.83MiB / 1.858GiB +mtusi-lab2-valkey-1;24.76%;6.504MiB / 1.858GiB +mtusi-lab2-cachebench-run-65296b236717;240.98%;14.81MiB / 1.858GiB +mtusi-lab2-api-1;523.38%;15.71MiB / 1.858GiB +mtusi-lab2-postgres-1;1.37%;57.29MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;58.83%;13.11MiB / 1.858GiB +mtusi-lab2-valkey-1;23.16%;6.492MiB / 1.858GiB +mtusi-lab2-api-1;283.33%;13.28MiB / 1.858GiB +mtusi-lab2-postgres-1;0.88%;55.77MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;30.55%;12.38MiB / 1.858GiB +mtusi-lab2-valkey-1;12.13%;6.426MiB / 1.858GiB diff --git a/evidence/track1/safe-d20-r1.json b/evidence/track1/safe-d20-r1.json new file mode 100644 index 0000000..161081f --- /dev/null +++ b/evidence/track1/safe-d20-r1.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 400547, + "keyspace_misses": 10275 + }, + "date_utc": "2026-10-29T06:58:08Z", + "duration_s": 30, + "error_statuses": {}, + "label": "safe-d20-r1", + "raw_checks": 446, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 5.299, + "read_p95_ms": 22.994, + "read_p99_ms": 29.476, + "read_rps": 4530.566666666667, + "readers": 32, + "reads_ok": 135917, + "seed_messages": 150, + "sql": { + "history_page_calls": 403, + "history_page_total_ms": 55.220766999999995, + "insert_message_calls": 446, + "membership_calls": 0, + "total_calls": 849 + }, + "sql_history_per_read": 0.002965044843544222, + "sql_read_path_per_read": 0.002965044843544222, + "stale_checks": 135757, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 4813, + "read_errors": 0, + "read_p95_ms": 21.187, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 5765, + "read_errors": 0, + "read_p95_ms": 12.686, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 5022, + "read_errors": 0, + "read_p95_ms": 13.761, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 4221, + "read_errors": 0, + "read_p95_ms": 23.366, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 3724, + "read_errors": 0, + "read_p95_ms": 25.297, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 3478, + "read_errors": 0, + "read_p95_ms": 24.897, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 2873, + "read_errors": 0, + "read_p95_ms": 26.895, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 5099, + "read_errors": 0, + "read_p95_ms": 23.7, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 5681, + "read_errors": 0, + "read_p95_ms": 10.692, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 4851, + "read_errors": 0, + "read_p95_ms": 23.092, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 4125, + "read_errors": 0, + "read_p95_ms": 22.855, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 3640, + "read_errors": 0, + "read_p95_ms": 26.047, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 3117, + "read_errors": 0, + "read_p95_ms": 25.736, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 3219, + "read_errors": 0, + "read_p95_ms": 25.51, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 6190, + "read_errors": 0, + "read_p95_ms": 16.943, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 5716, + "read_errors": 0, + "read_p95_ms": 11.157, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 4897, + "read_errors": 0, + "read_p95_ms": 12.399, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 3656, + "read_errors": 0, + "read_p95_ms": 25.878, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 3783, + "read_errors": 0, + "read_p95_ms": 24.986, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 3606, + "read_errors": 0, + "read_p95_ms": 23.7, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 3916, + "read_errors": 0, + "read_p95_ms": 25.07, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 7510, + "read_errors": 0, + "read_p95_ms": 7.173, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 4553, + "read_errors": 0, + "read_p95_ms": 23.594, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 4802, + "read_errors": 0, + "read_p95_ms": 14.581, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 4047, + "read_errors": 0, + "read_p95_ms": 25.085, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 3982, + "read_errors": 0, + "read_p95_ms": 23.065, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 3418, + "read_errors": 0, + "read_p95_ms": 25.882, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 4610, + "read_errors": 0, + "read_p95_ms": 23.036, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 6116, + "read_errors": 0, + "read_p95_ms": 10.175, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 5487, + "read_errors": 0, + "read_p95_ms": 11.041, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 6.573, + "write_p95_ms": 15.666, + "writers": 2, + "writes_ok": 446 +} \ No newline at end of file diff --git a/evidence/track1/safe-d20-r1.stats.txt b/evidence/track1/safe-d20-r1.stats.txt new file mode 100644 index 0000000..ceb15b3 --- /dev/null +++ b/evidence/track1/safe-d20-r1.stats.txt @@ -0,0 +1,89 @@ +mtusi-lab2-api-1;163.09%;14.39MiB / 1.858GiB +mtusi-lab2-postgres-1;9.70%;56.89MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;17.87%;11.71MiB / 1.858GiB +mtusi-lab2-valkey-1;0.59%;6.406MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;95.39%;10.45MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;264.26%;10.02MiB / 1.858GiB +mtusi-lab2-api-1;430.97%;16.82MiB / 1.858GiB +mtusi-lab2-postgres-1;1.38%;56.97MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;36.36%;11.75MiB / 1.858GiB +mtusi-lab2-valkey-1;14.17%;6.902MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;185.16%;10.29MiB / 1.858GiB +mtusi-lab2-api-1;418.08%;12.99MiB / 1.858GiB +mtusi-lab2-postgres-1;1.19%;57.04MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;56.21%;12.29MiB / 1.858GiB +mtusi-lab2-valkey-1;22.78%;6.93MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;247.95%;11.04MiB / 1.858GiB +mtusi-lab2-api-1;424.80%;14.06MiB / 1.858GiB +mtusi-lab2-postgres-1;1.21%;57.06MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;44.80%;8.777MiB / 1.858GiB +mtusi-lab2-valkey-1;17.89%;6.895MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;267.67%;10.79MiB / 1.858GiB +mtusi-lab2-api-1;416.31%;14.56MiB / 1.858GiB +mtusi-lab2-postgres-1;1.48%;57.08MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.28%;9.188MiB / 1.858GiB +mtusi-lab2-valkey-1;14.74%;6.887MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;258.54%;9.816MiB / 1.858GiB +mtusi-lab2-api-1;416.49%;12.41MiB / 1.858GiB +mtusi-lab2-postgres-1;3.83%;57.32MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;39.38%;9.426MiB / 1.858GiB +mtusi-lab2-valkey-1;16.30%;6.914MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;236.04%;10.69MiB / 1.858GiB +mtusi-lab2-api-1;419.89%;15.25MiB / 1.858GiB +mtusi-lab2-postgres-1;1.17%;57.08MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;47.70%;9.699MiB / 1.858GiB +mtusi-lab2-valkey-1;19.18%;6.898MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;257.64%;10.95MiB / 1.858GiB +mtusi-lab2-api-1;439.89%;14.39MiB / 1.858GiB +mtusi-lab2-postgres-1;1.08%;57.08MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.00%;9.648MiB / 1.858GiB +mtusi-lab2-valkey-1;16.06%;6.906MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;275.93%;11.82MiB / 1.858GiB +mtusi-lab2-api-1;429.78%;16MiB / 1.858GiB +mtusi-lab2-postgres-1;1.42%;57.09MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;36.37%;9.758MiB / 1.858GiB +mtusi-lab2-valkey-1;14.14%;6.895MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;209.38%;11.38MiB / 1.858GiB +mtusi-lab2-api-1;423.74%;15.08MiB / 1.858GiB +mtusi-lab2-postgres-1;1.18%;57.11MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;53.72%;10.24MiB / 1.858GiB +mtusi-lab2-valkey-1;21.26%;6.914MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;236.13%;11.95MiB / 1.858GiB +mtusi-lab2-api-1;427.89%;16.15MiB / 1.858GiB +mtusi-lab2-postgres-1;3.40%;57.11MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;43.16%;10.19MiB / 1.858GiB +mtusi-lab2-valkey-1;18.25%;6.918MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;271.50%;12.7MiB / 1.858GiB +mtusi-lab2-api-1;459.30%;17.58MiB / 1.858GiB +mtusi-lab2-postgres-1;1.16%;57.11MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;39.08%;10.61MiB / 1.858GiB +mtusi-lab2-valkey-1;15.18%;6.891MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;177.85%;13.13MiB / 1.858GiB +mtusi-lab2-api-1;437.08%;14.11MiB / 1.858GiB +mtusi-lab2-postgres-1;1.56%;58.54MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;59.93%;11.05MiB / 1.858GiB +mtusi-lab2-valkey-1;24.35%;6.859MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;230.47%;12.7MiB / 1.858GiB +mtusi-lab2-api-1;440.55%;14.54MiB / 1.858GiB +mtusi-lab2-postgres-1;1.24%;57.12MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;46.21%;11.25MiB / 1.858GiB +mtusi-lab2-valkey-1;18.59%;6.824MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;247.97%;13.98MiB / 1.858GiB +mtusi-lab2-api-1;458.24%;15.88MiB / 1.858GiB +mtusi-lab2-postgres-1;1.20%;57.13MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.16%;11.57MiB / 1.858GiB +mtusi-lab2-valkey-1;15.78%;6.816MiB / 1.858GiB +mtusi-lab2-cachebench-run-b4bb830d9555;219.63%;13.32MiB / 1.858GiB +mtusi-lab2-api-1;420.48%;13.91MiB / 1.858GiB +mtusi-lab2-postgres-1;3.62%;57.14MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.29%;12.12MiB / 1.858GiB +mtusi-lab2-valkey-1;17.73%;6.828MiB / 1.858GiB +mtusi-lab2-api-1;459.48%;15.22MiB / 1.858GiB +mtusi-lab2-postgres-1;1.19%;57.13MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;50.76%;12.09MiB / 1.858GiB +mtusi-lab2-valkey-1;20.04%;6.859MiB / 1.858GiB +mtusi-lab2-api-1;32.98%;60.29MiB / 1.858GiB +mtusi-lab2-postgres-1;4.48%;57.31MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;1.38%;12.12MiB / 1.858GiB +mtusi-lab2-valkey-1;1.28%;6.816MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;240.93%;9.531MiB / 1.858GiB diff --git a/evidence/track1/safe-d20-r2.json b/evidence/track1/safe-d20-r2.json new file mode 100644 index 0000000..b01757a --- /dev/null +++ b/evidence/track1/safe-d20-r2.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 394053, + "keyspace_misses": 10100 + }, + "date_utc": "2026-10-29T06:58:43Z", + "duration_s": 30, + "error_statuses": {}, + "label": "safe-d20-r2", + "raw_checks": 450, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 5.333, + "read_p95_ms": 23.449, + "read_p99_ms": 29.757, + "read_rps": 4455.766666666666, + "readers": 32, + "reads_ok": 133673, + "seed_messages": 150, + "sql": { + "history_page_calls": 407, + "history_page_total_ms": 56.04441999999998, + "insert_message_calls": 450, + "membership_calls": 0, + "total_calls": 857 + }, + "sql_history_per_read": 0.003044743515893262, + "sql_read_path_per_read": 0.003044743515893262, + "stale_checks": 133513, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 5304, + "read_errors": 0, + "read_p95_ms": 21.431, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 6025, + "read_errors": 0, + "read_p95_ms": 9.412, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 4749, + "read_errors": 0, + "read_p95_ms": 23.239, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 3760, + "read_errors": 0, + "read_p95_ms": 24.977, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 3405, + "read_errors": 0, + "read_p95_ms": 25.92, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 3276, + "read_errors": 0, + "read_p95_ms": 26.05, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 2925, + "read_errors": 0, + "read_p95_ms": 26.629, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 6159, + "read_errors": 0, + "read_p95_ms": 15.513, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 4689, + "read_errors": 0, + "read_p95_ms": 17.614, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 4518, + "read_errors": 0, + "read_p95_ms": 24.325, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 3958, + "read_errors": 0, + "read_p95_ms": 23.615, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 3518, + "read_errors": 0, + "read_p95_ms": 26.885, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 3245, + "read_errors": 0, + "read_p95_ms": 26.521, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 3350, + "read_errors": 0, + "read_p95_ms": 27.032, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 6479, + "read_errors": 0, + "read_p95_ms": 8.603, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 5176, + "read_errors": 0, + "read_p95_ms": 13.849, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 4512, + "read_errors": 0, + "read_p95_ms": 22.077, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 4165, + "read_errors": 0, + "read_p95_ms": 24.268, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 3278, + "read_errors": 0, + "read_p95_ms": 26.462, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 3096, + "read_errors": 0, + "read_p95_ms": 26.75, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 4956, + "read_errors": 0, + "read_p95_ms": 20.491, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 6204, + "read_errors": 0, + "read_p95_ms": 9.539, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 5228, + "read_errors": 0, + "read_p95_ms": 14.196, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 4432, + "read_errors": 0, + "read_p95_ms": 21.029, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 3574, + "read_errors": 0, + "read_p95_ms": 25.031, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 3551, + "read_errors": 0, + "read_p95_ms": 25.897, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 3138, + "read_errors": 0, + "read_p95_ms": 27.452, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 6721, + "read_errors": 0, + "read_p95_ms": 12.528, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 6000, + "read_errors": 0, + "read_p95_ms": 10.708, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 4282, + "read_errors": 0, + "read_p95_ms": 23.399, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 5.889, + "write_p95_ms": 11.421, + "writers": 2, + "writes_ok": 450 +} \ No newline at end of file diff --git a/evidence/track1/safe-d20-r2.stats.txt b/evidence/track1/safe-d20-r2.stats.txt new file mode 100644 index 0000000..0d30f9d --- /dev/null +++ b/evidence/track1/safe-d20-r2.stats.txt @@ -0,0 +1,84 @@ +mtusi-lab2-api-1;410.87%;14.67MiB / 1.858GiB +mtusi-lab2-postgres-1;4.14%;57.31MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.44%;11.82MiB / 1.858GiB +mtusi-lab2-valkey-1;17.53%;6.836MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;240.93%;9.531MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;270.71%;10.16MiB / 1.858GiB +mtusi-lab2-api-1;426.63%;15.55MiB / 1.858GiB +mtusi-lab2-postgres-1;1.88%;57.4MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;35.85%;11.85MiB / 1.858GiB +mtusi-lab2-valkey-1;13.64%;6.84MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;221.62%;9.738MiB / 1.858GiB +mtusi-lab2-api-1;429.56%;14.14MiB / 1.858GiB +mtusi-lab2-postgres-1;1.20%;57.39MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;52.89%;11.85MiB / 1.858GiB +mtusi-lab2-valkey-1;21.04%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;251.79%;10.32MiB / 1.858GiB +mtusi-lab2-api-1;422.08%;15.95MiB / 1.858GiB +mtusi-lab2-postgres-1;1.70%;57.39MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.03%;12.07MiB / 1.858GiB +mtusi-lab2-valkey-1;16.76%;7.07MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;275.18%;10.91MiB / 1.858GiB +mtusi-lab2-api-1;418.55%;15.9MiB / 1.858GiB +mtusi-lab2-postgres-1;1.36%;57.41MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;36.27%;8.699MiB / 1.858GiB +mtusi-lab2-valkey-1;13.77%;6.824MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;196.51%;10.21MiB / 1.858GiB +mtusi-lab2-api-1;396.55%;14.45MiB / 1.858GiB +mtusi-lab2-postgres-1;3.03%;57.41MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;56.46%;8.961MiB / 1.858GiB +mtusi-lab2-valkey-1;23.45%;6.848MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;258.88%;11.26MiB / 1.858GiB +mtusi-lab2-api-1;439.41%;15.17MiB / 1.858GiB +mtusi-lab2-postgres-1;1.12%;57.43MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.52%;9.391MiB / 1.858GiB +mtusi-lab2-valkey-1;17.91%;6.852MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;279.37%;11.46MiB / 1.858GiB +mtusi-lab2-api-1;452.75%;16.47MiB / 1.858GiB +mtusi-lab2-postgres-1;1.34%;57.43MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;39.96%;9.559MiB / 1.858GiB +mtusi-lab2-valkey-1;15.37%;6.824MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;222.07%;10.73MiB / 1.858GiB +mtusi-lab2-api-1;429.45%;13.45MiB / 1.858GiB +mtusi-lab2-postgres-1;1.60%;57.45MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.03%;10.15MiB / 1.858GiB +mtusi-lab2-valkey-1;18.05%;6.859MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;239.43%;12MiB / 1.858GiB +mtusi-lab2-api-1;440.04%;16.18MiB / 1.858GiB +mtusi-lab2-postgres-1;1.26%;57.46MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.84%;9.883MiB / 1.858GiB +mtusi-lab2-valkey-1;19.34%;6.812MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;244.92%;11.85MiB / 1.858GiB +mtusi-lab2-api-1;434.71%;16.83MiB / 1.858GiB +mtusi-lab2-postgres-1;3.26%;57.46MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.97%;10.45MiB / 1.858GiB +mtusi-lab2-valkey-1;16.42%;7.07MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;268.15%;13.25MiB / 1.858GiB +mtusi-lab2-api-1;449.02%;16.79MiB / 1.858GiB +mtusi-lab2-postgres-1;1.32%;57.47MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.03%;10.64MiB / 1.858GiB +mtusi-lab2-valkey-1;14.21%;6.82MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;204.62%;12.42MiB / 1.858GiB +mtusi-lab2-api-1;452.28%;13.36MiB / 1.858GiB +mtusi-lab2-postgres-1;1.23%;57.47MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;53.64%;10.83MiB / 1.858GiB +mtusi-lab2-valkey-1;21.67%;6.859MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;236.63%;12.61MiB / 1.858GiB +mtusi-lab2-api-1;436.53%;15.66MiB / 1.858GiB +mtusi-lab2-postgres-1;1.39%;57.48MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;41.58%;11MiB / 1.858GiB +mtusi-lab2-valkey-1;17.01%;6.859MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;259.09%;13.81MiB / 1.858GiB +mtusi-lab2-api-1;452.11%;17.82MiB / 1.858GiB +mtusi-lab2-postgres-1;1.44%;57.5MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;38.06%;11.41MiB / 1.858GiB +mtusi-lab2-valkey-1;14.73%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-b34fa5bdcb68;165.97%;13.3MiB / 1.858GiB +mtusi-lab2-api-1;438.99%;13.96MiB / 1.858GiB +mtusi-lab2-postgres-1;2.92%;57.5MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;58.75%;11.69MiB / 1.858GiB +mtusi-lab2-valkey-1;23.96%;6.859MiB / 1.858GiB +mtusi-lab2-api-1;255.26%;14.89MiB / 1.858GiB +mtusi-lab2-postgres-1;1.50%;55.98MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;26.12%;11.77MiB / 1.858GiB +mtusi-lab2-valkey-1;10.16%;6.781MiB / 1.858GiB diff --git a/evidence/track1/safe-d20-r3.json b/evidence/track1/safe-d20-r3.json new file mode 100644 index 0000000..6f1da5d --- /dev/null +++ b/evidence/track1/safe-d20-r3.json @@ -0,0 +1,351 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 380532, + "keyspace_misses": 10067 + }, + "date_utc": "2026-10-29T06:59:18Z", + "duration_s": 30, + "error_statuses": {}, + "label": "safe-d20-r3", + "raw_checks": 448, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 5.47, + "read_p95_ms": 24.029, + "read_p99_ms": 30.27, + "read_rps": 4305.566666666667, + "readers": 32, + "reads_ok": 129167, + "seed_messages": 150, + "sql": { + "history_page_calls": 410, + "history_page_total_ms": 59.12355100000003, + "insert_message_calls": 448, + "membership_calls": 0, + "total_calls": 858 + }, + "sql_history_per_read": 0.0031741853569410144, + "sql_read_path_per_read": 0.0031741853569410144, + "stale_checks": 129007, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 4896, + "read_errors": 0, + "read_p95_ms": 22.761, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 5470, + "read_errors": 0, + "read_p95_ms": 15.776, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 4819, + "read_errors": 0, + "read_p95_ms": 22.613, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 3690, + "read_errors": 0, + "read_p95_ms": 24.591, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 3069, + "read_errors": 0, + "read_p95_ms": 27.421, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 2237, + "read_errors": 0, + "read_p95_ms": 33.606, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 2792, + "read_errors": 0, + "read_p95_ms": 27.406, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 5392, + "read_errors": 0, + "read_p95_ms": 19.911, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 5241, + "read_errors": 0, + "read_p95_ms": 14.951, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 4421, + "read_errors": 0, + "read_p95_ms": 22.509, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 3383, + "read_errors": 0, + "read_p95_ms": 26.08, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 3144, + "read_errors": 0, + "read_p95_ms": 26.413, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 2877, + "read_errors": 0, + "read_p95_ms": 28.021, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 2912, + "read_errors": 0, + "read_p95_ms": 27.928, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 6961, + "read_errors": 0, + "read_p95_ms": 7.951, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 4618, + "read_errors": 0, + "read_p95_ms": 22.411, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 4766, + "read_errors": 0, + "read_p95_ms": 15.08, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 3852, + "read_errors": 0, + "read_p95_ms": 25.757, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 3760, + "read_errors": 0, + "read_p95_ms": 23.825, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 3291, + "read_errors": 0, + "read_p95_ms": 25.346, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 4230, + "read_errors": 0, + "read_p95_ms": 23.516, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 6180, + "read_errors": 0, + "read_p95_ms": 9.151, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 5358, + "read_errors": 0, + "read_p95_ms": 11.792, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 4002, + "read_errors": 0, + "read_p95_ms": 25.187, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 4293, + "read_errors": 0, + "read_p95_ms": 22.865, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 3403, + "read_errors": 0, + "read_p95_ms": 25.117, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 3109, + "read_errors": 0, + "read_p95_ms": 26.865, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 5735, + "read_errors": 0, + "read_p95_ms": 16.176, + "writes": 14, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 6223, + "read_errors": 0, + "read_p95_ms": 10.328, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 5040, + "read_errors": 0, + "read_p95_ms": 21.457, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 30, + "reads": 3, + "read_errors": 0, + "read_p95_ms": 4.728, + "writes": 0, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 6.108, + "write_p95_ms": 14.331, + "writers": 2, + "writes_ok": 448 +} \ No newline at end of file diff --git a/evidence/track1/safe-d20-r3.stats.txt b/evidence/track1/safe-d20-r3.stats.txt new file mode 100644 index 0000000..ef8e145 --- /dev/null +++ b/evidence/track1/safe-d20-r3.stats.txt @@ -0,0 +1,83 @@ +mtusi-lab2-api-1;261.30%;15.08MiB / 1.858GiB +mtusi-lab2-postgres-1;5.11%;57.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;22.40%;11.79MiB / 1.858GiB +mtusi-lab2-valkey-1;9.49%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;263.69%;9.652MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;258.97%;9.328MiB / 1.858GiB +mtusi-lab2-api-1;420.87%;14.09MiB / 1.858GiB +mtusi-lab2-postgres-1;1.67%;57.6MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;36.65%;11.7MiB / 1.858GiB +mtusi-lab2-valkey-1;14.19%;6.863MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;241.84%;9.863MiB / 1.858GiB +mtusi-lab2-api-1;436.39%;12.98MiB / 1.858GiB +mtusi-lab2-postgres-1;1.32%;57.61MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;49.95%;11.66MiB / 1.858GiB +mtusi-lab2-valkey-1;19.67%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;259.61%;10.43MiB / 1.858GiB +mtusi-lab2-api-1;413.27%;15.23MiB / 1.858GiB +mtusi-lab2-postgres-1;1.95%;57.62MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;39.00%;11.89MiB / 1.858GiB +mtusi-lab2-valkey-1;15.88%;6.863MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;260.40%;11.14MiB / 1.858GiB +mtusi-lab2-api-1;389.97%;18.05MiB / 1.858GiB +mtusi-lab2-postgres-1;1.62%;57.62MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;34.55%;11.72MiB / 1.858GiB +mtusi-lab2-valkey-1;13.13%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;231.51%;11.01MiB / 1.858GiB +mtusi-lab2-api-1;417.43%;14.11MiB / 1.858GiB +mtusi-lab2-postgres-1;3.32%;57.63MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;56.20%;12.02MiB / 1.858GiB +mtusi-lab2-valkey-1;23.12%;6.867MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;252.37%;11.46MiB / 1.858GiB +mtusi-lab2-api-1;426.95%;15.88MiB / 1.858GiB +mtusi-lab2-postgres-1;1.36%;57.64MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;42.08%;9.441MiB / 1.858GiB +mtusi-lab2-valkey-1;17.57%;6.828MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;259.71%;12.28MiB / 1.858GiB +mtusi-lab2-api-1;410.96%;15.7MiB / 1.858GiB +mtusi-lab2-postgres-1;22.00%;57.68MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.24%;9.695MiB / 1.858GiB +mtusi-lab2-valkey-1;13.84%;6.832MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;200.13%;10.59MiB / 1.858GiB +mtusi-lab2-api-1;429.44%;13.98MiB / 1.858GiB +mtusi-lab2-postgres-1;1.18%;57.71MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;54.30%;10.02MiB / 1.858GiB +mtusi-lab2-valkey-1;21.47%;6.863MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;238.67%;10.57MiB / 1.858GiB +mtusi-lab2-api-1;432.19%;14.54MiB / 1.858GiB +mtusi-lab2-postgres-1;1.35%;57.71MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;46.85%;10.14MiB / 1.858GiB +mtusi-lab2-valkey-1;18.63%;6.844MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;252.36%;12.71MiB / 1.858GiB +mtusi-lab2-api-1;429.33%;17.04MiB / 1.858GiB +mtusi-lab2-postgres-1;3.47%;57.92MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.16%;10.7MiB / 1.858GiB +mtusi-lab2-valkey-1;16.42%;7.008MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;260.05%;11.6MiB / 1.858GiB +mtusi-lab2-api-1;445.85%;13.52MiB / 1.858GiB +mtusi-lab2-postgres-1;1.71%;58.21MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;40.58%;10.96MiB / 1.858GiB +mtusi-lab2-valkey-1;15.89%;6.859MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;213.42%;12.34MiB / 1.858GiB +mtusi-lab2-api-1;437.87%;16MiB / 1.858GiB +mtusi-lab2-postgres-1;1.26%;57.72MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;50.14%;11.46MiB / 1.858GiB +mtusi-lab2-valkey-1;19.82%;6.863MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;253.42%;13.59MiB / 1.858GiB +mtusi-lab2-api-1;465.41%;15.7MiB / 1.858GiB +mtusi-lab2-postgres-1;1.27%;57.75MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;44.08%;11.13MiB / 1.858GiB +mtusi-lab2-valkey-1;16.93%;6.855MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;261.54%;14.02MiB / 1.858GiB +mtusi-lab2-api-1;449.02%;16.8MiB / 1.858GiB +mtusi-lab2-postgres-1;1.43%;57.75MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;37.26%;12MiB / 1.858GiB +mtusi-lab2-valkey-1;15.19%;6.848MiB / 1.858GiB +mtusi-lab2-cachebench-run-718134b44bb5;181.29%;13.21MiB / 1.858GiB +mtusi-lab2-api-1;446.46%;13.97MiB / 1.858GiB +mtusi-lab2-postgres-1;3.03%;58.09MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;57.11%;12.54MiB / 1.858GiB +mtusi-lab2-valkey-1;23.20%;7.301MiB / 1.858GiB +mtusi-lab2-postgres-1;2.23%;49.65MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;2.13%;11.55MiB / 1.858GiB +mtusi-lab2-valkey-1;1.06%;7.004MiB / 1.858GiB diff --git a/evidence/track1/safe-pause.json b/evidence/track1/safe-pause.json new file mode 100644 index 0000000..1c2bc9c --- /dev/null +++ b/evidence/track1/safe-pause.json @@ -0,0 +1,341 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 398700, + "keyspace_misses": 7737 + }, + "date_utc": "2026-10-29T07:01:13Z", + "duration_s": 30, + "error_statuses": {}, + "label": "safe-pause", + "raw_checks": 464, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 4.921, + "read_p95_ms": 12.471, + "read_p99_ms": 17.238, + "read_rps": 5363.7, + "readers": 32, + "reads_ok": 160911, + "seed_messages": 150, + "sql": { + "history_page_calls": 26942, + "history_page_total_ms": 4440.536608999984, + "insert_message_calls": 464, + "membership_calls": 26525, + "total_calls": 53931 + }, + "sql_history_per_read": 0.1674341716849687, + "sql_read_path_per_read": 0.33227684869275564, + "stale_checks": 160751, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 9069, + "read_errors": 0, + "read_p95_ms": 6.673, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 6724, + "read_errors": 0, + "read_p95_ms": 8.537, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 5003, + "read_errors": 0, + "read_p95_ms": 11.923, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 3886, + "read_errors": 0, + "read_p95_ms": 15.401, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 3629, + "read_errors": 0, + "read_p95_ms": 15.929, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 5095, + "read_errors": 0, + "read_p95_ms": 15.143, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 7860, + "read_errors": 0, + "read_p95_ms": 7.392, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 5522, + "read_errors": 0, + "read_p95_ms": 10.61, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 4789, + "read_errors": 0, + "read_p95_ms": 12.729, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 2238, + "read_errors": 0, + "read_p95_ms": 16.37, + "writes": 12, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 4092, + "read_errors": 0, + "read_p95_ms": 14.176, + "writes": 6, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 3922, + "read_errors": 0, + "read_p95_ms": 14.86, + "writes": 6, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 3928, + "read_errors": 0, + "read_p95_ms": 15.002, + "writes": 6, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 3471, + "read_errors": 0, + "read_p95_ms": 17.376, + "writes": 6, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 3298, + "read_errors": 0, + "read_p95_ms": 17.977, + "writes": 6, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 6880, + "read_errors": 0, + "read_p95_ms": 8.432, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 6989, + "read_errors": 0, + "read_p95_ms": 7.723, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 5469, + "read_errors": 0, + "read_p95_ms": 10.021, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 5065, + "read_errors": 0, + "read_p95_ms": 11.109, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 3488, + "read_errors": 0, + "read_p95_ms": 17.234, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 4919, + "read_errors": 0, + "read_p95_ms": 14.178, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 8928, + "read_errors": 0, + "read_p95_ms": 5.838, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 6683, + "read_errors": 0, + "read_p95_ms": 8.126, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 5425, + "read_errors": 0, + "read_p95_ms": 10.063, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 4376, + "read_errors": 0, + "read_p95_ms": 13.355, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 3907, + "read_errors": 0, + "read_p95_ms": 14.764, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 7145, + "read_errors": 0, + "read_p95_ms": 11.152, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 7825, + "read_errors": 0, + "read_p95_ms": 6.87, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 6436, + "read_errors": 0, + "read_p95_ms": 8.723, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 4850, + "read_errors": 0, + "read_p95_ms": 11.537, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 5.94, + "write_p95_ms": 210.593, + "writers": 2, + "writes_ok": 464 +} \ No newline at end of file diff --git a/evidence/track1/safe-pause.stats.txt b/evidence/track1/safe-pause.stats.txt new file mode 100644 index 0000000..071721e --- /dev/null +++ b/evidence/track1/safe-pause.stats.txt @@ -0,0 +1,84 @@ +mtusi-lab2-api-1;518.88%;18.09MiB / 1.858GiB +mtusi-lab2-postgres-1;2.62%;72.46MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.92%;6.141MiB / 1.858GiB +mtusi-lab2-valkey-1;4.67%;6.918MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;301.48%;10.2MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;284.69%;9.543MiB / 1.858GiB +mtusi-lab2-api-1;489.71%;14.39MiB / 1.858GiB +mtusi-lab2-postgres-1;3.63%;72.54MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.92%;6.484MiB / 1.858GiB +mtusi-lab2-valkey-1;20.19%;6.93MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;287.98%;9.902MiB / 1.858GiB +mtusi-lab2-api-1;487.32%;15.2MiB / 1.858GiB +mtusi-lab2-postgres-1;1.37%;72.54MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;55.53%;6.754MiB / 1.858GiB +mtusi-lab2-valkey-1;22.43%;6.91MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;297.05%;11.68MiB / 1.858GiB +mtusi-lab2-api-1;461.15%;16.93MiB / 1.858GiB +mtusi-lab2-postgres-1;1.64%;72.54MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;42.50%;6.879MiB / 1.858GiB +mtusi-lab2-valkey-1;17.19%;6.906MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;273.40%;9.996MiB / 1.858GiB +mtusi-lab2-api-1;470.02%;15MiB / 1.858GiB +mtusi-lab2-postgres-1;1.59%;72.56MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;57.50%;6.973MiB / 1.858GiB +mtusi-lab2-valkey-1;23.38%;6.93MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;289.88%;11.34MiB / 1.858GiB +mtusi-lab2-api-1;498.20%;17.88MiB / 1.858GiB +mtusi-lab2-postgres-1;1.36%;72.57MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;53.67%;7.297MiB / 1.858GiB +mtusi-lab2-valkey-1;21.39%;6.918MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;170.41%;11.84MiB / 1.858GiB +mtusi-lab2-api-1;237.26%;17.8MiB / 1.858GiB +mtusi-lab2-postgres-1;90.65%;73.15MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;5.41%;7.355MiB / 1.858GiB +mtusi-lab2-valkey-1;11.25%;6.902MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;295.40%;12.18MiB / 1.858GiB +mtusi-lab2-api-1;389.97%;18.04MiB / 1.858GiB +mtusi-lab2-postgres-1;191.24%;72.94MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.00%;7.355MiB / 1.858GiB +mtusi-lab2-valkey-1;16.65%;6.914MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;289.54%;13.16MiB / 1.858GiB +mtusi-lab2-api-1;375.45%;19.31MiB / 1.858GiB +mtusi-lab2-postgres-1;183.59%;73.17MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.00%;7.355MiB / 1.858GiB +mtusi-lab2-valkey-1;16.24%;6.902MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;217.31%;11.71MiB / 1.858GiB +mtusi-lab2-api-1;435.02%;16.28MiB / 1.858GiB +mtusi-lab2-postgres-1;158.96%;72.6MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;25.17%;7.281MiB / 1.858GiB +mtusi-lab2-valkey-1;27.07%;6.926MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;290.76%;13.63MiB / 1.858GiB +mtusi-lab2-api-1;518.13%;17.85MiB / 1.858GiB +mtusi-lab2-postgres-1;1.78%;72.61MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;51.64%;8.148MiB / 1.858GiB +mtusi-lab2-valkey-1;20.30%;6.91MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;299.68%;13.66MiB / 1.858GiB +mtusi-lab2-api-1;500.38%;18.24MiB / 1.858GiB +mtusi-lab2-postgres-1;4.01%;72.82MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;43.14%;9.227MiB / 1.858GiB +mtusi-lab2-valkey-1;17.52%;6.906MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;235.06%;13.98MiB / 1.858GiB +mtusi-lab2-api-1;522.19%;15.76MiB / 1.858GiB +mtusi-lab2-postgres-1;1.64%;72.63MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;65.81%;8.945MiB / 1.858GiB +mtusi-lab2-valkey-1;26.36%;6.543MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;275.32%;13.75MiB / 1.858GiB +mtusi-lab2-api-1;514.59%;18.88MiB / 1.858GiB +mtusi-lab2-postgres-1;1.77%;72.64MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;48.85%;9.859MiB / 1.858GiB +mtusi-lab2-valkey-1;19.24%;6.559MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;306.12%;12.64MiB / 1.858GiB +mtusi-lab2-api-1;539.49%;15.68MiB / 1.858GiB +mtusi-lab2-postgres-1;1.92%;72.64MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;45.41%;9.875MiB / 1.858GiB +mtusi-lab2-valkey-1;17.40%;6.559MiB / 1.858GiB +mtusi-lab2-cachebench-run-0776f55c1310;234.35%;15.77MiB / 1.858GiB +mtusi-lab2-api-1;524.94%;17.29MiB / 1.858GiB +mtusi-lab2-postgres-1;1.61%;72.66MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;60.96%;9.852MiB / 1.858GiB +mtusi-lab2-valkey-1;24.59%;6.559MiB / 1.858GiB +mtusi-lab2-api-1;198.90%;16.82MiB / 1.858GiB +mtusi-lab2-postgres-1;3.32%;71.35MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;20.12%;9.867MiB / 1.858GiB +mtusi-lab2-valkey-1;8.76%;6.703MiB / 1.858GiB diff --git a/evidence/track1/safe-restart.json b/evidence/track1/safe-restart.json new file mode 100644 index 0000000..77f33ea --- /dev/null +++ b/evidence/track1/safe-restart.json @@ -0,0 +1,351 @@ +{ + "cache": { + "evicted_keys": 0, + "keyspace_hits": 208477, + "keyspace_misses": 4025 + }, + "date_utc": "2026-10-29T07:00:01Z", + "duration_s": 30, + "error_statuses": {}, + "label": "safe-restart", + "raw_checks": 522, + "raw_violations": 0, + "read_errors": 0, + "read_p50_ms": 5.293, + "read_p95_ms": 13.104, + "read_p99_ms": 18.388, + "read_rps": 5117.4, + "readers": 32, + "reads_ok": 153522, + "seed_messages": 150, + "sql": { + "history_page_calls": 34955, + "history_page_total_ms": 5102.902426999931, + "insert_message_calls": 522, + "membership_calls": 34579, + "total_calls": 70056 + }, + "sql_history_per_read": 0.22768723700837665, + "sql_read_path_per_read": 0.4529253136358307, + "stale_checks": 153330, + "stale_reads": 0, + "timeline": [ + { + "s": 0, + "reads": 7692, + "read_errors": 0, + "read_p95_ms": 7.858, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 1, + "reads": 5873, + "read_errors": 0, + "read_p95_ms": 10.078, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 2, + "reads": 4776, + "read_errors": 0, + "read_p95_ms": 12.478, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 3, + "reads": 3855, + "read_errors": 0, + "read_p95_ms": 16.217, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 4, + "reads": 3092, + "read_errors": 0, + "read_p95_ms": 19.234, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 5, + "reads": 4433, + "read_errors": 0, + "read_p95_ms": 15.446, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 6, + "reads": 7001, + "read_errors": 0, + "read_p95_ms": 8.334, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 7, + "reads": 5737, + "read_errors": 0, + "read_p95_ms": 9.937, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 8, + "reads": 4475, + "read_errors": 0, + "read_p95_ms": 13.945, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 9, + "reads": 3328, + "read_errors": 0, + "read_p95_ms": 18.103, + "writes": 15, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 10, + "reads": 3464, + "read_errors": 0, + "read_p95_ms": 17.255, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 11, + "reads": 4442, + "read_errors": 0, + "read_p95_ms": 17.381, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 12, + "reads": 6309, + "read_errors": 0, + "read_p95_ms": 8.573, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 13, + "reads": 5296, + "read_errors": 0, + "read_p95_ms": 10.274, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 14, + "reads": 3808, + "read_errors": 0, + "read_p95_ms": 15.519, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 15, + "reads": 3683, + "read_errors": 0, + "read_p95_ms": 15.385, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 16, + "reads": 3717, + "read_errors": 0, + "read_p95_ms": 15.184, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 17, + "reads": 6681, + "read_errors": 0, + "read_p95_ms": 12.586, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 18, + "reads": 7216, + "read_errors": 0, + "read_p95_ms": 7.551, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 19, + "reads": 4621, + "read_errors": 0, + "read_p95_ms": 13.688, + "writes": 17, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 20, + "reads": 4284, + "read_errors": 0, + "read_p95_ms": 13.161, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 21, + "reads": 4195, + "read_errors": 0, + "read_p95_ms": 13.945, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 22, + "reads": 3757, + "read_errors": 0, + "read_p95_ms": 15.398, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 23, + "reads": 8646, + "read_errors": 0, + "read_p95_ms": 7.539, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 24, + "reads": 5886, + "read_errors": 0, + "read_p95_ms": 10.104, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 25, + "reads": 5452, + "read_errors": 0, + "read_p95_ms": 10.164, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 26, + "reads": 4641, + "read_errors": 0, + "read_p95_ms": 12.31, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 27, + "reads": 4145, + "read_errors": 0, + "read_p95_ms": 13.413, + "writes": 18, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 28, + "reads": 4481, + "read_errors": 0, + "read_p95_ms": 14.131, + "writes": 16, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 29, + "reads": 8535, + "read_errors": 0, + "read_p95_ms": 6.899, + "writes": 20, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + }, + { + "s": 30, + "reads": 1, + "read_errors": 0, + "read_p95_ms": 4.022, + "writes": 0, + "write_errors": 0, + "raw_violations": 0, + "stale_reads": 0 + } + ], + "warmup_s": 3, + "write_errors": 0, + "write_interval_ms": 100, + "write_p50_ms": 6.344, + "write_p95_ms": 13.713, + "writers": 2, + "writes_ok": 522 +} \ No newline at end of file diff --git a/evidence/track1/safe-restart.stats.txt b/evidence/track1/safe-restart.stats.txt new file mode 100644 index 0000000..116b917 --- /dev/null +++ b/evidence/track1/safe-restart.stats.txt @@ -0,0 +1,81 @@ +mtusi-lab2-api-1;519.00%;16MiB / 1.858GiB +mtusi-lab2-postgres-1;8.28%;55.34MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;47.14%;10.98MiB / 1.858GiB +mtusi-lab2-valkey-1;18.30%;6.895MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;289.23%;9.754MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;292.53%;9.461MiB / 1.858GiB +mtusi-lab2-api-1;511.77%;12.45MiB / 1.858GiB +mtusi-lab2-postgres-1;1.98%;55.5MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;46.65%;11.21MiB / 1.858GiB +mtusi-lab2-valkey-1;18.50%;6.934MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;271.36%;10.48MiB / 1.858GiB +mtusi-lab2-api-1;490.69%;14.79MiB / 1.858GiB +mtusi-lab2-postgres-1;1.57%;55.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;54.07%;11.63MiB / 1.858GiB +mtusi-lab2-valkey-1;21.74%;6.914MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;288.33%;11.06MiB / 1.858GiB +mtusi-lab2-api-1;473.12%;14.32MiB / 1.858GiB +mtusi-lab2-postgres-1;2.01%;55.52MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;42.71%;11.21MiB / 1.858GiB +mtusi-lab2-valkey-1;18.06%;6.914MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;265.09%;9.617MiB / 1.858GiB +mtusi-lab2-api-1;483.35%;13.19MiB / 1.858GiB +mtusi-lab2-postgres-1;3.91%;55.53MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;53.77%;11.45MiB / 1.858GiB +mtusi-lab2-valkey-1;21.82%;6.938MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;279.91%;10.73MiB / 1.858GiB +mtusi-lab2-api-1;487.70%;15.17MiB / 1.858GiB +mtusi-lab2-postgres-1;1.62%;55.55MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;52.30%;8.973MiB / 1.858GiB +mtusi-lab2-valkey-1;20.55%;6.91MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;270.57%;11.56MiB / 1.858GiB +mtusi-lab2-api-1;386.47%;18.03MiB / 1.858GiB +mtusi-lab2-postgres-1;143.15%;71.62MiB / 1.858GiB +mtusi-lab2-valkey-1;16.43%;6.98MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;232.12%;10.68MiB / 1.858GiB +mtusi-lab2-api-1;394.36%;15.83MiB / 1.858GiB +mtusi-lab2-postgres-1;237.74%;72.59MiB / 1.858GiB +mtusi-lab2-valkey-1;25.40%;7.207MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;252.34%;12.03MiB / 1.858GiB +mtusi-lab2-api-1;388.04%;17.7MiB / 1.858GiB +mtusi-lab2-postgres-1;202.77%;72.62MiB / 1.858GiB +mtusi-lab2-valkey-1;20.21%;6.996MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;267.03%;12.41MiB / 1.858GiB +mtusi-lab2-api-1;359.32%;17.57MiB / 1.858GiB +mtusi-lab2-postgres-1;185.18%;72.47MiB / 1.858GiB +mtusi-lab2-valkey-1;17.84%;7.426MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;0.36%;3.348MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;249.73%;12.88MiB / 1.858GiB +mtusi-lab2-api-1;510.51%;17.27MiB / 1.858GiB +mtusi-lab2-postgres-1;2.09%;72.17MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;60.91%;4.852MiB / 1.858GiB +mtusi-lab2-valkey-1;23.73%;6.992MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;292.24%;13.95MiB / 1.858GiB +mtusi-lab2-api-1;519.51%;18.75MiB / 1.858GiB +mtusi-lab2-postgres-1;4.19%;72.41MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;50.39%;5.215MiB / 1.858GiB +mtusi-lab2-valkey-1;20.32%;7.316MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;276.44%;13.17MiB / 1.858GiB +mtusi-lab2-api-1;521.40%;14.58MiB / 1.858GiB +mtusi-lab2-postgres-1;1.72%;72.19MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;55.47%;5.988MiB / 1.858GiB +mtusi-lab2-valkey-1;22.76%;6.922MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;241.94%;13.61MiB / 1.858GiB +mtusi-lab2-api-1;503.58%;16.35MiB / 1.858GiB +mtusi-lab2-postgres-1;2.26%;72.21MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;57.22%;5.988MiB / 1.858GiB +mtusi-lab2-valkey-1;22.95%;6.91MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;290.71%;13.53MiB / 1.858GiB +mtusi-lab2-api-1;531.16%;18.71MiB / 1.858GiB +mtusi-lab2-postgres-1;2.28%;72.21MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;46.89%;6.289MiB / 1.858GiB +mtusi-lab2-valkey-1;19.03%;6.918MiB / 1.858GiB +mtusi-lab2-cachebench-run-4d5eacbbc0a2;235.98%;14.41MiB / 1.858GiB +mtusi-lab2-api-1;502.68%;15.24MiB / 1.858GiB +mtusi-lab2-postgres-1;2.65%;72.26MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;66.70%;6.863MiB / 1.858GiB +mtusi-lab2-valkey-1;27.72%;6.93MiB / 1.858GiB +mtusi-lab2-api-1;0.31%;15.03MiB / 1.858GiB +mtusi-lab2-postgres-1;2.92%;70.78MiB / 1.858GiB +mtusi-lab2-valkey-cache-1;1.13%;6.812MiB / 1.858GiB +mtusi-lab2-valkey-1;1.02%;7.105MiB / 1.858GiB diff --git a/evidence/track1/summary.md b/evidence/track1/summary.md new file mode 100644 index 0000000..a73ca91 --- /dev/null +++ b/evidence/track1/summary.md @@ -0,0 +1,112 @@ +## Трек 1: медианы по повторам + +| Режим | Повт. | Чтений/с | p50, мс | p95, мс | p99, мс | SQL страницы | SQL членство | SQL на чтение | Hit ratio | RAW писателя: нарушений / проверок | Stale reads: нарушений / проверок | Ошибки | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| off-d0 | 3 | 2267 | 12.03 | 28.45 | 39.55 | 68479 | 68479 | 2.0136 | — | 0 / 1358 | 0 / 204418 | 0 | +| naive-d0 | 3 | 2712 | 9.88 | 25.48 | 36.00 | 1087 | 0 | 0.0103 | 99.2% | 712 / 1379 | 128731 / 248013 | 0 | +| safe-d0 | 3 | 4631 | 5.89 | 14.45 | 20.18 | 477 | 0 | 0.0034 | 97.8% | 0 / 1417 | 0 / 428275 | 0 | +| naive-d20 | 3 | 4813 | 4.74 | 23.29 | 30.00 | 7684 | 0 | 0.0532 | 97.3% | 3 / 1282 | 13484 / 361325 | 0 | +| safe-d20 | 3 | 4456 | 5.33 | 23.45 | 29.76 | 407 | 0 | 0.0030 | 97.5% | 0 / 1344 | 0 / 398277 | 0 | + +CPU (среднее, 100% = 1 ядро) / RAM (максимум) по контейнерам за прогоны: + +| Режим | api | postgres | valkey (сессии) | valkey-cache | +|---|---|---|---|---| +| off-d0 | 347% / 49 MiB | 175% / 71 MiB | 18% / 7 MiB | 1% / 5 MiB | +| naive-d0 | 420% / 74 MiB | 8% / 71 MiB | 19% / 7 MiB | 36% / 6 MiB | +| safe-d0 | 456% / 18 MiB | 3% / 61 MiB | 19% / 7 MiB | 47% / 13 MiB | +| naive-d20 | 402% / 54 MiB | 13% / 72 MiB | 18% / 7 MiB | 35% / 7 MiB | +| safe-d20 | 412% / 60 MiB | 2% / 59 MiB | 17% / 7 MiB | 42% / 13 MiB | + +Каждый прогон по отдельности: + +- off-d0-r1: чтений 67564, p95 28.6 мс, SQL страницы 68042, RAW 0/452, stale reads 0/67404 +- off-d0-r2: чтений 68018, p95 28.5 мс, SQL страницы 68479, RAW 0/453, stale reads 0/67858 +- off-d0-r3: чтений 69316, p95 28.1 мс, SQL страницы 69764, RAW 0/453, stale reads 0/69156 +- naive-d0-r1: чтений 81347, p95 25.5 мс, SQL страницы 3535, RAW 6/456, stale reads 1369/81187 +- naive-d0-r2: чтений 60935, p95 31.3 мс, SQL страницы 588, RAW 354/444, stale reads 44661/60903 +- naive-d0-r3: чтений 105987, p95 18.1 мс, SQL страницы 1087, RAW 352/479, stale reads 82701/105923 +- safe-d0-r1: чтений 134337, p95 14.7 мс, SQL страницы 512, RAW 0/512, stale reads 0/134145 +- safe-d0-r2: чтений 138935, p95 14.4 мс, SQL страницы 477, RAW 0/466, stale reads 0/138775 +- safe-d0-r3: чтений 155515, p95 12.7 мс, SQL страницы 437, RAW 0/439, stale reads 0/155355 +- naive-d20-r1: чтений 68278, p95 34.8 мс, SQL страницы 6833, RAW 2/394, stale reads 3052/68150 +- naive-d20-r2: чтений 144383, p95 23.3 мс, SQL страницы 7684, RAW 0/442, stale reads 5673/144223 +- naive-d20-r3: чтений 149112, p95 22.5 мс, SQL страницы 7847, RAW 1/446, stale reads 4759/148952 +- safe-d20-r1: чтений 135917, p95 23.0 мс, SQL страницы 403, RAW 0/446, stale reads 0/135757 +- safe-d20-r2: чтений 133673, p95 23.4 мс, SQL страницы 407, RAW 0/450, stale reads 0/133513 +- safe-d20-r3: чтений 129167, p95 24.0 мс, SQL страницы 410, RAW 0/448, stale reads 0/129007 + +## safe-restart: таймлайн (кэш недоступен с 10-й по ~15-ю секунду) + +Итого: чтений 153522, ошибок чтения 0, ошибок записи 0, RAW 0/522, stale reads 0/153330, SQL страницы 34955. + +| с | чтений | ошибок чт. | p95, мс | записей | ошибок зап. | RAW нарушений | stale reads | +|---|---|---|---|---|---|---|---| +| 0 | 7692 | 0 | 7.9 | 18 | 0 | 0 | 0 | +| 1 | 5873 | 0 | 10.1 | 18 | 0 | 0 | 0 | +| 2 | 4776 | 0 | 12.5 | 17 | 0 | 0 | 0 | +| 3 | 3855 | 0 | 16.2 | 17 | 0 | 0 | 0 | +| 4 | 3092 | 0 | 19.2 | 17 | 0 | 0 | 0 | +| 5 | 4433 | 0 | 15.4 | 17 | 0 | 0 | 0 | +| 6 | 7001 | 0 | 8.3 | 18 | 0 | 0 | 0 | +| 7 | 5737 | 0 | 9.9 | 18 | 0 | 0 | 0 | +| 8 | 4475 | 0 | 13.9 | 17 | 0 | 0 | 0 | +| 9 | 3328 | 0 | 18.1 | 15 | 0 | 0 | 0 | +| 10 | 3464 | 0 | 17.3 | 18 | 0 | 0 | 0 | +| 11 | 4442 | 0 | 17.4 | 16 | 0 | 0 | 0 | +| 12 | 6309 | 0 | 8.6 | 18 | 0 | 0 | 0 | +| 13 | 5296 | 0 | 10.3 | 18 | 0 | 0 | 0 | +| 14 | 3808 | 0 | 15.5 | 17 | 0 | 0 | 0 | +| 15 | 3683 | 0 | 15.4 | 17 | 0 | 0 | 0 | +| 16 | 3717 | 0 | 15.2 | 17 | 0 | 0 | 0 | +| 17 | 6681 | 0 | 12.6 | 18 | 0 | 0 | 0 | +| 18 | 7216 | 0 | 7.6 | 18 | 0 | 0 | 0 | +| 19 | 4621 | 0 | 13.7 | 17 | 0 | 0 | 0 | +| 20 | 4284 | 0 | 13.2 | 18 | 0 | 0 | 0 | +| 21 | 4195 | 0 | 13.9 | 16 | 0 | 0 | 0 | +| 22 | 3757 | 0 | 15.4 | 18 | 0 | 0 | 0 | +| 23 | 8646 | 0 | 7.5 | 18 | 0 | 0 | 0 | +| 24 | 5886 | 0 | 10.1 | 18 | 0 | 0 | 0 | +| 25 | 5452 | 0 | 10.2 | 18 | 0 | 0 | 0 | +| 26 | 4641 | 0 | 12.3 | 16 | 0 | 0 | 0 | +| 27 | 4145 | 0 | 13.4 | 18 | 0 | 0 | 0 | +| 28 | 4481 | 0 | 14.1 | 16 | 0 | 0 | 0 | +| 29 | 8535 | 0 | 6.9 | 20 | 0 | 0 | 0 | +| 30 | 1 | 0 | 4.0 | 0 | 0 | 0 | 0 | + +## safe-pause: таймлайн (кэш недоступен с 10-й по ~15-ю секунду) + +Итого: чтений 160911, ошибок чтения 0, ошибок записи 0, RAW 0/464, stale reads 0/160751, SQL страницы 26942. + +| с | чтений | ошибок чт. | p95, мс | записей | ошибок зап. | RAW нарушений | stale reads | +|---|---|---|---|---|---|---|---| +| 0 | 9069 | 0 | 6.7 | 18 | 0 | 0 | 0 | +| 1 | 6724 | 0 | 8.5 | 18 | 0 | 0 | 0 | +| 2 | 5003 | 0 | 11.9 | 18 | 0 | 0 | 0 | +| 3 | 3886 | 0 | 15.4 | 18 | 0 | 0 | 0 | +| 4 | 3629 | 0 | 15.9 | 16 | 0 | 0 | 0 | +| 5 | 5095 | 0 | 15.1 | 18 | 0 | 0 | 0 | +| 6 | 7860 | 0 | 7.4 | 18 | 0 | 0 | 0 | +| 7 | 5522 | 0 | 10.6 | 18 | 0 | 0 | 0 | +| 8 | 4789 | 0 | 12.7 | 16 | 0 | 0 | 0 | +| 9 | 2238 | 0 | 16.4 | 12 | 0 | 0 | 0 | +| 10 | 4092 | 0 | 14.2 | 6 | 0 | 0 | 0 | +| 11 | 3922 | 0 | 14.9 | 6 | 0 | 0 | 0 | +| 12 | 3928 | 0 | 15.0 | 6 | 0 | 0 | 0 | +| 13 | 3471 | 0 | 17.4 | 6 | 0 | 0 | 0 | +| 14 | 3298 | 0 | 18.0 | 6 | 0 | 0 | 0 | +| 15 | 6880 | 0 | 8.4 | 16 | 0 | 0 | 0 | +| 16 | 6989 | 0 | 7.7 | 18 | 0 | 0 | 0 | +| 17 | 5469 | 0 | 10.0 | 18 | 0 | 0 | 0 | +| 18 | 5065 | 0 | 11.1 | 18 | 0 | 0 | 0 | +| 19 | 3488 | 0 | 17.2 | 16 | 0 | 0 | 0 | +| 20 | 4919 | 0 | 14.2 | 18 | 0 | 0 | 0 | +| 21 | 8928 | 0 | 5.8 | 18 | 0 | 0 | 0 | +| 22 | 6683 | 0 | 8.1 | 18 | 0 | 0 | 0 | +| 23 | 5425 | 0 | 10.1 | 18 | 0 | 0 | 0 | +| 24 | 4376 | 0 | 13.4 | 16 | 0 | 0 | 0 | +| 25 | 3907 | 0 | 14.8 | 18 | 0 | 0 | 0 | +| 26 | 7145 | 0 | 11.2 | 18 | 0 | 0 | 0 | +| 27 | 7825 | 0 | 6.9 | 18 | 0 | 0 | 0 | +| 28 | 6436 | 0 | 8.7 | 18 | 0 | 0 | 0 | +| 29 | 4850 | 0 | 11.5 | 18 | 0 | 0 | 0 | diff --git a/migrations/00001_create_users_table.sql b/migrations/00001_create_users_table.sql new file mode 100644 index 0000000..34e3184 --- /dev/null +++ b/migrations/00001_create_users_table.sql @@ -0,0 +1,22 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + username text NOT NULL, + display_name text NOT NULL, + -- Строка password KDF (Argon2id/scrypt) вместе с солью и параметрами; никогда не отдаётся в API. + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + + CONSTRAINT users_username_key UNIQUE (username), + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100 + AND btrim(display_name) <> ''), + CONSTRAINT users_password_hash_not_empty CHECK (password_hash <> '') +); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS users; +-- +goose StatementEnd diff --git a/migrations/00002_create_chats_table.sql b/migrations/00002_create_chats_table.sql new file mode 100644 index 0000000..7b5cdd4 --- /dev/null +++ b/migrations/00002_create_chats_table.sql @@ -0,0 +1,16 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE chats ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + title text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + + CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100 + AND btrim(title) <> '') +); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS chats; +-- +goose StatementEnd diff --git a/migrations/00003_create_chat_members_table.sql b/migrations/00003_create_chat_members_table.sql new file mode 100644 index 0000000..91aaf57 --- /dev/null +++ b/migrations/00003_create_chat_members_table.sql @@ -0,0 +1,16 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT, + + CONSTRAINT chat_members_pkey PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX chat_members_user_id_chat_id_idx ON chat_members (user_id, chat_id); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS chat_members; +-- +goose StatementEnd diff --git a/migrations/00004_create_messages_table.sql b/migrations/00004_create_messages_table.sql new file mode 100644 index 0000000..4466222 --- /dev/null +++ b/migrations/00004_create_messages_table.sql @@ -0,0 +1,25 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE messages ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + + -- Отправитель обязан быть участником этого чата: FK на пару из chat_members. + CONSTRAINT messages_chat_member_fkey FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members (chat_id, user_id) ON DELETE RESTRICT, + CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000) +); + +-- История чата с keyset-пагинацией: +-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4 +-- Индекс отдаёт страницу без полного scan и без сортировки. +CREATE INDEX messages_chat_id_created_at_id_idx ON messages (chat_id, created_at, id); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS messages; +-- +goose StatementEnd diff --git a/scripts/explain.sh b/scripts/explain.sh new file mode 100644 index 0000000..5333cb4 --- /dev/null +++ b/scripts/explain.sh @@ -0,0 +1,106 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +OUT=evidence/explain.txt +mkdir -p evidence + +psql() { docker compose --env-file .env exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 "$@"; } + +psql -q <<'SQL' +DO $$ +DECLARE + u uuid; + c uuid; + i int; +BEGIN + IF EXISTS (SELECT 1 FROM users WHERE username = 'explain_seed_user') THEN + RETURN; + END IF; + INSERT INTO users (username, display_name, password_hash) + VALUES ('explain_seed_user', 'EXPLAIN seed', '$argon2id$not-a-login') + RETURNING id INTO u; + FOR i IN 0..4 LOOP + INSERT INTO chats (title) VALUES ('explain_seed_' || i) RETURNING id INTO c; + INSERT INTO chat_members (chat_id, user_id) VALUES (c, u); + INSERT INTO messages (chat_id, sender_id, text, created_at) + SELECT c, u, 'synthetic message ' || g || ' ' || repeat('x', 40), + now() - interval '1 day' + g * interval '1 millisecond' + FROM generate_series(1, CASE WHEN i = 0 THEN 12000 ELSE 10000 END) AS g; + END LOOP; +END $$; +ANALYZE users; ANALYZE chats; ANALYZE chat_members; ANALYZE messages; +SQL + +{ + echo "# EXPLAIN (ANALYZE, BUFFERS) истории сообщений" + echo "date_utc: $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "postgres: $(psql -At -c 'SHOW server_version')" + psql -At -c "SELECT 'messages total: ' || count(*) FROM messages" + psql -At -c "SELECT 'target chat (explain_seed_0) messages: ' || count(*) FROM messages m JOIN chats c ON c.id = m.chat_id WHERE c.title = 'explain_seed_0'" + psql -At -c "SELECT 'indexes on messages: ' || string_agg(indexdef, '; ') FROM pg_indexes WHERE tablename = 'messages'" + echo + psql <<'SQL' +\pset pager off +SELECT id AS chat FROM chats WHERE title = 'explain_seed_0' \gset +SELECT id AS uid FROM users WHERE username = 'explain_seed_user' \gset +-- Курсор глубокой страницы: позиция 10 000-го сообщения целевого чата. +SELECT created_at AS ct, id AS cid FROM messages WHERE chat_id = :'chat' +ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset + +PREPARE member(uuid, uuid) AS +SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2); + +PREPARE first_page(uuid, int) AS +SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at +FROM messages m +WHERE m.chat_id = $1 +ORDER BY m.created_at, m.id +LIMIT $2; + +PREPARE next_page(uuid, timestamptz, uuid, int) AS +SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at +FROM messages m +WHERE m.chat_id = $1 + AND (m.created_at, m.id) > ($2, $3) +ORDER BY m.created_at, m.id +LIMIT $4; + +\echo '=== 1. Проверка членства (PK chat_members), generic plan' +SET plan_cache_mode = force_generic_plan; +EXPLAIN (ANALYZE, BUFFERS) EXECUTE member(:'chat', :'uid'); + +\echo '=== 2. Первая страница, limit 51 (50 + 1 для next_cursor), custom plan' +SET plan_cache_mode = force_custom_plan; +EXPLAIN (ANALYZE, BUFFERS) EXECUTE first_page(:'chat', 51); +\echo '=== 2g. Первая страница, generic plan (так её выполняет pgx после 5 повторов)' +SET plan_cache_mode = force_generic_plan; +EXPLAIN (ANALYZE, BUFFERS) EXECUTE first_page(:'chat', 51); + +\echo '=== 3. Глубокая страница после 10 000 сообщений, custom plan' +SET plan_cache_mode = force_custom_plan; +EXPLAIN (ANALYZE, BUFFERS) EXECUTE next_page(:'chat', :'ct', :'cid', 51); +\echo '=== 3g. Глубокая страница, generic plan: граница курсора остаётся в Index Cond' +SET plan_cache_mode = force_generic_plan; +EXPLAIN (ANALYZE, BUFFERS) EXECUTE next_page(:'chat', :'ct', :'cid', 51); + +\echo '=== 3x. Было до исправления: один SQL с «$2 IS NULL OR ...», generic plan — курсор в Filter' +PREPARE combined(uuid, timestamptz, uuid, int) AS +SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at +FROM messages m +WHERE m.chat_id = $1 + AND ($2::timestamptz IS NULL OR (m.created_at, m.id) > ($2, $3::uuid)) +ORDER BY m.created_at, m.id +LIMIT $4; +EXPLAIN (ANALYZE, BUFFERS) EXECUTE combined(:'chat', :'ct', :'cid', 51); + +\echo '=== 4. Контроль: та же глубокая страница через OFFSET 10000 (так делать нельзя)' +EXPLAIN (ANALYZE, BUFFERS) +SELECT m.id FROM messages m WHERE m.chat_id = :'chat' ORDER BY m.created_at, m.id OFFSET 10000 LIMIT 51; + +\echo '=== 5. Контроль: без индекса (enable_indexscan/bitmapscan off) — полный scan и сортировка' +SET enable_indexscan = off; SET enable_bitmapscan = off; SET enable_indexonlyscan = off; +SET plan_cache_mode = force_custom_plan; +EXPLAIN (ANALYZE, BUFFERS) EXECUTE next_page(:'chat', :'ct', :'cid', 51); +SQL +} > "$OUT" 2>&1 +echo "written $OUT" diff --git a/scripts/failures-tests.sh b/scripts/failures-tests.sh new file mode 100644 index 0000000..0ac9aff --- /dev/null +++ b/scripts/failures-tests.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/../app" + +E2E_BASE_URL="${1:-${E2E_BASE_URL:-http://localhost:8080}}" +export E2E_BASE_URL + +exec go test -count=1 -v -timeout 10m ./e2e/ diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100644 index 0000000..ebd3ba0 --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,48 @@ +#!/bin/sh +set -eu + +cd "$(dirname "$0")/.." +DIR=secrets +DB_USER="${POSTGRES_USER:-messenger}" +DB_NAME="${POSTGRES_DB:-messenger}" + +umask 077 +mkdir -p "$DIR" + +if [ ! -s "$DIR/postgres_password" ]; then + # hex, чтобы пароль не требовал URL-экранирования в DSN. + od -An -tx1 -N24 /dev/urandom | tr -d ' \n' > "$DIR/postgres_password" + echo "init-secrets: created $DIR/postgres_password" +fi + +if [ ! -s "$DIR/database_url" ]; then + pw="$(cat "$DIR/postgres_password")" + printf 'postgres://%s:%s@postgres:5432/%s?sslmode=disable' "$DB_USER" "$pw" "$DB_NAME" > "$DIR/database_url" + echo "init-secrets: created $DIR/database_url" +fi + +if [ ! -s "$DIR/valkey_password" ]; then + od -An -tx1 -N24 /dev/urandom | tr -d ' \n' > "$DIR/valkey_password" + echo "init-secrets: created $DIR/valkey_password" +fi + +if [ ! -s "$DIR/cache_url" ]; then + pw="$(cat "$DIR/valkey_password")" + printf 'redis://:%s@valkey:6379/0' "$pw" > "$DIR/cache_url" + echo "init-secrets: created $DIR/cache_url" +fi + +if [ ! -s "$DIR/valkey_cache_password" ]; then + od -An -tx1 -N24 /dev/urandom | tr -d ' +' > "$DIR/valkey_cache_password" + echo "init-secrets: created $DIR/valkey_cache_password" +fi + +if [ ! -s "$DIR/history_cache_url" ]; then + pw="$(cat "$DIR/valkey_cache_password")" + printf 'redis://:%s@valkey-cache:6379/0' "$pw" > "$DIR/history_cache_url" + echo "init-secrets: created $DIR/history_cache_url" +fi + +chmod 0700 "$DIR" +chmod 0644 "$DIR/postgres_password" "$DIR/database_url" "$DIR/valkey_password" "$DIR/cache_url" "$DIR/valkey_cache_password" "$DIR/history_cache_url" diff --git a/scripts/integration-tests.sh b/scripts/integration-tests.sh new file mode 100644 index 0000000..7fbc27e --- /dev/null +++ b/scripts/integration-tests.sh @@ -0,0 +1,14 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." + +env_value() { sed -n "s/^$1=//p" .env 2>/dev/null | tail -n 1; } +PG_PORT="${POSTGRES_PORT:-$(env_value POSTGRES_PORT)}" +CACHE_PORT="${VALKEY_CACHE_PORT:-$(env_value VALKEY_CACHE_PORT)}" + +TEST_DATABASE_URL="postgres://messenger:$(cat secrets/postgres_password)@127.0.0.1:${PG_PORT:-5432}/messenger?sslmode=disable" +TEST_HISTORY_CACHE_URL="redis://:$(cat secrets/valkey_cache_password)@127.0.0.1:${CACHE_PORT:-6380}/15" +export TEST_DATABASE_URL TEST_HISTORY_CACHE_URL + +cd app +exec go test -count=1 -v -run 'TestUsernameRace|TestCreateChatRollback|TestMessageRequiresMembership|TestReadAfterWrite|TestStampede|TestAccessChecked|TestCacheLoss|TestCacheDown' ./internal/store/db/ ./internal/cache/ diff --git a/scripts/migrations-check.sh b/scripts/migrations-check.sh new file mode 100644 index 0000000..cd24a00 --- /dev/null +++ b/scripts/migrations-check.sh @@ -0,0 +1,31 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +export MSYS_NO_PATHCONV=1 +OUT=evidence/migrations.txt +mkdir -p evidence + +main() { docker compose --env-file .env "$@"; } +fresh() { POSTGRES_PORT=55433 docker compose --env-file .env -p mtusi-lab2-fresh "$@"; } +counts='SELECT (SELECT count(*) FROM users) AS users, (SELECT count(*) FROM chats) AS chats, (SELECT count(*) FROM chat_members) AS members, (SELECT count(*) FROM messages) AS messages' + +{ + echo "# Миграции ($(date -u +%Y-%m-%dT%H:%M:%SZ))" + echo + echo "## 1. С нуля (проект mtusi-lab2-fresh, пустой volume)" + fresh up -d --wait postgres 2>&1 | tail -n 1 + docker volume ls --filter name=mtusi-lab2-fresh --format "volume: {{.Name}}" + fresh run --rm migrate 2>&1 | grep -E "OK|goose|no migrations" || true + fresh exec -T postgres psql -U messenger -d messenger -c '\dt' + fresh exec -T postgres psql -U messenger -d messenger -At -c "SELECT version_id, is_applied FROM goose_db_version ORDER BY id" + echo "### повторный migrate на том же свежем volume" + fresh run --rm migrate 2>&1 | grep -E "OK|goose|no migrations" || true + fresh down -v 2>&1 | tail -n 2 + + echo + echo "## 2. Повторный migrate на рабочем стенде (volume mtusi-lab2_pgdata сохраняется)" + echo "до: $(main exec -T postgres psql -U messenger -d messenger -At -F ' ' -c "$counts")" + main run --rm migrate 2>&1 | grep -E "OK|goose|no migrations" || true + echo "после: $(main exec -T postgres psql -U messenger -d messenger -At -F ' ' -c "$counts")" +} > "$OUT" 2>&1 +cat "$OUT" diff --git a/scripts/persistence-evidence.sh b/scripts/persistence-evidence.sh new file mode 100644 index 0000000..6167966 --- /dev/null +++ b/scripts/persistence-evidence.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +set -eu +cd "$(dirname "$0")/.." +OUT=evidence/persistence.txt +mkdir -p evidence + +PY=python3 +"$PY" -c 'import sys' >/dev/null 2>&1 || PY=python + +hook=scripts/restart.sh +case "$(uname -s)" in + MINGW* | MSYS* | CYGWIN*) hook=scripts/restart.cmd ;; +esac + +state() { + for s in api postgres valkey valkey-cache; do + id=$(docker compose --env-file .env ps -q "$s") + docker inspect -f "$s {{.State.Status}} started={{.State.StartedAt}} restarts={{.RestartCount}} mounts={{range .Mounts}}{{.Name}} {{end}}" "$id" + done +} + +{ + echo "# Persistence ($(date -u +%Y-%m-%dT%H:%M:%SZ)), hook: $hook -> scripts/restart.sh" + echo "## до" + state + echo "## тест" + "$PY" tests/resilience.py --mode persistence --action-script "$hook" 2>&1 + echo "## после" + state + echo "## volumes" + docker volume ls --filter name=mtusi-lab2_ --format '{{.Name}}' | xargs docker volume inspect -f '{{.Name}} created={{.CreatedAt}}' +} > "$OUT" +cat "$OUT" diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..103d444 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." + +compose() { docker compose --env-file .env "$@"; } + +compose stop api +compose restart postgres valkey valkey-cache +compose up -d --wait postgres valkey valkey-cache +compose up -d api diff --git a/scripts/track1.sh b/scripts/track1.sh new file mode 100644 index 0000000..f03b10f --- /dev/null +++ b/scripts/track1.sh @@ -0,0 +1,87 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +export MSYS_NO_PATHCONV=1 + +REPEATS="${REPEATS:-3}" +DURATION="${DURATION:-30s}" +READERS="${READERS:-32}" +WRITERS="${WRITERS:-2}" +OUT=evidence/track1 +mkdir -p "$OUT" + +compose() { docker compose --env-file .env "$@"; } +cache_cli() { + compose exec -T valkey-cache sh -c 'valkey-cli -a "$(cat /run/secrets/valkey_cache_password)" --no-auth-warning "$@"' -- "$@" +} + +api_mode() { # mode delay_ms + HISTORY_CACHE="$1" HISTORY_CACHE_FILL_DELAY_MS="$2" compose up -d --wait api >/dev/null 2>&1 + docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$(compose ps -q api)" | + grep -qx "HISTORY_CACHE=$1" || { echo "api не в режиме $1" >&2; exit 1; } +} + +bench() { # name, затем доп. флаги + name="$1"; shift + # CPU/RAM контейнеров во время прогона (сэмпл каждые ~2 с, включая прогрев). + (while :; do docker stats --no-stream --format '{{.Name}};{{.CPUPerc}};{{.MemUsage}}' 2>/dev/null; done) \ + > "$OUT/$name.stats.txt" & + sampler=$! + compose --profile bench run --rm -T cachebench \ + -base-url http://api:8080 -duration "$DURATION" -readers "$READERS" -writers "$WRITERS" \ + -db-url-file /run/secrets/database_url -cache-url-file /run/secrets/history_cache_url \ + -label "$name" -out "/evidence/track1/$name.json" "$@" + kill "$sampler" 2>/dev/null || true +} + +want() { [ -z "${ONLY:-}" ] || echo " $ONLY " | grep -q " $1 "; } + +{ + echo "date_utc: $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "commit: $(git rev-parse --short HEAD 2>/dev/null || echo n/a) (+ рабочее дерево)" + echo "docker: $(docker version --format '{{.Server.Version}}') ncpu=$(docker info --format '{{.NCPU}}') mem_bytes=$(docker info --format '{{.MemTotal}}')" + echo "limits: CPU/RAM-лимиты контейнерам не заданы; DB_MAX_CONNS=10, APP_MAX_INFLIGHT=64" + compose images --format '{{.Service}} {{.Repository}}:{{.Tag}}' 2>/dev/null || compose images + echo "profile: readers=$READERS writers=$WRITERS write_interval=100ms duration=$DURATION warmup=3s seed=150 repeats=$REPEATS" +} > "$OUT/env.txt" + +compose --profile bench build cachebench >/dev/null + +for mode in off naive safe; do + for delay in 0 20; do + [ "$mode" = off ] && [ "$delay" != 0 ] && continue + want "$mode-d$delay" || continue + api_mode "$mode" "$delay" + r=1 + while [ "$r" -le "$REPEATS" ]; do + cache_cli FLUSHALL >/dev/null + echo "== $mode delay=${delay}ms repeat $r" + bench "$mode-d$delay-r$r" + r=$((r + 1)) + done + done +done + +fault() { # name, action_down, action_up + name="$1" + api_mode safe 0 + cache_cli FLUSHALL >/dev/null + echo "== $name" + bench "$name" -duration 30s & + pid=$! + sleep 13 # 3 с прогрева + 10 с замера + compose "$2" valkey-cache >/dev/null 2>&1 + echo " $(date -u +%T) valkey-cache: $2" + sleep 5 + compose "$3" valkey-cache >/dev/null 2>&1 + echo " $(date -u +%T) valkey-cache: $3" + wait "$pid" +} +want safe-restart && fault safe-restart stop start +want safe-pause && fault safe-pause pause unpause + +api_mode safe 0 +PY=python3 +"$PY" -c 'import sys' >/dev/null 2>&1 || PY=python # на Windows python3 — заглушка Store +"$PY" scripts/track1_summary.py "$OUT" > "$OUT/summary.md" +cat "$OUT/summary.md" diff --git a/scripts/track1_summary.py b/scripts/track1_summary.py new file mode 100644 index 0000000..ecda82f --- /dev/null +++ b/scripts/track1_summary.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Сводка evidence/track1/*.json в Markdown: медиана по повторам и таймлайн отказов.""" +import json +import re +import statistics +import sys +from pathlib import Path + +sys.stdout.reconfigure(encoding='utf-8') + +out = Path(sys.argv[1] if len(sys.argv) > 1 else 'evidence/track1') +runs = {} +for f in sorted(out.glob('*.json')): + data = json.loads(f.read_text(encoding='utf-8')) + group = re.sub(r'-r\d+$', '', data['label']) + runs.setdefault(group, []).append(data) + + +def med(rows, key, sub=None): + vals = [(r.get(sub) or {}).get(key, 0) if sub else r.get(key, 0) for r in rows] + return statistics.median(vals) if vals else 0 + + +def hit_ratio(rows): + vals = [] + for r in rows: + c = r.get('cache') or {} + total = c.get('keyspace_hits', 0) + c.get('keyspace_misses', 0) + if total: + vals.append(c['keyspace_hits'] / total) + return '%.1f%%' % (100 * statistics.median(vals)) if vals else '—' + + +def resources(group): + """Средний CPU% и максимум RAM (MiB) по сервисам из *.stats.txt прогонов группы.""" + cpu, mem = {}, {} + for f in out.glob(group + '*.stats.txt'): + if re.sub(r'-r\d+$', '', f.name[:-len('.stats.txt')]) != group: + continue + for line in f.read_text(encoding='utf-8', errors='replace').splitlines(): + parts = line.split(';') + m = re.match(r'mtusi-lab2-(api|postgres|valkey|valkey-cache)-1$', parts[0]) if len(parts) == 3 else None + if not m: + continue + svc = m.group(1) + cpu.setdefault(svc, []).append(float(parts[1].rstrip('%') or 0)) + used = parts[2].split('/')[0].strip() + num = float(re.sub(r'[^0-9.]', '', used) or 0) + mib = num / 1024 if used.endswith('KiB') else num * 1024 if used.endswith('GiB') else num + mem[svc] = max(mem.get(svc, 0), mib) + return {s: (statistics.mean(v), mem.get(s, 0)) for s, v in cpu.items()} + + +def res_cell(group, svc): + r = resources(group).get(svc) + return '%.0f%% / %.0f MiB' % r if r else '—' + + +def ratio(rows, bad, total): + return '%d / %d' % (sum(r.get(bad, 0) for r in rows), sum(r.get(total, 0) for r in rows)) + + +order = ['off-d0', 'naive-d0', 'safe-d0', 'naive-d20', 'safe-d20'] +print('## Трек 1: медианы по повторам\n') +print('| Режим | Повт. | Чтений/с | p50, мс | p95, мс | p99, мс | SQL страницы | SQL членство | SQL на чтение | Hit ratio | RAW писателя: нарушений / проверок | Stale reads: нарушений / проверок | Ошибки |') +print('|---|---|---|---|---|---|---|---|---|---|---|---|---|') +for g in order: + rows = runs.get(g) + if not rows: + continue + errors = sum(r['read_errors'] + r['write_errors'] for r in rows) + print('| %s | %d | %.0f | %.2f | %.2f | %.2f | %.0f | %.0f | %.4f | %s | %s | %s | %d |' % ( + g, len(rows), med(rows, 'read_rps'), med(rows, 'read_p50_ms'), med(rows, 'read_p95_ms'), + med(rows, 'read_p99_ms'), med(rows, 'history_page_calls', 'sql'), med(rows, 'membership_calls', 'sql'), + med(rows, 'sql_read_path_per_read'), hit_ratio(rows), + ratio(rows, 'raw_violations', 'raw_checks'), ratio(rows, 'stale_reads', 'stale_checks'), errors)) + +print('\nCPU (среднее, 100% = 1 ядро) / RAM (максимум) по контейнерам за прогоны:\n') +print('| Режим | api | postgres | valkey (сессии) | valkey-cache |') +print('|---|---|---|---|---|') +for g in order: + if g in runs: + print('| %s | %s | %s | %s | %s |' % (g, res_cell(g, 'api'), res_cell(g, 'postgres'), + res_cell(g, 'valkey'), res_cell(g, 'valkey-cache'))) + +print('\nКаждый прогон по отдельности:\n') +for g in order: + for r in runs.get(g, []): + print('- %s: чтений %d, p95 %.1f мс, SQL страницы %d, RAW %d/%d, stale reads %d/%d' % ( + r['label'], r['reads_ok'], r['read_p95_ms'], (r.get('sql') or {}).get('history_page_calls', 0), + r['raw_violations'], r['raw_checks'], r.get('stale_reads', 0), r.get('stale_checks', 0))) + +for g in ('safe-restart', 'safe-pause'): + for r in runs.get(g, []): + print('\n## %s: таймлайн (кэш недоступен с 10-й по ~15-ю секунду)\n' % g) + print('Итого: чтений %d, ошибок чтения %d, ошибок записи %d, RAW %d/%d, stale reads %d/%d, SQL страницы %d.\n' % ( + r['reads_ok'], r['read_errors'], r['write_errors'], r['raw_violations'], r['raw_checks'], + r.get('stale_reads', 0), r.get('stale_checks', 0), (r.get('sql') or {}).get('history_page_calls', 0))) + print('| с | чтений | ошибок чт. | p95, мс | записей | ошибок зап. | RAW нарушений | stale reads |') + print('|---|---|---|---|---|---|---|---|') + for s in r['timeline']: + print('| %d | %d | %d | %.1f | %d | %d | %d | %d |' % ( + s['s'], s['reads'], s['read_errors'], s['read_p95_ms'], s['writes'], s['write_errors'], + s['raw_violations'], s.get('stale_reads', 0)))