diff --git a/.dockerignore b/.dockerignore index bc16e556..a4397ed5 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,20 +1,8 @@ -.git -.github -.env -.env.* -!.env.example -secrets -certs -volumes -data -backups -*.key -*.pem -*.p12 -*.pfx -*.jks -.venv -__pycache__ -node_modules -evidence -.DS_Store +* +!go.mod +!go.sum +!cmd/ +!cmd/** +!internal/ +!internal/** +!Dockerfile diff --git a/.env.example b/.env.example index 714c8076..e824eb8b 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,22 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# Synthetic isolated environment only. Never commit the local .env. APP_HOST=0.0.0.0 APP_PORT=8080 -APP_ENV=lab +DATABASE_URL=postgres://messenger:REPLACE_LOCALLY@127.0.0.1:5432/messenger?sslmode=disable +VALKEY_SHARDS=shard0=127.0.0.1:6379,shard1=127.0.0.1:6380 +VALKEY_COORDINATOR=shard0 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 -CACHE_URL_FILE=/run/secrets/cache_url +DEPENDENCY_POOL_SIZE=8 +DEPENDENCY_TIMEOUT_MS=1000 +REQUEST_TIMEOUT_SECONDS=3 +SHUTDOWN_TIMEOUT_SECONDS=5 +MAX_IN_FLIGHT=32 +REQUESTS_PER_SECOND=1000 +AUTH_RATE=100 +AUTH_SLOTS=4 +USER_RATE=100 +USER_SLOTS=8 +USER_WRITE_RATE=50 +USER_WRITE_SLOTS=4 +USER_AUTH_RATE=20 +USER_AUTH_SLOTS=2 +LOG_LEVEL=info diff --git a/.github/workflows/application.yml b/.github/workflows/application.yml new file mode 100644 index 00000000..b9ba4fc3 --- /dev/null +++ b/.github/workflows/application.yml @@ -0,0 +1,50 @@ +name: Application +on: [push, pull_request] +permissions: + contents: read +jobs: + verify: + runs-on: ubuntu-latest + timeout-minutes: 15 + services: + postgres: + image: postgres:17.6-alpine + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: isolated-ci-password + POSTGRES_DB: messenger + ports: ['5432:5432'] + options: >- + --health-cmd "pg_isready -U postgres -d messenger" + --health-interval 2s --health-timeout 2s --health-retries 20 + valkey0: + image: valkey/valkey:8.1.3-alpine + ports: ['6379:6379'] + valkey1: + image: valkey/valkey:8.1.3-alpine + ports: ['6380:6379'] + valkey2: + image: valkey/valkey:8.1.3-alpine + ports: ['6381:6379'] + env: + DATABASE_URL: postgres://postgres:isolated-ci-password@localhost:5432/messenger?sslmode=disable + TEST_DATABASE_URL: postgres://postgres:isolated-ci-password@localhost:5432/messenger?sslmode=disable + VALKEY_SHARDS: shard0=localhost:6379,shard1=localhost:6380,shard2=localhost:6381 + TEST_VALKEY_ADDRESS: localhost:6381 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.26.1' + - run: make check + - run: make vet + - uses: golangci/golangci-lint-action@v8 + with: + version: v2.12.2 + - run: make coverage + - run: make test-faults + - uses: actions/upload-artifact@v4 + if: always() + with: + name: coverage + path: coverage/ diff --git a/.gitignore b/.gitignore index b5a71896..b72f046b 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. +/server + +/key.json diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000..c00b9409 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,21 @@ +version: "2" +run: + timeout: 3m +linters: + default: none + enable: + - errcheck + - govet + - ineffassign + - staticcheck + - unused + - revive + - gocritic +formatters: + enable: + - gofmt + - goimports + settings: + goimports: + local-prefixes: + - gitea.privcloud.tech/vlad_marlo/mtusi2026lab2 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 00000000..e0aef649 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,44 @@ +# Архитектура лабораторной 2 + +Статус: реализовано, проверено локально и развёрнуто в Kubernetes dev / highload-applications. Требования: [SPEC](docs/SPEC.md), фактический статус: [PLAN](docs/PLAN.md). + +Сохраняются Fiber v2, Fx, Zap и транспортный реестр fielderr. Composition root связывает интерфейсы с реализациями. Controller декодирует HTTP и преобразует DTO, service валидирует значения и доступ, PostgreSQL store исполняет SQL и транзакции. Парольная криптография и кеширование имеют собственные интерфейсы потребителей. + +## Схема и транзакции + +`users`: UUID PK, username UNIQUE, display_name, password_hash, created_at. `chats`: UUID PK, title, created_at. `chat_members`: составной PK(chat_id,user_id), FK на users/chats. `messages`: UUID PK, chat_id/sender_id FK, text, created_at; индекс (chat_id,created_at,id). `sessions`: hash токена PK, user_id FK, expires_at. Создание чата и всех участников — одна транзакция; ограничение username обеспечивается БД, включая гонки. Вставки сообщений сериализуются на строке чата для монотонного времени в пределах чата. Чтение истории использует keyset и LIMIT, без OFFSET. + +PostgreSQL хранит источник истины. Кэш неизменяемых профилей пользователей допускает безопасное восстановление из БД; сессия проверяется по PostgreSQL при каждом запросе, поэтому logout не зависит от успешной инвалидации кэша. TTL ограничивает срок хранения профиля. История не кэшируется. + +## Admission и шарды + +Клиентское кольцо consistent hashing с виртуальными узлами распределяет пользовательские ключи и кэш между 2–3 самостоятельными Valkey. Это не Redis Cluster с его 16384 hash slots. Глобальный координатор лимитов имеет стабильный адрес и не перемещается при расширении кольца. Группы auth/read/write имеют независимые бюджеты. Слоты ограничивают одновременную работу, rate ограничивает частоту; lease освобождается при завершении и истекает после аварии. Недоступность limiter закрывает admission с ограниченной ошибкой. + +Topology изменяется через остановку admission и drain активных lease; после выдержки полного окна rate новое кольцо безопасно включается. Кэш прогревается по требованию: обязательные данные не перемещаются и не теряются. Это демонстрация шардирования, не высокая доступность: отказ единственного PostgreSQL или глобального координатора останавливает обязательный путь. + +## Go и зависимости + +Указатели на данные конфигурации, nullable значения и конкретные внутренние объекты инфраструктурного адаптера допустимы. Интерфейсы вводятся на границах поведения, прежде всего service/store/admission, а не для каждого поля. Все функции многострочные и документированы; HTTP-коды принадлежат transport. + + +## Результат аудита зависимостей + +Controller получает `service.Service`, `service.Authentication`, `admission.Distributed` и собственный интерфейс `Readiness`. Прямая зависимость от `*admission.Limiter` заменена. Business service получает `store.Interface`, `service.CursorCodec` и `service.ProfileCache`; authentication получает `service.Accounts` и `service.Passwords`. PostgreSQL/Valkey связываются только в `cmd/server`. + +Конкретные указатели `*fiber.App`, `*zap.Logger`, `*fielderr.Registry`, `*pgxpool.Pool`, `*redis.Client` остаются внутри соответствующих инфраструктурных адаптеров. Они не пересекают business service boundary. Nullable cursor и указатели на секции конфигурации являются представлением данных, интерфейсы им не требуются. + +Memory store и локальный limiter сохранены для независимых тестовых fixtures. Production Fx graph использует только PostgreSQL и Valkey. Публичная регистрация проходит через authentication и KDF. `UsersCreate` базового service остаётся операцией профильных fixtures; HTTP route не вызывает её напрямую. + +Основные SQL-запросы используют `pgx.StrictNamedArgs`; статические migration DDL не содержат значений пользователя и выполняются без параметров. Миграция embedded, не зависит от рабочего каталога контейнера. Все чтения rows закрываются и проверяют `rows.Err()`. + +Фактические проверки и эксплуатационные ограничения, включая process-local cursor key, приведены в [REPORT](REPORT.md). Указанные Go conventions проверяются formatter/lint и AST-тестом направления импортов; они не заменяют анализ ответственности компонентов. + +## Классификация ошибок + +PostgreSQL нормализует сетевые ошибки, разрыв соединения, deadline и SQLSTATE недоступности в `store.ErrUnavailable`, сохраняя исходную причину для `errors.Is`. `service.ErrUnavailable` — alias этой общей категории интерфейса хранилища; controller не импортирует драйвер или store. Это сохраняет классификацию и на пути проверки сессии, и в бизнес-операциях. HTTP-слой возвращает фиксированный 503/unavailable без деталей. Неизвестные ошибки SQL остаются 500; ограничения уникальности и отсутствие записи сохраняют прежнее отображение. + +## Развёртывание + +[Helm chart](charts/messenger) — единственный источник ресурсов стенда. Values задают образ, API-конфигурацию, ресурсы и число шардов. Изменение конфигурации меняет checksum pod template и вызывает rollout API. Namespace изолирует лабораторную; имена StatefulSet и PVC стабильны. Credentials создаются отдельно и передаются по именам Secret, без записи паролей в Helm values. + +Смена кольца выполняется командой `make reshard` через Helm upgrade с остановленным API и ожиданием 31 секунды. Runtime topology guard защищает от несовпадающих колец; chart дополнительно запрещает изменение topology при работающем API. Подробности и порядок переноса существующих ресурсов: [ADR-0002](docs/decisions/0002-helm.md). diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..5a479560 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,16 @@ +FROM golang:1.26.1-alpine3.23 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server + +FROM scratch AS runtime +COPY --from=build /out/server /server +USER 65532:65532 +ENV APP_HOST=0.0.0.0 APP_PORT=8080 GOMEMLIMIT=160MiB +EXPOSE 8080 +STOPSIGNAL SIGTERM +HEALTHCHECK --interval=5s --timeout=3s --start-period=3s --retries=3 CMD ["/server", "healthcheck"] +ENTRYPOINT ["/server"] diff --git a/Makefile b/Makefile index 9ecb223e..cf02b534 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) .PHONY: help check validate test load test-persistence help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "init/deploy/port-forward: Helm stand; chart-check: Helm lint; reshard SHARDS=2|3; test/test-persistence: API; coverage: Go; research: SQL; check/validate: contract" check: $(PYTHON) scripts/check_contract.py @@ -24,3 +24,60 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +GO ?= go +.PHONY: build test-student coverage vet lint fmt research +build: + $(GO) build -trimpath -o bin/server ./cmd/server +test-student: + $(GO) test -race ./... +coverage: + GO="$(GO)" scripts/coverage.sh +vet: + $(GO) vet ./... +lint: + golangci-lint run ./... +fmt: + golangci-lint fmt +research: + scripts/research.sh + +REGISTRY ?= asisti.registry.twcstorage.ru +IMAGE := $(REGISTRY)/mtusi2026lab2 +IMAGE_TAG ?= dev-$(shell date -u +%Y%m%d%H%M%S) +PLATFORM ?= linux/amd64 +REGISTRY_USER ?= token +REGISTRY_TOKEN_FILE ?= $(HOME)/.secrets/twc-registry-token +KUBE_CONTEXT ?= dev +NAMESPACE ?= highload-applications +RELEASE ?= lab2 +CHART := charts/messenger +VALUES ?= $(CHART)/values.yaml +HELM_ARGS := --kube-context "$(KUBE_CONTEXT)" -n "$(NAMESPACE)" +export KUBE_CONTEXT NAMESPACE RELEASE REGISTRY REGISTRY_USER REGISTRY_TOKEN_FILE + +.PHONY: registry-login build-push init deploy chart-check reload port-forward ready reshard +registry-login: + docker login "$(REGISTRY)" --username "$(REGISTRY_USER)" --password-stdin < "$(REGISTRY_TOKEN_FILE)" +build-push: registry-login + docker buildx build --platform "$(PLATFORM)" --target runtime --tag "$(IMAGE):$(IMAGE_TAG)" --metadata-file evidence/image-build.json --push . +init: + scripts/init-secrets.sh +chart-check: + helm lint $(CHART) -f "$(VALUES)" + helm template "$(RELEASE)" $(CHART) -n "$(NAMESPACE)" -f "$(VALUES)" > /dev/null +deploy: + helm upgrade --install "$(RELEASE)" $(CHART) $(HELM_ARGS) --create-namespace -f "$(VALUES)" $(if $(IMAGE_DIGEST),--set-string image.digest=$(IMAGE_DIGEST),) --wait --timeout 180s +reload: + kubectl --context "$(KUBE_CONTEXT)" -n "$(NAMESPACE)" rollout restart deployment/api + kubectl --context "$(KUBE_CONTEXT)" -n "$(NAMESPACE)" rollout status deployment/api --timeout=180s +port-forward: + scripts/port-forward.sh +ready: + @for attempt in $$(seq 1 60); do curl --fail --silent --max-time 1 "$(BASE_URL)/health/ready" >/dev/null && exit 0; sleep 1; done; echo 'API readiness timeout' >&2; exit 1 +reshard: + SHARDS="$(SHARDS)" scripts/scale-shards.sh + +.PHONY: test-faults +test-faults: + scripts/test-faults.sh diff --git a/REPORT.md b/REPORT.md index e42f2b05..299a4bd1 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,107 @@ -# Отчёт — лабораторная 2 +# Лабораторная 2: хранение, сессии и шардирование -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +## Реализация -## Запуск из чистого clone +Возможности lab1 перенесены на PostgreSQL: пользователи, чаты, участники, сообщения и сессии сохраняются после перезапуска. Пароли обрабатываются Argon2id; Basic используется при входе, Bearer — для остальных операций. Сессия имеет фиксированный TTL и немедленно отзывается при logout. Valkey хранит кэш профилей и состояние rate limiter: общий и пользовательский лимиты, группы auth/read/write, слоты одновременного выполнения. -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Пользовательские ключи распределяются consistent hashing между тремя Valkey. Глобальные ограничения проверяет `shard0`. Это клиентское шардирование самостоятельных узлов, а не Redis Cluster. Controller, service и store связаны интерфейсами через Fx. Подробности: [ARCHITECTURE](ARCHITECTURE.md), требования: [SPEC](docs/SPEC.md). -## Архитектура и решения +Целевой объём: уровни 3 и 4, исследовательский трек 2 «План запроса и восстановление». Основной стенд — Kubernetes; допустимость замены Compose/Swarm преподавателем пока не подтверждена. -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +## Запуск -## Доказательства критериев +Нужны Helm, kubectl, Docker buildx, curl, jq и openssl. Для публичных проверок задания дополнительно нужен Python 3.9+. Для тестов Go — toolchain из `go.mod` и golangci-lint. Контекст по умолчанию `dev`, namespace `highload-applications`, Helm release `lab2`. Namespace общий с другими лабораторными; этот чарт управляет только ресурсами lab2. -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Все параметры стенда находятся в [values.yaml](charts/messenger/values.yaml): опубликованный образ по digest, количество шардов, ресурсы, размеры дисков и окружение API. PostgreSQL — 17.6-alpine, Valkey — 8.1.3-alpine. По умолчанию используется default StorageClass; другой класс нужно задать перед первой установкой. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +```sh +make init # namespace и секреты; пароль БД сохраняется, pull-secret обновляется +make deploy # установка или обновление Helm release +make port-forward # держать терминал открытым; localhost:8080 +``` -## Эксперименты и отказы +Registry — `asisti.registry.twcstorage.ru/mtusi2026lab2`. `make init` читает токен из `~/.secrets/twc-registry-token`, обновляет `registry-pull` и создаёт случайный пароль PostgreSQL только при отсутствии Secret БД. Секреты не входят в chart, values или Git. Chart использует их по имени. PVC сохраняются при рестарте и upgrade. -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Для публикации изменённого приложения: -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +```sh +make build-push +``` -## Ограничения и следующие шаги +Из `evidence/image-build.json` перенести значение `containerimage.digest` в `image.digest` файла values, затем выполнить `make deploy`. Для другого окружения: `make deploy VALUES=path/to/values.yaml KUBE_CONTEXT=... NAMESPACE=...`. Для временного выбора образа допускается `IMAGE_DIGEST=sha256:...`; следующий deploy снова использует digest из values. -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Изменение числа шардов требует остановки API: + +```sh +make reshard SHARDS=2 # или 3; простой включает ожидание lease 31 секунду +``` + +После успешной команды изменить `valkey.shards` в values. Обычный upgrade с работающим API отклоняет смену кольца. При ошибке reshard API остаётся остановленным; исправить причину и повторить команду. Если API было несколько реплик, задать `API_REPLICAS` при reshard. + +## Проверки + +Во втором терминале: + +```sh +make ready +make check +make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make chart-check +``` + +Persistence перезапускает API, PostgreSQL и все Valkey, затем читает прежние данные с прежней сессией. Туннель автоматически переподключается. Доступ к API открыт только на loopback; внешнего ingress нет. + +Go-проверки: `make vet`, `make lint`, `make test-student`. Полная проверка `make coverage` требует `DATABASE_URL`, `VALKEY_SHARDS`, `TEST_DATABASE_URL`, `TEST_VALKEY_ADDRESS`, указывающих на **изолированные тестовые** зависимости. Она запускает race, интеграционные тесты, настоящий сервер, smoke и SIGTERM; shell/awk объединяют профили и проверяют ≥90% statements отдельно в каждом исполняемом Go-файле. CI создаёт зависимости автоматически. Без TEST-переменных интеграционные тесты пропускаются. + +Проверки после перехода на Helm: [adoption и upgrade](evidence/helm-deployment.txt), [smoke](evidence/helm-smoke.txt), [persistence](evidence/helm-persistence.txt), [coverage](evidence/helm-coverage-per-file.json). Более ранние измерения и их область действия перечислены в [evidence/README](evidence/README.md). Удалённый CI не подтверждён; актуальная публикация и PR указаны ниже. + +## SQL-эксперимент + +```sh +make research +``` + +Команда создаёт отдельный временный PostgreSQL в Docker, применяет миграцию приложения и запускает [SQL-сценарий](student-tests/research.sql). Профиль: 100 000 сообщений, распределение по чатам 90% / 9% / 1%, два индекса — `chat_id` и `(chat_id,created_at,id)`. Для каждого выполняются три поздних keyset-чтения и три вставки 1000 строк с rollback. Затем полный логический dump восстанавливается в новую БД; сверяются количество, checksum сообщений и выборка записей. После проверки контейнер удаляется. + +Гипотеза: составной индекс ускоряет поздние страницы за счёт дополнительной работы при записи. Планы, время операций, ограничения ресурсов, контрольные суммы исходников и результат восстановления: [raw results](evidence/sql-research-helm.txt). Более раннее измерение с агрегированными данными: [sql-research-domain.json](evidence/sql-research-domain.json). Новый прогон также подтвердил выигрыш чтения. Диапазоны времени вставки перекрываются; трёх повторов недостаточно для вывода об устойчивом росте стоимости записи. + +Эксперимент синтетический, на одном Docker-хосте, без конкурентных записей. Восстановление в другую БД того же instance подтверждает логический backup/restore; оно не проверяет потерю узла или PITR. Данные после момента dump в таком backup отсутствуют. + +## Ограничения + +- Один PostgreSQL и глобальный координатор — точки отказа; репликация и автоматический failover не реализованы. При недоступности limiter новые запросы отклоняются. +- Расширение кольца требует простоя API. Обязательные данные остаются в PostgreSQL, кэш прогревается заново. +- Cursor подписан ключом процесса: после рестарта обход страниц начинается заново. Данные и действующие сессии сохраняются. +- Истёкшие сессии отвергаются запросом к БД, но фоновая очистка строк ещё не реализована. +- PVC на `microk8s-hostpath` обеспечивает сохранность при рестарте pod; он не заменяет резервную копию. + +Версии Go и зависимостей закреплены в `go.mod`, `go.sum` и Dockerfile. Источники решений: [ADR-0001](docs/decisions/0001-postgres-sessions-shards.md), [ADR-0002](docs/decisions/0002-helm.md). При разработке использован Codex. Автор: Агапов Владислав, БПИ2303; PR №52 указан ниже. + +## Репозиторий Gitea + +Решение перенесено 2026-10-15 в `ssh://git@gitea.privcloud.tech:2222/vlad_marlo/mtusi2026lab2.git`. Go-модуль и imports обновлены под новый адрес. [Проверки переноса](evidence/gitea-transfer-tests.txt) относятся к новой рабочей копии; прежние измерения и опубликованный образ относятся к снимку от 2026-10-07. Повторное развёртывание, новый image build и Git push при переносе не выполнялись. + +## Исправление классификации отказов — 2026-10-16 + +В PostgreSQL-адаптере недоступность соединения и timeout выделены в отдельную категорию. HTTP возвращает `503 unavailable` с безопасным сообщением, включая отказ на этапе проверки сессии. Неожиданные ошибки SQL сохраняют `500 internal_error`. + +```sh +make test-faults +``` + +Сценарий воспроизводится из отдельного clone с Docker, curl, jq, rg, OpenSSL и shasum. Он создаёт собственные PostgreSQL 17.6 и Valkey 8.1.3, собирает API из рабочего дерева, проверяет реальные `stop` и `pause` каждого backend и удаляет временные ресурсы. Ни существующие Docker-контейнеры, ни dev-кластер не используются. В начале вывода сохраняются базовая Git-ревизия и SHA-256 исходников: проверенный снимок включает ещё не закоммиченные изменения. + +[Результат](evidence/fault-regression.txt): все четыре сценария прошли. История с действующей сессией возвращала 503 за 0.002–0.508 с; зависание ограничено timeout 500 мс и внешним HTTP deadline 3 с. Проверены отсутствие анонимного доступа и обхода через X-User-Id/повреждённый/неизвестный Bearer, безопасный error envelope, liveness/readiness. После каждого восстановления исходная сессия читает то же сообщение без повторного входа. При отказе Valkey admission отклоняет запрос до аутентификации, поэтому анонимный запрос тоже получает 503, а не данные. + +Свежие [race/integration/coverage](evidence/fault-coverage.txt), [покрытие по файлам](evidence/fault-coverage-per-file.json), [lint](evidence/fault-lint.txt), [vet](evidence/fault-vet.txt) и [contract check](evidence/fault-contract.txt) прошли. Все 57 исполняемых Go-файлов имеют покрытие ≥90%. Fault-сценарий добавлен в application CI; удалённый runner этим локальным прогоном не проверяется. Кластерный образ в рамках этого исправления не обновлялся. + +Работа сдаётся в [PR №52](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/52), ветка `main` → `master`, автор Агапов Владислав, БПИ2303. + +## Timeweb и повторное развёртывание — 2026-10-16 + +Релиз `lab2` удалён через Helm и установлен заново в `dev / highload-applications`. Применён образ кода `87e1e5d` из Timeweb, digest закреплён в [values](charts/messenger/values.yaml); [метаданные сборки](evidence/timeweb-image-build.json), [проверка registry](evidence/timeweb-image-inspect.txt), [установка](evidence/timeweb-reinstall.txt). Используется Secret `registry-pull`; пароль БД не менялся. Другие releases не переустанавливались. + +Четыре PVC сохранили UID и привязку к прежним PV ([до](evidence/timeweb-pvc-before.txt), [после](evidence/timeweb-pvc-after.txt)). До запуска новых тестов совпали количества пользователей/чатов/сообщений: 36/12/18 ([до](evidence/timeweb-counts-before.txt), [после](evidence/timeweb-counts-after.txt)). Это проверка количества, не полная сверка содержимого БД. Полный цикл HTTP проверяется отдельно: [smoke](evidence/timeweb-smoke.txt), [persistence](evidence/timeweb-persistence.txt). + +[План защиты на 9 минут 30 секунд](docs/DEFENSE.md) содержит порядок демонстрации, команды и ограничения результатов. Эксперименты SQL и fault-проверки готовятся заранее, чтобы уложиться в десятиминутный лимит. diff --git a/charts/messenger/Chart.yaml b/charts/messenger/Chart.yaml new file mode 100644 index 00000000..14ffef69 --- /dev/null +++ b/charts/messenger/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: messenger +description: Учебный мессенджер с PostgreSQL и шардированным Valkey +version: 0.1.0 +appVersion: lab2 +type: application diff --git a/charts/messenger/templates/_helpers.tpl b/charts/messenger/templates/_helpers.tpl new file mode 100644 index 00000000..2fcf3714 --- /dev/null +++ b/charts/messenger/templates/_helpers.tpl @@ -0,0 +1,7 @@ +{{- define "messenger.shards" -}} +{{- $nodes := list -}} +{{- range $i := until (int .Values.valkey.shards) -}} +{{- $nodes = append $nodes (printf "shard%d=valkey-%d.valkey:6379" $i $i) -}} +{{- end -}} +{{- join "," $nodes -}} +{{- end -}} diff --git a/charts/messenger/templates/api.yaml b/charts/messenger/templates/api.yaml new file mode 100644 index 00000000..594185b8 --- /dev/null +++ b/charts/messenger/templates/api.yaml @@ -0,0 +1,88 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: messenger-config + namespace: {{ .Release.Namespace }} +data: + APP_PORT: '8080' + VALKEY_COORDINATOR: shard0 + VALKEY_SHARDS: {{ include "messenger.shards" . | quote }} +{{- range $key, $value := .Values.api.env }} + {{ $key }}: {{ $value | quote }} +{{- end }} +--- +apiVersion: v1 +kind: Service +metadata: + name: api + namespace: {{ .Release.Namespace }} +spec: + selector: + app: api + ports: + - port: 8080 + targetPort: 8080 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: api + namespace: {{ .Release.Namespace }} +spec: + replicas: {{ .Values.api.replicas }} + selector: + matchLabels: + app: api + template: + metadata: + annotations: + checksum/config: {{ printf "%s%s" (include "messenger.shards" .) (toJson .Values.api.env) | sha256sum }} + labels: + app: api + spec: + imagePullSecrets: + - name: {{ .Values.imagePullSecret }} + terminationGracePeriodSeconds: 10 + securityContext: + runAsNonRoot: true + runAsUser: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: api + image: "{{ .Values.image.repository }}@{{ .Values.image.digest }}" + imagePullPolicy: IfNotPresent + ports: + - containerPort: 8080 + envFrom: + - configMapRef: + name: messenger-config + env: + - name: DATABASE_URL + valueFrom: + secretKeyRef: + name: {{ .Values.databaseSecret }} + key: database-url + resources: + {{- toYaml .Values.api.resources | nindent 12 }} + startupProbe: + httpGet: + path: /health/ready + port: 8080 + periodSeconds: 2 + failureThreshold: 30 + readinessProbe: + httpGet: + path: /health/ready + port: 8080 + periodSeconds: 2 + livenessProbe: + httpGet: + path: /health/live + port: 8080 + periodSeconds: 5 + securityContext: + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + capabilities: + drop: [ALL] diff --git a/charts/messenger/templates/guard.yaml b/charts/messenger/templates/guard.yaml new file mode 100644 index 00000000..313b843e --- /dev/null +++ b/charts/messenger/templates/guard.yaml @@ -0,0 +1,7 @@ +{{- $live := lookup "v1" "ConfigMap" .Release.Namespace "messenger-config" -}} +{{- if and $live (ne (index $live.data "VALKEY_SHARDS") (include "messenger.shards" .)) -}} +{{- $api := lookup "apps/v1" "Deployment" .Release.Namespace "api" -}} +{{- if or (gt (int .Values.api.replicas) 0) (and $api (gt (int $api.spec.replicas) 0)) -}} +{{- fail "Changing shards requires drained API: use make reshard SHARDS=2 or SHARDS=3" -}} +{{- end -}} +{{- end -}} diff --git a/charts/messenger/templates/network-policy.yaml b/charts/messenger/templates/network-policy.yaml new file mode 100644 index 00000000..433486ac --- /dev/null +++ b/charts/messenger/templates/network-policy.yaml @@ -0,0 +1,22 @@ +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: private-databases + namespace: {{ .Release.Namespace }} +spec: + podSelector: + matchExpressions: + - key: app + operator: In + values: [postgres, valkey] + policyTypes: [Ingress] + ingress: + - from: + - podSelector: + matchLabels: + app: api + ports: + - protocol: TCP + port: 5432 + - protocol: TCP + port: 6379 diff --git a/charts/messenger/templates/postgres.yaml b/charts/messenger/templates/postgres.yaml new file mode 100644 index 00000000..8d8704a2 --- /dev/null +++ b/charts/messenger/templates/postgres.yaml @@ -0,0 +1,66 @@ +apiVersion: v1 +kind: Service +metadata: + name: postgres + namespace: {{ .Release.Namespace }} +spec: + selector: + app: postgres + ports: + - port: 5432 + targetPort: 5432 +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: postgres + namespace: {{ .Release.Namespace }} +spec: + serviceName: postgres + replicas: 1 + selector: + matchLabels: + app: postgres + template: + metadata: + labels: + app: postgres + spec: + terminationGracePeriodSeconds: 30 + containers: + - name: postgres + image: {{ .Values.postgres.image | quote }} + ports: + - containerPort: 5432 + env: + - name: POSTGRES_DB + value: messenger + - name: POSTGRES_USER + value: messenger + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: {{ .Values.databaseSecret }} + key: postgres-password + - name: PGDATA + value: /var/lib/postgresql/data/pgdata + resources: + {{- toYaml .Values.postgres.resources | nindent 12 }} + readinessProbe: + exec: + command: [pg_isready, -U, messenger, -d, messenger] + initialDelaySeconds: 3 + volumeMounts: + - name: data + mountPath: /var/lib/postgresql/data + volumeClaimTemplates: + - metadata: + name: data + spec: +{{- if .Values.storageClass }} + storageClassName: {{ .Values.storageClass | quote }} +{{- end }} + accessModes: [ReadWriteOnce] + resources: + requests: + storage: {{ .Values.postgres.storage }} diff --git a/charts/messenger/templates/valkey.yaml b/charts/messenger/templates/valkey.yaml new file mode 100644 index 00000000..5c996cc7 --- /dev/null +++ b/charts/messenger/templates/valkey.yaml @@ -0,0 +1,57 @@ +apiVersion: v1 +kind: Service +metadata: + name: valkey + namespace: {{ .Release.Namespace }} +spec: + clusterIP: None + selector: + app: valkey + ports: + - port: 6379 + targetPort: 6379 +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: valkey + namespace: {{ .Release.Namespace }} +spec: + serviceName: valkey + replicas: {{ .Values.valkey.shards }} + podManagementPolicy: Parallel + selector: + matchLabels: + app: valkey + template: + metadata: + labels: + app: valkey + spec: + terminationGracePeriodSeconds: 30 + containers: + - name: valkey + image: {{ .Values.valkey.image | quote }} + args: [valkey-server, --appendonly, 'yes', --appendfsync, always, --maxmemory, {{ .Values.valkey.maxmemory | quote }}, --maxmemory-policy, noeviction] + ports: + - containerPort: 6379 + resources: + {{- toYaml .Values.valkey.resources | nindent 12 }} + readinessProbe: + exec: + command: [valkey-cli, ping] + initialDelaySeconds: 2 + volumeMounts: + - name: data + mountPath: /data + volumeClaimTemplates: + - metadata: + name: data + spec: +{{- if .Values.storageClass }} + storageClassName: {{ .Values.storageClass | quote }} +{{- end }} + accessModes: [ReadWriteOnce] + resources: + requests: + storage: {{ .Values.valkey.storage }} diff --git a/charts/messenger/values.schema.json b/charts/messenger/values.schema.json new file mode 100644 index 00000000..3640ffe9 --- /dev/null +++ b/charts/messenger/values.schema.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema#", + "type": "object", + "properties": { + "valkey": {"type": "object", "properties": {"shards": {"type": "integer", "minimum": 2, "maximum": 3}}}, + "api": {"type": "object", "properties": {"replicas": {"type": "integer", "minimum": 0}}}, + "image": {"type": "object", "properties": {"digest": {"type": "string", "pattern": "^sha256:[a-f0-9]{64}$"}}} + } +} diff --git a/charts/messenger/values.yaml b/charts/messenger/values.yaml new file mode 100644 index 00000000..79800180 --- /dev/null +++ b/charts/messenger/values.yaml @@ -0,0 +1,34 @@ +# Ресурсы lab2 в общем namespace. Секреты создаются через make init. +image: + repository: asisti.registry.twcstorage.ru/mtusi2026lab2 + digest: sha256:3f19c9feb306a88044cc46b25d99592d48f04c21eba477d59676486277b2956c +imagePullSecret: registry-pull +databaseSecret: messenger-secrets +api: + replicas: 1 + resources: + requests: {cpu: 250m, memory: 128Mi} + limits: {cpu: '1', memory: 256Mi} + env: + SESSION_TTL_SECONDS: '3600' + DEPENDENCY_TIMEOUT_MS: '1000' + DEPENDENCY_POOL_SIZE: '8' + REQUEST_TIMEOUT_SECONDS: '3' + SHUTDOWN_TIMEOUT_SECONDS: '5' + GOMEMLIMIT: 160MiB +postgres: + image: postgres:17.6-alpine + storage: 2Gi + resources: + requests: {cpu: 250m, memory: 256Mi} + limits: {cpu: '1', memory: 512Mi} +valkey: + image: valkey/valkey:8.1.3-alpine + shards: 3 + storage: 1Gi + maxmemory: 64mb + resources: + requests: {cpu: 100m, memory: 96Mi} + limits: {cpu: 500m, memory: 128Mi} +# Пустое значение использует default StorageClass. Задать до первой установки. +storageClass: '' diff --git a/cmd/server/app.go b/cmd/server/app.go new file mode 100644 index 00000000..d04c8df3 --- /dev/null +++ b/cmd/server/app.go @@ -0,0 +1,97 @@ +package main + +import ( + "time" + + "go.uber.org/fx" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/controller" + fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/controller/http/fiber" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/password" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service/production" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store/postgres" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/valkey" +) + +const applicationStopTimeout = 9 * time.Second + +// CreateApp defines the dependency graph and Fx lifecycle for the lab2 server. +// Constructors do not open sockets; controller.RunControllerFx registers startup +// and shutdown hooks. The outer stop deadline bounds all component cleanup. +func CreateApp() fx.Option { + return fx.Options( + fx.StopTimeout(applicationStopTimeout), + fx.Supply(fx.Annotate(password.Hasher{}, fx.As(new(service.Passwords)))), + fx.Provide( + config.New, + config.NewPersistence, + newDatabase, + newValkey, + newAuthentication, + fx.Annotate(newReadiness, fx.As(new(fiberctrl.Readiness))), + httpConfig, + + loggerConfig, + newLogger, + fx.Annotate(newAdmissionLimiter, fx.As(new(admission.Distributed))), + fiberctrl.NewErrorRegistry, + fx.Annotate(databaseStore, fx.As(new(store.Interface))), + fx.Annotate(databaseAccounts, fx.As(new(service.Accounts))), + fx.Annotate(profileCache, fx.As(new(service.ProfileCache))), + fx.Annotate(cursor.New, fx.As(new(service.CursorCodec))), + fx.Annotate(production.NewCached, fx.As(new(service.Service))), + fx.Annotate(fiberctrl.New, fx.As(new(controller.Controller))), + ), + fx.WithLogger(newFxLogger), + fx.Invoke(controller.RunControllerFx), + ) +} + +// httpConfig provides the HTTP configuration section to Fx. +func httpConfig(cfg *config.Config) *config.Controller { + return cfg.HTTP +} + +// loggerConfig provides the logging configuration section to Fx. +func loggerConfig(cfg *config.Config) *config.Logger { + return cfg.Logger +} + +// newAdmissionLimiter translates configured bounds into separate shared policy budgets. +func newAdmissionLimiter(cfg *config.Controller, client *valkey.Client) (*valkey.Limiter, error) { + global := valkey.Budget{Rate: cfg.Admission.RequestsPerSecond, Slots: cfg.Admission.MaxInFlight} + return valkey.NewLimiter(client, valkey.Limits{ + Global: global, + Groups: map[string]valkey.Budget{ + "auth": {Rate: cfg.Admission.AuthRate, Slots: cfg.Admission.AuthSlots}, + "read": global, + "write": global, + }, + User: valkey.Budget{Rate: cfg.Admission.UserRate, Slots: cfg.Admission.UserSlots}, + UserGroups: map[string]valkey.Budget{ + "auth": {Rate: cfg.Admission.UserAuthRate, Slots: cfg.Admission.UserAuthSlots}, + "read": {Rate: cfg.Admission.UserRate, Slots: cfg.Admission.UserSlots}, + "write": {Rate: cfg.Admission.UserWriteRate, Slots: cfg.Admission.UserWriteSlots}, + }, + }) +} + +// databaseStore exposes business persistence through its consumer interface. +func databaseStore(database *postgres.Store) store.Interface { + return database +} + +// databaseAccounts exposes account and session persistence through its consumer interface. +func databaseAccounts(database *postgres.Store) service.Accounts { + return database +} + +// profileCache exposes immutable profiles without leaking the Valkey client. +func profileCache(client *valkey.Client) service.ProfileCache { + return client +} diff --git a/cmd/server/app_test.go b/cmd/server/app_test.go new file mode 100644 index 00000000..34c93032 --- /dev/null +++ b/cmd/server/app_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "context" + "net" + "os" + "testing" + "time" + + "go.uber.org/fx" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" +) + +// TestDependencyGraph ensures constructor signatures and interface bindings agree. +func TestDependencyGraph(t *testing.T) { + if err := fx.ValidateApp(CreateApp(), fx.NopLogger); err != nil { + t.Fatal(err) + } +} + +// TestInvalidConfigurationStopsStartup checks failure before a listener is acquired. +func TestInvalidConfigurationStopsStartup(t *testing.T) { + t.Setenv("APP_PORT", "0") + app := fx.New(CreateApp(), fx.NopLogger) + if err := app.Start(context.Background()); err == nil { + t.Fatal("invalid listener configuration accepted") + } +} + +// TestCommandValidation ensures unsupported arguments cannot accidentally start a server. +func TestCommandValidation(t *testing.T) { + if err := run([]string{"unknown"}); err == nil { + t.Fatal("unknown command accepted") + } +} + +// TestLoggerConfiguration checks that process logging uses its own validated section. +func TestLoggerConfiguration(t *testing.T) { + if _, err := newLogger(&config.Logger{Level: "invalid"}); err == nil { + t.Fatal("invalid logger configuration accepted") + } +} + +// TestApplicationLifecycle starts the complete Fx graph and drains its real HTTP listener. +func TestApplicationLifecycle(t *testing.T) { + requirePersistence(t) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + cfg := config.Default() + cfg.HTTP.Host = "127.0.0.1" + cfg.HTTP.Port = listener.Addr().(*net.TCPAddr).Port + cfg.Logger.Level = "error" + if err := listener.Close(); err != nil { + t.Fatal(err) + } + app := fx.New(CreateApp(), fx.Replace(cfg)) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + if err := app.Start(ctx); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer stopCancel() + if err := app.Stop(stopCtx); err != nil { + t.Error(err) + } + }) + if err := checkReadiness(cfg.HTTP); err != nil { + t.Fatal(err) + } +} + +// TestOccupiedListenerFailsStartup ensures bind failures propagate through the Fx lifecycle. +func TestOccupiedListenerFailsStartup(t *testing.T) { + requirePersistence(t) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { + _ = listener.Close() + }() + cfg := config.Default() + cfg.HTTP.Host = "127.0.0.1" + cfg.HTTP.Port = listener.Addr().(*net.TCPAddr).Port + cfg.Logger.Level = "error" + app := fx.New(CreateApp(), fx.Replace(cfg), fx.NopLogger) + if err := app.Start(t.Context()); err == nil { + _ = app.Stop(t.Context()) + t.Fatal("startup succeeded on an occupied listener") + } +} + +// requirePersistence prevents infrastructure scenarios from silently passing on configuration failure. +func requirePersistence(t *testing.T) { + t.Helper() + if os.Getenv("DATABASE_URL") == "" || os.Getenv("VALKEY_SHARDS") == "" { + t.Skip("DATABASE_URL and VALKEY_SHARDS are required for real application lifecycle tests") + } +} diff --git a/cmd/server/commands.go b/cmd/server/commands.go new file mode 100644 index 00000000..cdce9527 --- /dev/null +++ b/cmd/server/commands.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + + "go.uber.org/fx" +) + +// run dispatches the server command or the container healthcheck. +func run(args []string) error { + if len(args) == 0 { + fx.New(CreateApp()).Run() + return nil + } + if len(args) == 1 && args[0] == "healthcheck" { + return healthcheck() + } + return fmt.Errorf("usage: server [healthcheck]") +} diff --git a/cmd/server/healthcheck.go b/cmd/server/healthcheck.go new file mode 100644 index 00000000..dab28400 --- /dev/null +++ b/cmd/server/healthcheck.go @@ -0,0 +1,46 @@ +package main + +import ( + "fmt" + "net" + "net/http" + "strconv" + "time" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" +) + +const readinessProbeTimeout = 2 * time.Second + +// healthcheck loads configuration and runs the container readiness probe. +func healthcheck() error { + cfg, err := config.New() + if err != nil { + return err + } + return checkReadiness(cfg.HTTP) +} + +// checkReadiness checks the local readiness endpoint within the probe timeout. +func checkReadiness(cfg *config.Controller) error { + host := cfg.Host + if host == "0.0.0.0" { + host = "127.0.0.1" + } + if host == "::" { + host = "::1" + } + address := "http://" + net.JoinHostPort(host, strconv.Itoa(cfg.Port)) + "/health/ready" + client := http.Client{Timeout: readinessProbeTimeout} + response, err := client.Get(address) + if err != nil { + return fmt.Errorf("readiness probe: %w", err) + } + defer func() { + _ = response.Body.Close() + }() + if response.StatusCode != http.StatusOK { + return fmt.Errorf("not ready: %d", response.StatusCode) + } + return nil +} diff --git a/cmd/server/healthcheck_test.go b/cmd/server/healthcheck_test.go new file mode 100644 index 00000000..11076354 --- /dev/null +++ b/cmd/server/healthcheck_test.go @@ -0,0 +1,111 @@ +package main + +import ( + "errors" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "testing" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" +) + +// TestRun_Healthcheck verifies command routing to the readiness endpoint. +func TestRun_Healthcheck(t *testing.T) { + // Arrange. + requests := make(chan string, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests <- r.Method + " " + r.URL.Path + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(server.Close) + address := server.Listener.Addr().(*net.TCPAddr) + t.Setenv("APP_HOST", "0.0.0.0") + t.Setenv("APP_PORT", strconv.Itoa(address.Port)) + + // Act. + err := run([]string{"healthcheck"}) + + // Assert. + if err != nil { + t.Fatal(err) + } + select { + case got := <-requests: + if got != "GET /health/ready" { + t.Fatalf("probe=%q", got) + } + default: + t.Fatal("command returned success without probing readiness") + } +} + +// TestHealthcheck_InvalidConfig rejects invalid startup settings before attempting HTTP. +func TestHealthcheck_InvalidConfig(t *testing.T) { + // Arrange. + t.Setenv("APP_PORT", "invalid") + + // Act. + err := healthcheck() + + // Assert. + if err == nil { + t.Fatal("invalid port accepted") + } +} + +// TestCheckReadiness distinguishes unhealthy responses from connection failures. +func TestCheckReadiness(t *testing.T) { + t.Run("Negative: unhealthy response", func(t *testing.T) { + // Arrange. + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(server.Close) + address := server.Listener.Addr().(*net.TCPAddr) + cfg := config.Default().HTTP + cfg.Host = "127.0.0.1" + cfg.Port = address.Port + + // Act. + err := checkReadiness(cfg) + + // Assert. + if err == nil { + t.Fatalf("probe accepted %s", "Negative: unhealthy response") + } + if err.Error() != "not ready: 503" { + t.Fatalf("unexpected health failure: %v", err) + } + + }) + + t.Run("Negative: server unavailable", func(t *testing.T) { + // Arrange. + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(server.Close) + address := server.Listener.Addr().(*net.TCPAddr) + cfg := config.Default().HTTP + cfg.Host = "127.0.0.1" + cfg.Port = address.Port + + server.Close() + + // Act. + err := checkReadiness(cfg) + + // Assert. + if err == nil { + t.Fatalf("probe accepted %s", "Negative: server unavailable") + } + + if _, ok := errors.AsType[*url.Error](err); !ok { + t.Fatalf("connection failure was not preserved: %v", err) + } + + }) +} diff --git a/cmd/server/logger.go b/cmd/server/logger.go new file mode 100644 index 00000000..64e59744 --- /dev/null +++ b/cmd/server/logger.go @@ -0,0 +1,29 @@ +package main + +import ( + "go.uber.org/fx/fxevent" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" +) + +// newLogger creates a structured logger with the configured severity threshold. +func newLogger(cfg *config.Logger) (*zap.Logger, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + level, err := zapcore.ParseLevel(cfg.Level) + if err != nil { + return nil, err + } + settings := zap.NewProductionConfig() + settings.Level = zap.NewAtomicLevelAt(level) + settings.DisableStacktrace = true + return settings.Build() +} + +// newFxLogger adapts the application logger for Fx lifecycle events. +func newFxLogger(log *zap.Logger) fxevent.Logger { + return &fxevent.ZapLogger{Logger: log.Named("fx")} +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..1d1fbd58 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,15 @@ +// Command server runs the messenger or its container readiness probe. +package main + +import ( + "fmt" + "os" +) + +// main runs the selected command and reports failures to stderr. +func main() { + if err := run(os.Args[1:]); err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/cmd/server/persistence.go b/cmd/server/persistence.go new file mode 100644 index 00000000..3d1d3ce7 --- /dev/null +++ b/cmd/server/persistence.go @@ -0,0 +1,77 @@ +package main + +import ( + "context" + "time" + + "go.uber.org/fx" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service/authentication" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store/postgres" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/valkey" +) + +type dependencyReadiness struct { + database *postgres.Store + cache *valkey.Client +} + +// Ping checks persistence and all limiter shards under a shared deadline. +func (d *dependencyReadiness) Ping(ctx context.Context) error { + if err := d.database.Ping(ctx); err != nil { + return err + } + return d.cache.Ping(ctx) +} + +// newDatabase creates the pool and registers its migration/start and shutdown hooks. +func newDatabase(lifecycle fx.Lifecycle, cfg *config.Persistence) (*postgres.Store, error) { + database, err := postgres.New(postgres.Options{ + URL: cfg.DatabaseURL, + MaxConnections: int32(cfg.PoolSize), + Timeout: time.Duration(cfg.TimeoutMilliseconds) * time.Millisecond, + }) + if err != nil { + return nil, err + } + lifecycle.Append(fx.Hook{ + OnStart: database.Start, + OnStop: func(context.Context) error { + database.Close() + return nil + }, + }) + return database, nil +} + +// newValkey creates bounded clients and registers connectivity and cleanup hooks. +func newValkey(lifecycle fx.Lifecycle, cfg *config.Persistence) (*valkey.Client, error) { + client, err := valkey.New(valkey.Options{ + Nodes: cfg.Shards, + Coordinator: cfg.Coordinator, + PoolSize: cfg.PoolSize, + Timeout: time.Duration(cfg.TimeoutMilliseconds) * time.Millisecond, + }) + if err != nil { + return nil, err + } + lifecycle.Append(fx.Hook{ + OnStart: client.Ping, + OnStop: func(context.Context) error { + return client.Close() + }, + }) + return client, nil +} + +// newAuthentication binds credentials and KDF implementations to authentication policy. +func newAuthentication(accounts service.Accounts, passwords service.Passwords, cfg *config.Persistence) (service.Authentication, error) { + return authentication.New(accounts, passwords, time.Duration(cfg.SessionTTLSeconds)*time.Second) +} + +// newReadiness assembles infrastructure checks at the composition boundary. +func newReadiness(database *postgres.Store, cache *valkey.Client) *dependencyReadiness { + return &dependencyReadiness{database: database, cache: cache} +} diff --git a/cmd/server/persistence_test.go b/cmd/server/persistence_test.go new file mode 100644 index 00000000..0b9a5cec --- /dev/null +++ b/cmd/server/persistence_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "testing" + "time" + + "go.uber.org/fx" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store/postgres" +) + +// TestDatabaseProviderRejectsInvalidConfiguration verifies dependency errors propagate before startup. +func TestDatabaseProviderRejectsInvalidConfiguration(t *testing.T) { + var lifecycle fx.Lifecycle + app := fx.New(fx.NopLogger, fx.Populate(&lifecycle)) + if err := app.Err(); err != nil { + t.Fatal(err) + } + if _, err := newDatabase(lifecycle, &config.Persistence{}); err == nil { + t.Fatal("invalid database settings accepted") + } +} + +// TestValkeyProviderRejectsInvalidConfiguration verifies the cache constructor is a real boundary. +func TestValkeyProviderRejectsInvalidConfiguration(t *testing.T) { + var lifecycle fx.Lifecycle + app := fx.New(fx.NopLogger, fx.Populate(&lifecycle)) + if err := app.Err(); err != nil { + t.Fatal(err) + } + if _, err := newValkey(lifecycle, &config.Persistence{}); err == nil { + t.Fatal("invalid cache settings accepted") + } +} + +// TestReadinessStopsAtUnavailableDatabase checks that mandatory persistence failure is visible. +func TestReadinessStopsAtUnavailableDatabase(t *testing.T) { + database, err := postgres.New(postgres.Options{URL: "postgres://localhost/test", MaxConnections: 1, Timeout: time.Second}) + if err != nil { + t.Fatal(err) + } + database.Close() + readiness := newReadiness(database, nil) + if err := readiness.Ping(t.Context()); err == nil { + t.Fatal("closed database reported ready") + } +} diff --git a/docs/DEFENSE.md b/docs/DEFENSE.md new file mode 100644 index 00000000..97c16cc1 --- /dev/null +++ b/docs/DEFENSE.md @@ -0,0 +1,89 @@ +# План защиты лабораторной 2 — 9 минут 30 секунд + +Резерв до лимита 10 минут — 30 секунд. Рабочий каталог — корень репозитория lab2. Демонстрация относится к PostgreSQL, сессиям, Valkey и SQL-исследованию; HPA и балансировка lab3 сюда не входят. + +## Подготовить до защиты + +- Открыть REPORT.md, ARCHITECTURE.md, этот план и два терминала. +- Выполнить `make chart-check`, `make test-faults`; сборка Docker и остановки зависимостей не должны съедать время защиты. +- Открыть сохранённые `evidence/fault-regression.txt`, `evidence/sql-research-domain.json`, `evidence/sql-research-helm.txt`. Это реальные предыдущие измерения с датами, а не результаты сегодняшнего стенда. +- В первом терминале запустить `make port-forward` (localhost:8080); во втором — `make ready` и `make test`. +- Если 8080 занят, использовать `LOCAL_PORT=18082 make port-forward`, а в проверках `BASE_URL=http://localhost:18082`. +- Для воспроизведения SQL-исследования заранее выполнить `make research`: отдельный временный Docker PostgreSQL, не база dev. На защите показывать готовые планы и результаты. + +## 0:00–0:45 — задача и результат + +«Перенесён мессенджер из памяти в PostgreSQL. Подтверждённые сообщения и сессии переживают рестарт. Valkey используется для кэша профилей и распределённых ограничений. Цель — уровни 3 и 4 и трек “План запроса и восстановление”.» + +```sh +helm list --kube-context dev -n highload-applications +kubectl --context dev -n highload-applications get pods -l 'app in (api,postgres,valkey)' +``` + +Показать API, PostgreSQL, три Valkey. Kubernetes — выбранный способ развёртывания; формальное принятие замены Compose/Swarm преподавателем учитывается отдельно. + +## 0:45–1:45 — архитектура и авторизация + +Показать ARCHITECTURE.md и коротко объяснить: + +- Fiber controller принимает HTTP; service проверяет правила и доступ; store выполняет SQL. Реализации связываются через Fx, между слоями — интерфейсы. +- Пароль хранится как Argon2id hash. Basic применяется при входе, затем используется случайный opaque Bearer token. +- В PostgreSQL хранится digest токена и абсолютный срок действия. Сессия проверяется в источнике истины на каждом запросе, поэтому logout действует сразу. +- Valkey кэширует профиль, но не подменяет проверку сессии. Отказ зависимости не открывает анонимный доступ. + +## 1:45–3:00 — работа API + +```sh +make test +``` + +Пояснить, что публичный smoke проверяет цепочку регистрации, входа, чатов и сообщений, авторизацию и пагинацию. Не выводить реальные токены. Пока работает тест, показать schema/migration и ограничения FK/unique. + +## 3:00–4:30 — сохранность после рестарта + +```sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +«Тест создаёт сообщение и сессию, перезапускает API, PostgreSQL и Valkey через явно заданный hook. PVC не удаляются. Затем прежний токен читает прежнее подтверждённое сообщение без нового логина.» + +Дождаться PASS. Если инфраструктура задерживает рестарт, не выдавать сохранённый лог за текущий PASS: показать прошлый результат с его датой и продолжить по плану. + +## 4:30–5:45 — реальные отказы зависимостей + +```sh +rg 'PASS:' evidence/fault-regression.txt +``` + +«Команда воспроизведения — make test-faults. Отдельные Docker-контейнеры PostgreSQL и Valkey по очереди останавливаются и замораживаются. Во всех четырёх сценариях запрос истории с действующим токеном получает 503 unavailable. Проверяются readiness=503, liveness=200, отсутствие доступа без токена и по поддельной идентичности, затем восстановление с прежней сессией.» + +Уточнить исправление ревью: сетевые ошибки PostgreSQL классифицируются в store; неизвестная SQL-ошибка остаётся безопасным 500. В измеренном прогоне отказ отвечал за 0.002–0.508 с при timeout зависимости 500 мс. На dev для демонстрации ничего дополнительно останавливать не требуется. + +## 5:45–7:45 — исследовательский трек на 5 + +Гипотеза: индекс `(chat_id, created_at, id)` ускоряет позднюю страницу истории, поскольку соответствует фильтру, курсору и порядку сортировки. + +```sh +jq '[.variants[] | {name, read_ms:[.select_plans[][0]["Execution Time"]]}]' evidence/sql-research-domain.json +rg 'PASS: restore' evidence/sql-research-helm.txt +``` + +Объяснить метод: 100 000 синтетических сообщений, распределение 90/9/1% по чатам; сравнение индекса по chat_id с составным индексом; три повтора чтения и вставки 1000 строк с rollback; EXPLAIN ANALYZE BUFFERS. + +Результат исторического прогона 2026-10-07: чтение 7.646–8.604 мс против 0.055–0.136 мс. Показать в плане исчезновение лишней сортировки и уменьшение объёма обработки. Это эффект конкретного запроса и набора данных, не обещание такого ускорения всего API. По вставке диапазоны перекрываются: измеренного устойчивого штрафа не доказано. + +Backup/restore: логический dump восстановлен в новую БД, совпали 100 000 строк и checksum; приведены выборочные записи. Это не HA и не PITR. + +## 7:45–8:45 — дополнительные лимиты и шарды + +«В Valkey Lua атомарно проверяет rate и слоты одновременных запросов. Есть глобальный бюджет, группы auth/read/write и бюджет пользователя. 429 — превышение частоты, 503 — занятые слоты или недоступность обязательного backend.» + +«Пользовательские ключи распределяются consistent hashing с виртуальными узлами. Это три самостоятельных Valkey и клиентская маршрутизация, не Redis Cluster. Глобальные лимиты согласуются на shard0. Изменение кольца выполняется через остановку и drain API; глобальная координация остаётся точкой отказа.» + +Не запускать reshard в десятиминутной защите: команда намеренно ждёт истечения lease и вызывает простой. Показать `make reshard SHARDS=2` как документированный способ, а измерения — в REPORT. + +## 8:45–9:30 — проверки и ограничения + +Показать `evidence/fault-coverage-per-file.json`: каждый из 57 исполняемых Go-файлов имеет ≥90% statements. Упомянуть race, реальные PostgreSQL/Valkey integration, lint/vet и отдельный fault-сценарий в CI; запуск удалённого runner не подтверждён локальными проверками. + +Ограничения: PostgreSQL и координатор Valkey не реплицированы; hostpath PVC зависят от узла; cursor key lab2 локален процессу, старый cursor после рестарта может стать недействительным; исторические измерения отделены от свежих проверок. Оценку определяет преподаватель. diff --git a/docs/PLAN.md b/docs/PLAN.md new file mode 100644 index 00000000..ba717cdd --- /dev/null +++ b/docs/PLAN.md @@ -0,0 +1,23 @@ +# План лабораторной 2 + +| Задача | Требования | Результат и проверка | Статус | +| --- | --- | --- | --- | +| L2-T01 | L2-REQ-01,08 | Выборочный перенос, новая аутентификация; [smoke](../evidence/smoke.txt) | Выполнено локально | +| L2-T02 | L2-REQ-01,04,05 | PostgreSQL, миграции, rollback, гонки, keyset; [race/integration](../evidence/go-tests-coverage.txt) | Выполнено | +| L2-T03 | L2-REQ-02,03 | Argon2id, сессии, TTL/отзыв, профильный кэш; [fault tests](../evidence/dependencies.json) | Выполнено локально | +| L2-T04 | L2-REQ-06,07 | Группы и user/global budgets, Lua/lease, consistent hashing; unit/integration; [ring](../evidence/hashring.txt) | Выполнено; [расширение 2→3](../evidence/k8s-scale-shards.txt) и smoke прошли | +| L2-T05 | L2-REQ-09 | Helm install/upgrade/restart/reshard, PVC, локальный Docker [persistence](../evidence/persistence.txt) | Выполнено в dev / highload-applications; [smoke/persistence](../evidence/k8s-persistence-three-shards.txt); принятие преподавателем учитывается отдельно | +| L2-T06 | L2-REQ-05,10 | 100 000 сообщений, планы/вставки, backup/restore; [raw results](../evidence/sql-research-domain.json) | Выполнено локально | +| L2-T07 | L2-REQ-08 | DIP-аудит, fmt/lint/vet/race; [порог каждого файла](../evidence/coverage-per-file.json); CI workflow | Локально выполнено; удалённый CI не запускался | +| L2-T09 | L2-REQ-11 | Registry build/push, digest deployment, namespaced pull-secret | Выполнено; [build metadata](../evidence/image-build.json) | +| L2-T08 | Все | [REPORT](../REPORT.md), evidence и инструкция Helm | Выполнено; [итоговый Kubernetes snapshot](../evidence/k8s-deployment.json) | +| L2-T10 | L2-REQ-09,11,12 | Helm chart, values, adoption без потери данных, upgrade, reshard 3→2→3; [проверка](../evidence/helm-deployment.txt) | Выполнено в dev | +| L2-T11 | L2-REQ-08,10,12 | [Покрытие shell/awk](../evidence/helm-coverage-per-file.json), [SQL-эксперимент](../evidence/sql-research-helm.txt), сокращённый REPORT; собственные Python-скрипты удалены | Выполнено | + +Обязательные contracts и публичные tests сохранены. Lab1 и соседние реализации не изменялись. Контейнерный образ опубликован; решение находится в main и PR №52 (Агапов Владислав, БПИ2303). Результат защиты не зафиксирован. Код, локальные измерения, кластерная проверка и принятие работы учитываются отдельно. + +| Задача | Требования | Результат и проверка | Статус | +| --- | --- | --- | --- | +| L2-T12 | L2-REQ-13 | Перенесены 182 файла; module/imports обновлены; build, vet, race, lint, chart-check и неизменность публичных материалов проверены; [результаты](../evidence/gitea-transfer-tests.txt) | Перенос проверен; main опубликован, PR №52 открыт; без redeploy | +| L2-T13 | L2-REQ-03,04 | Классификация PostgreSQL, unit-регрессии, make test-faults: stop/pause обоих backend, запрет анонимного доступа, recovery; evidence/fault-regression.txt; race/coverage ≥90% по каждому файлу | Выполнено локально | +| L2-T14 | L2-REQ-09,11 | Переустановка lab2 в dev из Timeweb; PVC и данные сохранены, smoke/persistence PASS; docs/DEFENSE.md | Выполнено; evidence/timeweb-* | diff --git a/docs/SPEC.md b/docs/SPEC.md new file mode 100644 index 00000000..fb502d49 --- /dev/null +++ b/docs/SPEC.md @@ -0,0 +1,48 @@ +# Спецификация лабораторной 2 + +Версия 4, локальная реализация и развёртывание в Kubernetes dev проверены. Цель: весь уровень 3 и 4, один исследовательский трек уровня 5; дополнительно распределённый admission и демонстрация шардирования. + +Нормативные источники: [задание](../README.md), [курс](../COURSE.md), [контракт](../contracts/README.md), [OpenAPI](../contracts/openapi.json), [правила сдачи](../CONTRIBUTING.md). Обязательные контракты и публичные проверки сохраняются. + +| ID | Требование | Критерий приёмки | +| --- | --- | --- | +| L2-REQ-01 | Перенести бизнес-возможности lab1, хранить пользователей, чаты, участников и сообщения в PostgreSQL | Публичный smoke; уникальность username; FK; атомарное создание чата; миграции с нуля и повторно | +| L2-REQ-02 | Пароль 12–128 Unicode code points, библиотечный KDF; Basic только при входе; случайная opaque Bearer-сессия | Неверный пароль, UTF-8, expiry, logout, игнорирование X-User-Id, WWW-Authenticate | +| L2-REQ-03 | PostgreSQL — источник истины для сессий; Redis/Valkey — осмысленный кэш | Сохранность после полного рестарта; TTL не продлевается; отзыв виден сразу; отказ кэша не предоставляет доступ | +| L2-REQ-04 | Ограниченные pool и timeout; ошибки зависимостей не раскрывают секреты | Изолированные проверки отказа PostgreSQL и Valkey; readiness | +| L2-REQ-05 | Keyset pagination, индекс истории, read-after-write | EXPLAIN ANALYZE BUFFERS на ≥10 000 сообщений; отсутствие повторов неизменной истории | +| L2-REQ-06 | Redis/Valkey admission: глобальные и пользовательские лимиты, группы auth/read/write | Конкурентные запросы не превышают лимит; освобождение lease и TTL при аварии; отказ хранилища закрывает admission | +| L2-REQ-07 | 2–3 шарда и клиентское consistent hashing | При добавлении третьего узла перемещается только часть ключей; сохранение лимитов при смене topology; явное описание SPOF | +| L2-REQ-08 | Проверить DIP и соглашения Go | Controller→service interface; service→store/client interfaces; gofmt, vet, lint, race; ≥90% statements в каждом исполняемом Go-файле, порог CI | +| L2-REQ-09 | Воспроизводимый стенд и restart hook | Bootstrap из отдельного clone, сохранённые volumes, публичный persistence | +| L2-REQ-10 | Полный исследовательский трек | Трек 2: ≥100 000 сообщений, ≥2 варианта запросов/индексов, стоимость записи, backup/restore и сверка; проверен в изолированном PostgreSQL | + +## Инварианты + +Авторизация остаётся в service. Store получает проверенные UUID и обеспечивает транзакции и ограничения. Сессии хранят hash токена; парольный hash никогда не попадает в HTTP User. Кэш не является основанием обойти проверку действительности сессии. Чужой чат возвращает 404. История читается из PostgreSQL для read-after-write. + +Глобальный лимит требует общего координатора: распределение пользовательских ключей по шардам само по себе не даёт атомарного общего лимита. Изменение topology выполняется управляемо; нельзя потерять активные счётчики и предоставить новый burst. + +## Открытые вопросы + +- Основной реализованный стенд — Kubernetes dev; формальное принятие преподавателем отдельно не подтверждено. Второй путь оркестрации не реализуется. +- Исследовательский трек 2 реализован; результаты и ограничения приведены в REPORT. +- Git-публикация и принятие преподавателем не выполнены; commit/push/PR не выполняются без поручения. + +## Развёртывание в dev + +L2-REQ-11: использовать существующий Yandex Container Registry `cr.yandex/crpv8disueqk68pv29jg`, отдельный image `mtusi2026lab2`, контекст `dev` и namespace `highload-applications`. Локальный service-account key читается из `~/key.json`, не копируется в Git и не выводится. Deployment закрепляется по опубликованному digest из build metadata; tag обозначает время сборки. Проверки: pull, rollout, smoke, полный persistence, расширение 2→3 shard и повторный smoke. Применение в dev разрешено; принятие Kubernetes преподавателем учитывается отдельно. + +## Упрощение стенда + +L2-REQ-12: единственный источник Kubernetes-ресурсов — Helm chart. Values задают образ, ресурсы и 2–3 шарда; одна лабораторная размещается в одном namespace. Повторный upgrade сохраняет PVC, секреты и данные. Изменение кольца требует остановки API и истечения lease. Python остаётся только в публичных проверках задания; собственная обвязка заменяется стандартными Helm/Docker/kubectl, shell, SQL и awk. REPORT содержит однозначные команды запуска, фактические проверки и ограничения. Приёмка: helm lint/template, adoption текущего стенда без замены PVC, повторный upgrade, smoke/persistence, проверка новых команд покрытия и SQL-эксперимента. + +## Перенос в Gitea + +L2-REQ-13: решение размещается в репозитории `ssh://git@gitea.privcloud.tech:2222/vlad_marlo/mtusi2026lab2.git`. Имя Go-модуля и внутренние imports соответствуют новому хосту. Задание, contracts и публичные tests нового репозитория сохраняются. Секреты, runtime-данные и история исходного `.git` не переносятся. Проверки: сборка, unit/race, vet, chart lint и неизменность публичных материалов. Измерения от 2026-10-07 остаются историческими и не подменяют проверки переноса. + +## Классификация отказов зависимостей + +Уточнение L2-REQ-04: потеря соединения, timeout и недоступность PostgreSQL возвращают HTTP 503 / `unavailable`, включая проверку действительной сессии. Ошибки SQL/неизвестные ошибки сохраняют безопасный 500. Воспроизводимый `make test-faults` создаёт изолированные Docker-зависимости, останавливает PostgreSQL и Valkey по очереди, проверяет историю с прежним токеном, отсутствие анонимного доступа, readiness/liveness и восстановление. Пользовательский кластер и данные не затрагиваются. + +Уточнение L2-REQ-11 от 2026-10-16: основной registry — `asisti.registry.twcstorage.ru`, локальный токен — `~/.secrets/twc-registry-token`. Helm использует `registry-pull` и опубликованный digest исправления 87e1e5d. Переустановка lab2 в dev сохраняет существующие PVC и Secret БД; соседние releases не изменяются. diff --git a/docs/decisions/0001-postgres-sessions-shards.md b/docs/decisions/0001-postgres-sessions-shards.md new file mode 100644 index 00000000..e982b512 --- /dev/null +++ b/docs/decisions/0001-postgres-sessions-shards.md @@ -0,0 +1,33 @@ +# ADR-0001: PostgreSQL, сессии и шардированный Valkey + +Статус: реализовано, проверено локально и развёрнуто в Kubernetes dev / highload-applications. + +## Контекст + +[Задание](../../README.md) требует устойчивого состояния и аутентификации. Дополнительные требования: общий limiter с группами, пользовательские лимиты и демонстрация consistent hashing на 2–3 шардах. + +## Решение + +PostgreSQL хранит пользователей, credentials, чаты, участников, сообщения и hash сессионного токена с абсолютным expiry. Пароли обрабатывает библиотечный Argon2id: 19 MiB, 2 прохода, один поток, salt 16 bytes, hash 32 bytes. Bearer содержит 32 случайных bytes; хранится только SHA-256 digest. Сессия проверяется по PostgreSQL на каждом запросе. Logout удаляет запись до ответа 204. + +Valkey кэширует неизменяемые профили с TTL 5 минут. Кэш не хранит историю и не определяет действительность сессии. Cache miss, повреждённая запись и ошибка чтения профиля ведут к PostgreSQL. Поскольку Valkey одновременно обслуживает обязательный limiter, отказ его узла закрывает admission; обход кэша не означает обход лимитера. + +Клиентское кольцо использует SHA-256 → 64-bit координату и 256 виртуальных узлов на стабильный ID шарда. Глобальные бюджеты имеют постоянного координатора `shard0`; пользовательские бюджеты и профили распределяются по кольцу. Недоступный шард не исключается автоматически: такое исключение сбросило бы активный пользовательский лимит. + +Lua атомарно проверяет и резервирует два бюджета на одном узле: общий и соответствующей группы. Глобальная резервация предшествует аутентификации, пользовательская следует за ней. Это последовательное консервативное резервирование, а не распределённая транзакция: отклонённый пользовательский запрос уже расходует глобальный rate budget; глобальный slot освобождается. Успешных запросов сверх лимита такой порядок не допускает. + +Rate использует фиксированное окно 1 секунда от первого запроса; на границе возможны два burst подряд. Slots представлены sorted sets с уникальными lease ID, освобождением через ZREM и expiry 30 секунд. HTTP timeout ограничен 15 секундами, по умолчанию 3. Отказ освобождения оставляет временно занятый slot до expiry. Длительная приостановка процесса свыше lease и скачки часов Valkey выходят за гарантию строгой одновременности; это не распределённая блокировка для изменения обязательных данных. + +Смена кольца: остановить все API, дождаться drain и 31 секунду, добавить шард, изменить конфигурацию, сбросить только guard topology, запустить API. Fingerprint стабильных ID проверяется при старте/readiness. Значения профилей на старых владельцах истекают; новые владельцы прогреваются из PostgreSQL. Миграция обязательных данных не нужна. В этой демонстрации расширение требует короткого окна недоступности, online resharding не заявляется. + +## Альтернативы и последствия + +Redis Cluster использует фиксированные hash slots и собственный протокол маршрутизации; это другая модель, чем реализуемое клиентское кольцо. Перенос authoritative sessions в Valkey усложнил бы проверку persistence и инвалидацию при смене кольца. Здесь PostgreSQL остаётся единственным источником истины. + +Один PostgreSQL, один глобальный координатор и локальные PVC не обеспечивают HA. Глобальный координатор ограничивает масштабирование строгого общего лимита. Для lab2 это намеренная, явно проверяемая граница. + +## Проверки и источники + +Проверки кольца, атомарности и групп находятся в `internal/hashring` и `internal/valkey`; сценарии отказов и результаты — в [REPORT](../../REPORT.md). + +Первичные материалы: [Redis rate limiter](https://redis.io/docs/latest/develop/use-cases/rate-limiter/), [pgx StrictNamedArgs](https://pkg.go.dev/github.com/jackc/pgx/v5#StrictNamedArgs). Собственные Lua-операции и ring реализованы в этом репозитории. diff --git a/docs/decisions/0002-helm.md b/docs/decisions/0002-helm.md new file mode 100644 index 00000000..5f270ed9 --- /dev/null +++ b/docs/decisions/0002-helm.md @@ -0,0 +1,15 @@ +# ADR-0002: Helm для учебного стенда + +Принято: 2026-10-07. + +API, PostgreSQL, Valkey, ConfigMap и NetworkPolicy описываются одним Helm chart. Отдельный namespace изолирует лабораторную; внутри него имена ресурсов стабильны. Values содержат изменяемые параметры. Нет параллельного набора статических манифестов и генератора Kubernetes YAML. + +Секреты создаются отдельно один раз и передаются chart по имени. Helm не хранит пароли и registry key в values. StatefulSet сохраняет существующие имена и volumeClaimTemplates. При переходе существующие ресурсы принимаются через однократный `--take-ownership`; namespace, Secret и PVC не принимаются во владение release. + +Смена topology остаётся обслуживанием с остановкой API. Команда сначала выключает API, ждёт истечения lease, обновляет шарды, удаляет только guard topology и возвращает API. Обычный upgrade отклоняется при изменении кольца с работающим API. Ошибка обслуживания оставляет API остановленным; повтор команды продолжает процедуру. + +Chart рассчитан на одну лабораторную в namespace. Он не реализует HA PostgreSQL или Redis Cluster. Следующие лабораторные могут расширить этот chart своими компонентами. + +Источник: [Helm upgrade](https://docs.helm.sh/docs/helm/helm_upgrade/) — параметры upgrade, wait и take-ownership. + +При adoption Helm 4 server-side apply встретил конфликт владельцев `volumeClaimTemplates`, созданных kubectl. Повторный upgrade с `--take-ownership --server-side=false` сохранил StatefulSet и PVC. Обычные последующие upgrade наследуют этот способ применения. Флаг принятия владения не входит в Makefile: он нужен только при переносе существующей установки. diff --git a/evidence/README.md b/evidence/README.md index 8df70015..aafe9fea 100644 --- a/evidence/README.md +++ b/evidence/README.md @@ -1,5 +1,59 @@ -# Доказательства +# Доказательства лабораторной 2 -Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки. +Результаты относятся к локальному синтетическому стенду и Kubernetes dev / highload-applications, 2026-10-07. Удалённый CI и публикация PR не проверены. -Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно. +| Файл | Что подтверждает | +| --- | --- | +| `coverage-per-file.json` | Statements и SHA-256 каждого Go-файла; ≥90% отдельно, включая entrypoint; type-only файлы имеют null | +| `go-tests-coverage.txt` | Race/unit/integration, инструментированный процесс, публичный smoke и SIGTERM | +| `go-lint.txt` | golangci-lint: 0 issues | +| `container-build.txt` | Сборка Dockerfile с Go 1.26.1 | +| `smoke.txt` | Публичный API-сценарий на финальном контейнере | +| `persistence.txt`, `docker-restart.sh` | Сохранность данных и действующей сессии; точный scope локального restart hook | +| `dependencies.json`, `dependencies.txt` | Короткий TTL, logout, неверный пароль, отказ PostgreSQL/Valkey и восстановление | +| `sql-research-domain.json` | Итоговый SQL-эксперимент на настоящей миграции, 100 000 сообщений, два индекса, raw EXPLAIN и logical backup/restore | +| `sql-research.json` | Предварительный эксперимент на упрощённой таблице; не основной результат | +| `load.json`, `load-resources.json` | Closed-loop HTTP-нагрузка и выборки CPU/RAM; 429 учитываются среди ошибок | +| `environment.json` | Версии, образ, ресурсы, снимок исходников и границы проверки | +| `hashring.txt` | Реальный тест распределения 100 000 ключей при добавлении третьего узла | + +SQL-результаты содержат snapshot исходников на момент измерения. Последующие изменения admission/config/lifecycle не подменяют эту ревизию; схема сообщений и исследуемые запросы сохранены. Финальные проверки Go содержат собственные SHA-256 файлов. Ни один файл не содержит bearer tokens, password hashes или пользовательские сообщения; dataset синтетический. + +Повторение: команды в [REPORT](../REPORT.md). Скрипт эксперимента создаёт новую БД для restore и удаляет только созданные им объекты. Local Docker restart hook относится только к перечисленным тестовым контейнерам, не к произвольному стенду или Kubernetes. + + +## Kubernetes и registry + +- `image-build.json`: digest и metadata push в `cr.yandex/crpv8disueqk68pv29jg/mtusi2026lab2`. +- `registry-build.txt`: build/push log без содержимого локального ключа. +- `k8s-namespace-move.json`: сверка данных и прежней сессии при переносе из временного namespace в `highload-applications`. +- `k8s-highload-smoke-two-shards.txt`, `k8s-highload-persistence-two-shards.txt`: публичные проверки нового namespace с двумя шардами. +- `k8s-scale-shards.txt`, `k8s-smoke-three-shards.txt`: контролируемое расширение 2→3 и проверка API. +- `k8s-deployment.json`: итоговые ресурсы, PVC, image digest и Kubernetes-версия без Secret data. + +Файлы `k8s-smoke-two-shards.txt` и `k8s-persistence-two-shards.txt` относятся к первоначальному временному namespace `mtusi-lab2`; не подменяют результаты `highload-applications`. Исторические локальные `environment.json` и SQL snapshots сохранены отдельно от текущего кластерного состояния. + +- `k8s-persistence-three-shards.txt`: полный restart API, PostgreSQL и трёх Valkey с прежней сессией. +- `k8s-smoke-three-shards-first-attempt.txt`: сохранённый первый отказ туннеля после замены pod; это не успешная проверка. После ожидания туннеля повторный smoke прошёл. + +## Переход на Helm + +Новая инфраструктурная проверка 2026-10-07; Go-код и опубликованный runtime image не менялись. + +- `helm-deployment.txt`: принятие ресурсов в release `lab2`, повторный upgrade, сохранность UID PVC и количества записей; первый конфликт server-side apply сохранён в журнале. +- `helm-smoke.txt`, `helm-persistence.txt`: публичные проверки после перехода на Helm. +- `helm-reshard-two.txt`, `helm-reshard-three.txt`, `helm-smoke-two.txt`, `helm-smoke-three.txt`: новая команда обслуживания кольца 3→2→3 и smoke. +- `helm-coverage.txt`, `helm-coverage-per-file.json`: shell/awk coverage runner, race, реальные зависимости, entrypoint и SIGTERM; SHA-256 каждого файла и автоматический порог 90%. +- `sql-research-helm.txt`: новый прогон SQL-сценария из `student-tests/`, отдельный контейнер, 100000 сообщений, два индекса, dump/restore в новую БД. Два блока `real/user/sys` — wall time backup и restore соответственно; они включают вызов Docker CLI. + +Старые JSON-измерения сохранены как история, а не как результаты нового запуска. Собственные Python-скрипты удалены; публичные проверки задания остались без изменений. Повторяемые команды актуального стенда находятся в REPORT. + +## Перенос в Gitea — 2026-10-15 + +Репозиторий: `ssh://git@gitea.privcloud.tech:2222/vlad_marlo/mtusi2026lab2.git`. При переносе обновлены имя Go-модуля, imports и local-prefixes formatter. Исходный skeleton Gitea: `65003b6`. Публичные задания, tests и contracts сохранены без изменений. + +Свежие проверки переноса находятся в `gitea-transfer-tests.txt`: сборка, vet и race-тесты. Интеграционные тесты PostgreSQL/Valkey требуют отдельного окружения и в этом запуске пропускаются; развёртывание в Kubernetes не выполнялось. Остальные файлы evidence содержат прежние измерения от 2026-10-07 с исходными hash и именем модуля. Они не являются измерениями новой ревизии. + +Проверки исправления от 2026-10-16: `fault-regression.txt` — изолированный реальный stop/pause PostgreSQL и Valkey через HTTP, базовая ревизия и SHA-256 проверенного рабочего дерева; `fault-coverage.txt` / `fault-coverage-per-file.json` — race/integration и покрытие каждого файла; `fault-lint.txt`, `fault-vet.txt`, `fault-contract.txt` — статические проверки. Старые измерения не переписываются. + +`timeweb-*` — переустановка lab2 в dev от 2026-10-16: опубликованный образ кода 87e1e5d, Helm lint/render, сохранение четырёх PVC и количества записей до запуска новых тестов, публичные smoke/persistence. Метаданные сборки не означают запуск удалённого CI; SQL-измерения не повторялись. diff --git a/evidence/container-build.txt b/evidence/container-build.txt new file mode 100644 index 00000000..79ed7ccc --- /dev/null +++ b/evidence/container-build.txt @@ -0,0 +1,54 @@ +#0 building with "desktop-linux" instance using docker driver + +#1 [internal] load build definition from Dockerfile +#1 transferring dockerfile: 583B done +#1 DONE 0.0s + +#2 [internal] load metadata for docker.io/library/golang:1.26.1-alpine3.23 +#2 DONE 1.6s + +#3 [internal] load .dockerignore +#3 transferring context: 145B done +#3 DONE 0.0s + +#4 [build 1/7] FROM docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 +#4 resolve docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 done +#4 DONE 0.0s + +#5 [internal] load build context +#5 transferring context: 36.51kB 0.0s done +#5 DONE 0.0s + +#6 [build 3/7] COPY go.mod go.sum ./ +#6 CACHED + +#7 [build 2/7] WORKDIR /src +#7 CACHED + +#8 [build 4/7] RUN go mod download +#8 CACHED + +#9 [build 5/7] COPY cmd/ ./cmd/ +#9 DONE 0.0s + +#10 [build 6/7] COPY internal/ ./internal/ +#10 DONE 0.0s + +#11 [build 7/7] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server +#11 DONE 9.1s + +#12 [runtime 1/1] COPY --from=build /out/server /server +#12 DONE 0.0s + +#13 exporting to image +#13 exporting layers +#13 exporting layers 0.3s done +#13 exporting manifest sha256:bca510927916ed641287fe1b150244f74ed2f766e650bdaa024f0c5654ae4844 done +#13 exporting config sha256:87904053e6498b54ffcf8ce11f28175905c45a11f68dea19b81b384c3fa825ce done +#13 exporting attestation manifest sha256:230105ba2a87cfec168af2cf6d27c48884957ff5271c4f4a9a15a73da074e8ab done +#13 exporting manifest list sha256:bfec77a7c61e34f5c29804fd58f7c05fe7f59cbb2ed1ac50f24fdca5fa992608 done +#13 naming to docker.io/library/mtusi-messenger:lab2 done +#13 unpacking to docker.io/library/mtusi-messenger:lab2 0.0s done +#13 DONE 0.3s + +View build details: docker-desktop://dashboard/build/desktop-linux/desktop-linux/lv9t5wcizdrvn2334uyh085cm diff --git a/evidence/coverage-per-file.json b/evidence/coverage-per-file.json new file mode 100644 index 00000000..9b9f371c --- /dev/null +++ b/evidence/coverage-per-file.json @@ -0,0 +1,433 @@ +{ + "go_version": "go version go1.27.1 darwin/arm64", + "threshold": 90, + "files": { + "internal/controller/fx.go": { + "statements": 1, + "covered": 1, + "sha256": "af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a", + "percent": 100.0 + }, + "cmd/server/app.go": { + "statements": 8, + "covered": 8, + "sha256": "2c8e791d08fca312f52a40e082b18dc82676e891df57c04fbca1334d5edcfa26", + "percent": 100.0 + }, + "cmd/server/commands.go": { + "statements": 6, + "covered": 6, + "sha256": "7290636ea31539d87bd97bb78cb28658409da966be8983e748ce1701f6f9f8f6", + "percent": 100.0 + }, + "cmd/server/healthcheck.go": { + "statements": 19, + "covered": 18, + "sha256": "b0a0c1689dfe2db5abc889af13d7adb00a1d4f3d260b5ebe6d5f529cb5983a0e", + "percent": 94.73684210526316 + }, + "cmd/server/logger.go": { + "statements": 10, + "covered": 9, + "sha256": "43ad9caf2260d8551b8b3e149681c5e66770e9901d72de41b81746cb0cac47ec", + "percent": 90.0 + }, + "cmd/server/main.go": { + "statements": 3, + "covered": 3, + "sha256": "c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495", + "percent": 100.0 + }, + "cmd/server/persistence.go": { + "statements": 18, + "covered": 18, + "sha256": "06b304d8f0cad20c206edbef8becab283c50c1722fd81c56a06f018dfe03bb7f", + "percent": 100.0 + }, + "internal/admission/limiter.go": { + "statements": 16, + "covered": 16, + "sha256": "a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4", + "percent": 100.0 + }, + "internal/config/config.go": { + "statements": 17, + "covered": 17, + "sha256": "8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa", + "percent": 100.0 + }, + "internal/config/controller.go": { + "statements": 24, + "covered": 23, + "sha256": "e784d7b934c4604065cd00bf4ff2b0c74741e759b1b7c81162adfc206d160153", + "percent": 95.83333333333333 + }, + "internal/config/environment.go": { + "statements": 14, + "covered": 14, + "sha256": "027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3", + "percent": 100.0 + }, + "internal/config/logger.go": { + "statements": 7, + "covered": 7, + "sha256": "3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988", + "percent": 100.0 + }, + "internal/config/memory.go": { + "statements": 11, + "covered": 11, + "sha256": "86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0", + "percent": 100.0 + }, + "internal/config/persistence.go": { + "statements": 15, + "covered": 15, + "sha256": "671f92c52c827989ce194f3928b02f707292022bb97d3c483410e97cf626b4af", + "percent": 100.0 + }, + "internal/controller/http/fiber/auth.go": { + "statements": 29, + "covered": 29, + "sha256": "3107673b329dbe7934a29679024a18e3baada2cc99bee4d0ddbba0f9fd93edf9", + "percent": 100.0 + }, + "internal/controller/http/fiber/configure.go": { + "statements": 7, + "covered": 7, + "sha256": "be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd", + "percent": 100.0 + }, + "internal/controller/http/fiber/controller.go": { + "statements": 10, + "covered": 10, + "sha256": "fd0d06ac838c8ceca1189303b98ce006ca1298381de49fe6d790d0f0f4007d3e", + "percent": 100.0 + }, + "internal/controller/http/fiber/decode.go": { + "statements": 6, + "covered": 6, + "sha256": "bb4216cb6c5813b66b51dc99a53f8cf09982789155305a099c321dd12fa8e2de", + "percent": 100.0 + }, + "internal/controller/http/fiber/error_registry.go": { + "statements": 2, + "covered": 2, + "sha256": "9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a", + "percent": 100.0 + }, + "internal/controller/http/fiber/errors.go": { + "statements": 28, + "covered": 28, + "sha256": "d502e2a9f7fe3980c10c2760c31711794898c539d07b43b02497dc2cfb870358", + "percent": 100.0 + }, + "internal/controller/http/fiber/handlers.go": { + "statements": 37, + "covered": 36, + "sha256": "59e3f16adc94b7426c74e2f40b5ff18a9129c80fc619cb8144110bdeec095021", + "percent": 97.29729729729729 + }, + "internal/controller/http/fiber/health.go": { + "statements": 7, + "covered": 7, + "sha256": "6d18f3c4be98e70a7e61d82b014b6db9b3a5e594c9b5f50ecea88f89bd6917cd", + "percent": 100.0 + }, + "internal/controller/http/fiber/lifecycle.go": { + "statements": 24, + "covered": 22, + "sha256": "f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08", + "percent": 91.66666666666667 + }, + "internal/controller/http/fiber/mapping.go": { + "statements": 19, + "covered": 19, + "sha256": "f63d4b0e2ee5f62c4d0d8c4b26a8734d68230af4577e3c6cb71a92525c3c8681", + "percent": 100.0 + }, + "internal/controller/http/fiber/middleware.go": { + "statements": 34, + "covered": 33, + "sha256": "34fd687af80730601ba9276ef606fee76df84d14b4400a65ec5b804897673536", + "percent": 97.05882352941177 + }, + "internal/controller/http/fiber/public_errors.go": { + "statements": 12, + "covered": 11, + "sha256": "d806c2d026a8ff2fc54d60b62c062e80a3532e652fcfa5c3105684ba17cc9f67", + "percent": 91.66666666666667 + }, + "internal/controller/http/fiber/routes.go": { + "statements": 56, + "covered": 56, + "sha256": "826fe61b8d59465de7190c175b6abaa118f4a7deacdb1b9c628e25bb7f4feb3b", + "percent": 100.0 + }, + "internal/cursor/codec.go": { + "statements": 33, + "covered": 31, + "sha256": "a5bc7aac6d1764929fb11365c9f8b6a45ff65e47b3a317a7ccd9ec6dd1b2713a", + "percent": 93.93939393939394 + }, + "internal/hashring/ring.go": { + "statements": 21, + "covered": 20, + "sha256": "e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c", + "percent": 95.23809523809524 + }, + "internal/password/password.go": { + "statements": 18, + "covered": 17, + "sha256": "fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76", + "percent": 94.44444444444444 + }, + "internal/service/authentication/service.go": { + "statements": 48, + "covered": 47, + "sha256": "1cc82be87998dc9b66216965dc3ac37aa6c210c1007fc46a2a0bd698e9cb6167", + "percent": 97.91666666666667 + }, + "internal/service/production/access.go": { + "statements": 27, + "covered": 27, + "sha256": "fc191b98aaf0488cb60f258c3ce9788708818c7f299a10f80e91568adabd05e5", + "percent": 100.0 + }, + "internal/service/production/chats.go": { + "statements": 22, + "covered": 22, + "sha256": "881f9269ad84ab5dc091fdec8ad6c36bebd2eaac0da0685b8d333216e0a2dd16", + "percent": 100.0 + }, + "internal/service/production/creation.go": { + "statements": 12, + "covered": 12, + "sha256": "fe5940f705df32902151d51f82c7f9f1df3e274e62413d9e1b54f2a512707d48", + "percent": 100.0 + }, + "internal/service/production/errors.go": { + "statements": 5, + "covered": 5, + "sha256": "7495818188cc13028d9400dfa18005e9aa334ac048b7a84150dd2b6ddb28d796", + "percent": 100.0 + }, + "internal/service/production/members.go": { + "statements": 19, + "covered": 19, + "sha256": "1f5c9335bf4cf5b9f4137454e3ca22975e7c6c7118e4e60bb470851f8a7cd61e", + "percent": 100.0 + }, + "internal/service/production/messages.go": { + "statements": 18, + "covered": 18, + "sha256": "6bdd523dd8be7ce139a0a7f2c9ee16d8d2f03e4d15ed00e7a31658c23fb97c17", + "percent": 100.0 + }, + "internal/service/production/pages.go": { + "statements": 17, + "covered": 16, + "sha256": "4306cd592bdcd2dd5c31eeadc0dc5e1a59b275ffa6de091032edf644171020c5", + "percent": 94.11764705882354 + }, + "internal/service/production/pagination.go": { + "statements": 21, + "covered": 21, + "sha256": "4cb0d47ef9cc020e608f93a8257b6d65136f6f74b86c3f591f19dad688fc7bf0", + "percent": 100.0 + }, + "internal/service/production/service.go": { + "statements": 10, + "covered": 10, + "sha256": "70fb90d812432e321c4fca1b1e2141cfad91453e294f4efda60c0898be686d7d", + "percent": 100.0 + }, + "internal/service/production/users.go": { + "statements": 19, + "covered": 19, + "sha256": "50d873980bdc97a799c2e61a4b25c5bd222a32bd7baed28590510ef373ac0461", + "percent": 100.0 + }, + "internal/service/production/validation.go": { + "statements": 13, + "covered": 13, + "sha256": "6aa0ff490fe8fca8b906b5073e0914a64369ddfc7d0648d895cc41cb69cdd2e0", + "percent": 100.0 + }, + "internal/store/memory/capacity.go": { + "statements": 7, + "covered": 7, + "sha256": "ac2aafe9f19706ff39b16a4ca1b1e142f6e52bef160ef591f9f2120d106ffd51", + "percent": 100.0 + }, + "internal/store/memory/chats.go": { + "statements": 31, + "covered": 31, + "sha256": "150851ac6a0d5da8835a9aaaa7c1156b075e5e3dd962698fb483b0afa8a2097f", + "percent": 100.0 + }, + "internal/store/memory/messages.go": { + "statements": 19, + "covered": 18, + "sha256": "94f2a5ce429aa8280e1333760309fd1d02b314310cbdea495aef56a63ed145b1", + "percent": 94.73684210526316 + }, + "internal/store/memory/ordering.go": { + "statements": 6, + "covered": 6, + "sha256": "4aef07be1cb907cfa7a4a3d78060d8be57c9ff566c16e729dea9b0db68c7dfae", + "percent": 100.0 + }, + "internal/store/memory/store.go": { + "statements": 3, + "covered": 3, + "sha256": "f463d530955bfe5793fb9a4ad93d6615a3ce923d1d4719b8c515f487c96997ca", + "percent": 100.0 + }, + "internal/store/memory/users.go": { + "statements": 22, + "covered": 21, + "sha256": "1652a23bc8fc29a6ef00851a19d4547b660f3bfcce9d458b7381db5b3f30778c", + "percent": 95.45454545454545 + }, + "internal/store/postgres/chats.go": { + "statements": 26, + "covered": 24, + "sha256": "b9d69046cd919957434da02c635d259c8e36f27371270afedc312947eb5bb615", + "percent": 92.3076923076923 + }, + "internal/store/postgres/messages.go": { + "statements": 21, + "covered": 20, + "sha256": "1ab5dd2f8d81697a57ee89e1969995e52bfccc0f3f25a5c480822e41313988f1", + "percent": 95.23809523809524 + }, + "internal/store/postgres/sessions.go": { + "statements": 13, + "covered": 13, + "sha256": "6f7f2e86822d806640888da990716279659fe90e5a74b3b0d5454a5155d0334b", + "percent": 100.0 + }, + "internal/store/postgres/store.go": { + "statements": 39, + "covered": 36, + "sha256": "5f3e022a414103198a1ab8e62f337e67c22afd1afddda400884b79a5e51488a2", + "percent": 92.3076923076923 + }, + "internal/store/postgres/users.go": { + "statements": 21, + "covered": 20, + "sha256": "2721381975755efe2a4f14a8df3c1189d2dcc6c7933fc25292977014c26aa220", + "percent": 95.23809523809524 + }, + "internal/strictjson/decode.go": { + "statements": 37, + "covered": 36, + "sha256": "ef9bfaf3bd684fded87c92a15b3e5c706a794caf04cc4ef711c4185e9c7fb12a", + "percent": 97.29729729729729 + }, + "internal/valkey/admission.go": { + "statements": 45, + "covered": 45, + "sha256": "4baa4e399be201189371d1ace6169e56958251386624af4996fac04e0ab5d1f7", + "percent": 100.0 + }, + "internal/valkey/cache.go": { + "statements": 19, + "covered": 18, + "sha256": "693b866a740b6d5f765221be4c6489391821d4b58942cf0ff36030163dbae6a9", + "percent": 94.73684210526316 + }, + "internal/valkey/client.go": { + "statements": 35, + "covered": 34, + "sha256": "86acf0827e1d29993eda7ee62a8fa42b02d707330a94a70f5a3933911407e882", + "percent": 97.14285714285714 + }, + "internal/admission/distributed.go": { + "statements": 0, + "covered": 0, + "sha256": "41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d", + "percent": null + }, + "internal/controller/http/fiber/dependencies.go": { + "statements": 0, + "covered": 0, + "sha256": "6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d", + "percent": null + }, + "internal/controller/http/fiber/error_codes.go": { + "statements": 0, + "covered": 0, + "sha256": "3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41", + "percent": null + }, + "internal/controller/http/fiber/headers.go": { + "statements": 0, + "covered": 0, + "sha256": "d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd", + "percent": null + }, + "internal/controller/interface.go": { + "statements": 0, + "covered": 0, + "sha256": "24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68", + "percent": null + }, + "internal/model/dto/models.go": { + "statements": 0, + "covered": 0, + "sha256": "e2ecd732848d10f4471567c9603aa7359fcb1af7b2708ead477f4949f7a2fa4a", + "percent": null + }, + "internal/model/dto/session.go": { + "statements": 0, + "covered": 0, + "sha256": "896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb", + "percent": null + }, + "internal/model/http/models.go": { + "statements": 0, + "covered": 0, + "sha256": "8c183b065bc3ab4cad20570eab79f334ca75a3309186fdf832fb1aa598894465", + "percent": null + }, + "internal/service/auth.go": { + "statements": 0, + "covered": 0, + "sha256": "ede0474befff6773779dd448e9b42a98bd2edb12033b65366e5f65618ec4885e", + "percent": null + }, + "internal/service/cache.go": { + "statements": 0, + "covered": 0, + "sha256": "55baf7ba65292ae6a75b7a6af8d304886f35c7ad854b8d700251d6f32c964dbf", + "percent": null + }, + "internal/service/cursor.go": { + "statements": 0, + "covered": 0, + "sha256": "07244e89d9948087318df2dfecfb3a648c217bc313fb033748f5562e08ba8a95", + "percent": null + }, + "internal/service/errors.go": { + "statements": 0, + "covered": 0, + "sha256": "e19c47379f63a5ee7e24b9b0fded1eb326ea231392b4e27c324d205d4c620f7d", + "percent": null + }, + "internal/service/interface.go": { + "statements": 0, + "covered": 0, + "sha256": "017b13007719a32a8eec26527848231381590e5632790bedec66a126776bad6e", + "percent": null + }, + "internal/store/interface.go": { + "statements": 0, + "covered": 0, + "sha256": "ea599de0e0d2a0be7de7b0835307a4d1852db16a49bfad3636f7c30b85181fce", + "percent": null + } + }, + "failures": [] +} diff --git a/evidence/dependencies.json b/evidence/dependencies.json new file mode 100644 index 00000000..49be96e0 --- /dev/null +++ b/evidence/dependencies.json @@ -0,0 +1,25 @@ +{ + "date_utc": "2026-10-07T12:13:17.044405+00:00", + "checks": [ + "wrong_password_401", + "legacy_header_rejected", + "basic_rejected_for_business", + "short_ttl_expiry_401", + "postgres_failure_and_recovery", + "valkey_coordinator_failure_and_recovery", + "logout_401" + ], + "faults": [ + { + "role": "postgres", + "status": 500, + "seconds": 0.010046916984720156 + }, + { + "role": "valkey_coordinator", + "status": 503, + "seconds": 0.5187327080057003 + } + ], + "scope": "Explicitly owned local Docker containers; synthetic data only; no cluster workloads changed." +} diff --git a/evidence/dependencies.txt b/evidence/dependencies.txt new file mode 100644 index 00000000..0d0e0fe5 --- /dev/null +++ b/evidence/dependencies.txt @@ -0,0 +1 @@ +PASS: wrong_password_401, legacy_header_rejected, basic_rejected_for_business, short_ttl_expiry_401, postgres_failure_and_recovery, valkey_coordinator_failure_and_recovery, logout_401 diff --git a/evidence/docker-restart.sh b/evidence/docker-restart.sh new file mode 100755 index 00000000..77e23246 --- /dev/null +++ b/evidence/docker-restart.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +docker stop lab2-codex-api >/dev/null +docker restart lab2-codex-pg lab2-codex-valkey-0 lab2-codex-valkey-1 lab2-codex-valkey-2 >/dev/null +docker start lab2-codex-api >/dev/null diff --git a/evidence/environment.json b/evidence/environment.json new file mode 100644 index 00000000..6cf68849 --- /dev/null +++ b/evidence/environment.json @@ -0,0 +1,310 @@ +{ + "date_utc": "2026-10-07T12:16:37.046450+00:00", + "source_snapshot_sha256": "e15a4539d3e22949b09832f04949b11445fe7ac4867ad380b99b49963dece070", + "source_files_sha256": { + "cmd/server/app.go": "2c8e791d08fca312f52a40e082b18dc82676e891df57c04fbca1334d5edcfa26", + "cmd/server/app_test.go": "8fabb622999b681eb42452bfd349f71b53ad979e41f2ae57189d34c099bb3ee2", + "cmd/server/commands.go": "7290636ea31539d87bd97bb78cb28658409da966be8983e748ce1701f6f9f8f6", + "cmd/server/healthcheck.go": "b0a0c1689dfe2db5abc889af13d7adb00a1d4f3d260b5ebe6d5f529cb5983a0e", + "cmd/server/healthcheck_test.go": "900039906536a81de51dc45af3904a7e44b4739d56690dd59f915d03d092c7e9", + "cmd/server/logger.go": "43ad9caf2260d8551b8b3e149681c5e66770e9901d72de41b81746cb0cac47ec", + "cmd/server/main.go": "c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495", + "cmd/server/persistence.go": "06b304d8f0cad20c206edbef8becab283c50c1722fd81c56a06f018dfe03bb7f", + "cmd/server/persistence_test.go": "aaf096a8c0abb9e6860d5cd620a5b0580c130276374a09f21ac3a7790273385f", + "internal/admission/distributed.go": "41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d", + "internal/admission/limiter.go": "a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4", + "internal/admission/limiter_test.go": "d52fb501e76ddb23c645c1aaa599e32da9d01e50064c9ca97ac0e320ffc7f0c8", + "internal/config/config.go": "8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa", + "internal/config/config_test.go": "0181673dcc4db2557783941aa8c5b3f61bc0ca6b5196d87e69df000346c40391", + "internal/config/controller.go": "e784d7b934c4604065cd00bf4ff2b0c74741e759b1b7c81162adfc206d160153", + "internal/config/environment.go": "027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3", + "internal/config/logger.go": "3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988", + "internal/config/memory.go": "86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0", + "internal/config/persistence.go": "671f92c52c827989ce194f3928b02f707292022bb97d3c483410e97cf626b4af", + "internal/config/persistence_test.go": "7377c7fc286e04292b7c82e4e286cadf409ce833079f794a501456024e73434a", + "internal/controller/fx.go": "af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a", + "internal/controller/http/fiber/auth.go": "3107673b329dbe7934a29679024a18e3baada2cc99bee4d0ddbba0f9fd93edf9", + "internal/controller/http/fiber/auth_test.go": "960cd6ea803ea4ef9b0231ce557fc5e792921aae343f33da6e8aca12495da39f", + "internal/controller/http/fiber/chats_test.go": "9c092ba7bca191f25c3ba9c9a5d1ca844126bee740a4c0262b776e947263ac68", + "internal/controller/http/fiber/configure.go": "be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd", + "internal/controller/http/fiber/controller.go": "fd0d06ac838c8ceca1189303b98ce006ca1298381de49fe6d790d0f0f4007d3e", + "internal/controller/http/fiber/controller_test.go": "151fb360bc3f7309678961b7739c5d905f3430bc4e63fb6c9b26495e12ab7227", + "internal/controller/http/fiber/decode.go": "bb4216cb6c5813b66b51dc99a53f8cf09982789155305a099c321dd12fa8e2de", + "internal/controller/http/fiber/dependencies.go": "6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d", + "internal/controller/http/fiber/error_codes.go": "3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41", + "internal/controller/http/fiber/error_registry.go": "9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a", + "internal/controller/http/fiber/errors.go": "d502e2a9f7fe3980c10c2760c31711794898c539d07b43b02497dc2cfb870358", + "internal/controller/http/fiber/errors_test.go": "81e95e02b6e41929bf8e73f65e2d4921fc6471293815d590d38ad7d849106f3c", + "internal/controller/http/fiber/fixtures_auth_test.go": "49bb58b260f2df9473d8e0ae01b8c3c742e4266db00d64fe5e999730aba42a80", + "internal/controller/http/fiber/handlers.go": "13a4b3b69977517e0497e99a01f21bf757e910c5d2b69bd473b7954c96ff6789", + "internal/controller/http/fiber/headers.go": "d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd", + "internal/controller/http/fiber/health.go": "6d18f3c4be98e70a7e61d82b014b6db9b3a5e594c9b5f50ecea88f89bd6917cd", + "internal/controller/http/fiber/lifecycle.go": "f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08", + "internal/controller/http/fiber/lifecycle_test.go": "496f50e5693456574614b8a47086a550018884adb37919ce82abf8c4e7e5254d", + "internal/controller/http/fiber/mapping.go": "f63d4b0e2ee5f62c4d0d8c4b26a8734d68230af4577e3c6cb71a92525c3c8681", + "internal/controller/http/fiber/messages_test.go": "d848e00aff04d7a3339ca1847f47cad59fb7c05085f6cfb1965b27df516acdd6", + "internal/controller/http/fiber/middleware.go": "34fd687af80730601ba9276ef606fee76df84d14b4400a65ec5b804897673536", + "internal/controller/http/fiber/middleware_test.go": "5259d44ea6c7d4e1776f5b66e00408d1450fdf859e2017bf14937d3020f3dcff", + "internal/controller/http/fiber/public_errors.go": "d806c2d026a8ff2fc54d60b62c062e80a3532e652fcfa5c3105684ba17cc9f67", + "internal/controller/http/fiber/public_errors_test.go": "47089b63442f02d6e637a8dd785e323e97efb15fd82d2ffa303e7e10de4876cd", + "internal/controller/http/fiber/routes.go": "826fe61b8d59465de7190c175b6abaa118f4a7deacdb1b9c628e25bb7f4feb3b", + "internal/controller/http/fiber/users_test.go": "0b3fad8fc87f561573bf4ee906a48a8fb317385ecc7600bdca3cc61992fa9253", + "internal/controller/interface.go": "24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68", + "internal/cursor/codec.go": "a5bc7aac6d1764929fb11365c9f8b6a45ff65e47b3a317a7ccd9ec6dd1b2713a", + "internal/cursor/codec_test.go": "a611b59197a205fd21fd94077577f2db7024266cd5ce8a5bfb18a85196bd357b", + "internal/hashring/ring.go": "e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c", + "internal/hashring/ring_test.go": "606cdf84342b97a63eedfb9cd37aa7c99a489eee54641d8645be930a9ce6be0d", + "internal/model/dto/models.go": "ca833e3314680322fb4464b62b102aa07710b71ff0301d351dc035d96173c4f3", + "internal/model/dto/session.go": "896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb", + "internal/model/http/models.go": "8c183b065bc3ab4cad20570eab79f334ca75a3309186fdf832fb1aa598894465", + "internal/password/password.go": "fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76", + "internal/password/password_test.go": "1ad8dcb7d055fcb8da56d10e1089b47fe1b9cbf848381ded1a4048f8fd41278a", + "internal/service/auth.go": "ede0474befff6773779dd448e9b42a98bd2edb12033b65366e5f65618ec4885e", + "internal/service/authentication/service.go": "1cc82be87998dc9b66216965dc3ac37aa6c210c1007fc46a2a0bd698e9cb6167", + "internal/service/authentication/service_test.go": "c77137c6799dc1f9012387e45c21414ced2d7e0923b6f2750a09f61b76c6523a", + "internal/service/cache.go": "55baf7ba65292ae6a75b7a6af8d304886f35c7ad854b8d700251d6f32c964dbf", + "internal/service/cursor.go": "07244e89d9948087318df2dfecfb3a648c217bc313fb033748f5562e08ba8a95", + "internal/service/errors.go": "e19c47379f63a5ee7e24b9b0fded1eb326ea231392b4e27c324d205d4c620f7d", + "internal/service/interface.go": "3ccde6c8d0b5dedcaff1c548cbe15ef7038ad3b702eb31acb949805420bc9dad", + "internal/service/production/access.go": "fc191b98aaf0488cb60f258c3ce9788708818c7f299a10f80e91568adabd05e5", + "internal/service/production/cache_test.go": "af0659140715e467ab15388cc75aea8b2ff09b8edbbd5dc90aa6d3f5c24bf5bf", + "internal/service/production/chats.go": "881f9269ad84ab5dc091fdec8ad6c36bebd2eaac0da0685b8d333216e0a2dd16", + "internal/service/production/chats_page_test.go": "8eb5b603aeb7be2d5e5af859762610e26c8ad7c05fa222e04802950dd71f9c21", + "internal/service/production/chats_test.go": "e7d4fa61a14f7cb4ba421ed5e83d794a85b42fac597e269807d564c830e2cbb8", + "internal/service/production/creation.go": "fe5940f705df32902151d51f82c7f9f1df3e274e62413d9e1b54f2a512707d48", + "internal/service/production/errors.go": "7495818188cc13028d9400dfa18005e9aa334ac048b7a84150dd2b6ddb28d796", + "internal/service/production/fixture_test.go": "007b27ba3005a3040283b35b7640523bc8ae04ada89b2731396b1559c3b20075", + "internal/service/production/members.go": "1f5c9335bf4cf5b9f4137454e3ca22975e7c6c7118e4e60bb470851f8a7cd61e", + "internal/service/production/messages.go": "6bdd523dd8be7ce139a0a7f2c9ee16d8d2f03e4d15ed00e7a31658c23fb97c17", + "internal/service/production/messages_page_test.go": "7b82f74aedb2f26079cce497778302246e9166c365508e37266a97078df5ca5c", + "internal/service/production/messages_test.go": "6722838a6c117f76fb2710d664ec4ce9945479f18013af18437cf93814351d93", + "internal/service/production/pages.go": "4306cd592bdcd2dd5c31eeadc0dc5e1a59b275ffa6de091032edf644171020c5", + "internal/service/production/pages_test.go": "f0611bc8ad150fcac5505a6696bd293a144274431fb71b3e96f16a8229b85bcc", + "internal/service/production/pagination.go": "4cb0d47ef9cc020e608f93a8257b6d65136f6f74b86c3f591f19dad688fc7bf0", + "internal/service/production/pagination_test.go": "1886cbbaa88de20d0e21bf6c1c35fde64164547fa86c1fb74860c93f59b5fc9b", + "internal/service/production/service.go": "70fb90d812432e321c4fca1b1e2141cfad91453e294f4efda60c0898be686d7d", + "internal/service/production/service_test.go": "b8ab1e6e92a365f38fb5ac660e311a00fea6a458c6c9cd9c8184dbaebb419f50", + "internal/service/production/users.go": "50d873980bdc97a799c2e61a4b25c5bd222a32bd7baed28590510ef373ac0461", + "internal/service/production/users_test.go": "04e0cb7a51877014ef23a8063ca435e3eb5e98fb78902ff166abc08139287315", + "internal/service/production/validation.go": "6aa0ff490fe8fca8b906b5073e0914a64369ddfc7d0648d895cc41cb69cdd2e0", + "internal/store/interface.go": "ea599de0e0d2a0be7de7b0835307a4d1852db16a49bfad3636f7c30b85181fce", + "internal/store/memory/capacity.go": "ac2aafe9f19706ff39b16a4ca1b1e142f6e52bef160ef591f9f2120d106ffd51", + "internal/store/memory/chats.go": "150851ac6a0d5da8835a9aaaa7c1156b075e5e3dd962698fb483b0afa8a2097f", + "internal/store/memory/chats_test.go": "3036029e86462d8cf52aad993c4f9eff62a5cf0454e757b871abfd5b4902c9f5", + "internal/store/memory/messages.go": "94f2a5ce429aa8280e1333760309fd1d02b314310cbdea495aef56a63ed145b1", + "internal/store/memory/messages_test.go": "76f977bbabec7550093ca9d376efc9686345198cbee5e13ce31d38dcd425a469", + "internal/store/memory/ordering.go": "4aef07be1cb907cfa7a4a3d78060d8be57c9ff566c16e729dea9b0db68c7dfae", + "internal/store/memory/store.go": "f463d530955bfe5793fb9a4ad93d6615a3ce923d1d4719b8c515f487c96997ca", + "internal/store/memory/store_test.go": "b7f8237e22eac473ad47cd879238aed7ed16e08b28a6ff3029ddcc58072dfe0e", + "internal/store/memory/users.go": "1652a23bc8fc29a6ef00851a19d4547b660f3bfcce9d458b7381db5b3f30778c", + "internal/store/memory/users_test.go": "dc9a73504116b7e54d38a4e3b8c88ed1aa4c1144efdb9bb3ac671e0e1182d9a3", + "internal/store/postgres/chats.go": "b9d69046cd919957434da02c635d259c8e36f27371270afedc312947eb5bb615", + "internal/store/postgres/messages.go": "1ab5dd2f8d81697a57ee89e1969995e52bfccc0f3f25a5c480822e41313988f1", + "internal/store/postgres/migrations/001_initial.sql": "8b8bf6a255cc48cee4b3e4adc94c23cf6955ecf5dfba689bba973dfccbd1b1cb", + "internal/store/postgres/sessions.go": "6f7f2e86822d806640888da990716279659fe90e5a74b3b0d5454a5155d0334b", + "internal/store/postgres/store.go": "5f3e022a414103198a1ab8e62f337e67c22afd1afddda400884b79a5e51488a2", + "internal/store/postgres/store_test.go": "538f1739eae4c276aa6b5df9aa8c4f4c3aca4a3043a71650256f257ffaaed029", + "internal/store/postgres/users.go": "2721381975755efe2a4f14a8df3c1189d2dcc6c7933fc25292977014c26aa220", + "internal/strictjson/decode.go": "ef9bfaf3bd684fded87c92a15b3e5c706a794caf04cc4ef711c4185e9c7fb12a", + "internal/strictjson/decode_test.go": "ea6273526572b4bfcf681ef2659ea2c1ec74bfedeb5e9bdbd83ebfabe0647bf9", + "internal/valkey/admission.go": "4baa4e399be201189371d1ace6169e56958251386624af4996fac04e0ab5d1f7", + "internal/valkey/cache.go": "693b866a740b6d5f765221be4c6489391821d4b58942cf0ff36030163dbae6a9", + "internal/valkey/client.go": "86acf0827e1d29993eda7ee62a8fa42b02d707330a94a70f5a3933911407e882", + "internal/valkey/client_test.go": "b39e08ecc720e1d4fc81d342fa15192c0a0a82e849231161c1e0d2da2d8f625d" + }, + "host": { + "os": "Darwin", + "architecture": "arm64" + }, + "docker": { + "version": "27.5.1", + "cpus": 4, + "memory_bytes": 9365356544 + }, + "containers": [ + { + "name": "/lab2-codex-api", + "image_id": "sha256:bfec77a7c61e34f5c29804fd58f7c05fe7f59cbb2ed1ac50f24fdca5fa992608", + "image_tag": "mtusi-messenger:lab2", + "memory_bytes": 268435456, + "nano_cpus": 1000000000, + "owner": "lab2-codex" + }, + { + "name": "/lab2-codex-expiry", + "image_id": "sha256:bfec77a7c61e34f5c29804fd58f7c05fe7f59cbb2ed1ac50f24fdca5fa992608", + "image_tag": "mtusi-messenger:lab2", + "memory_bytes": 268435456, + "nano_cpus": 1000000000, + "owner": "lab2-codex" + }, + { + "name": "/lab2-codex-pg", + "image_id": "sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94", + "image_tag": "postgres:17.6-alpine", + "memory_bytes": 0, + "nano_cpus": 0, + "owner": "lab2-codex" + }, + { + "name": "/lab2-codex-valkey-0", + "image_id": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "image_tag": "valkey/valkey:8.1.3-alpine", + "memory_bytes": 0, + "nano_cpus": 0, + "owner": "lab2-codex" + }, + { + "name": "/lab2-codex-valkey-1", + "image_id": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "image_tag": "valkey/valkey:8.1.3-alpine", + "memory_bytes": 0, + "nano_cpus": 0, + "owner": "lab2-codex" + }, + { + "name": "/lab2-codex-valkey-2", + "image_id": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "image_tag": "valkey/valkey:8.1.3-alpine", + "memory_bytes": 0, + "nano_cpus": 0, + "owner": "lab2-codex" + } + ], + "commands": [ + "make check", + "go vet ./...", + "golangci-lint run ./...", + "python3 scripts/coverage.py", + "docker build -t mtusi-messenger:lab2 .", + "python3 tests/smoke.py --base-url http://localhost:28081", + "python3 tests/resilience.py --mode persistence --action-script evidence/docker-restart.sh --base-url http://localhost:28081", + "python3 scripts/verify-dependencies.py --base-url http://localhost:28081 --expiry-url http://localhost:28082 --postgres lab2-codex-pg --valkey lab2-codex-valkey-0 --owner-label lab2-codex", + "python3 scripts/research.py --container lab2-codex-pg --output evidence/sql-research-domain.json", + "python3 scripts/sample-load.py --base-url http://localhost:28081 --duration 10 --concurrency 4 --containers lab2-codex-api lab2-codex-pg lab2-codex-valkey-0 lab2-codex-valkey-1 lab2-codex-valkey-2" + ], + "limits": [ + "PostgreSQL and Valkey containers have no explicit cgroup CPU/RAM cap in this local experiment; Docker host bounds apply. Valkey maxmemory=64mb,noeviction,AOF appendfsync always.", + "API: one CPU,256MiB,read-only filesystem,drop capabilities.", + "SQL measurement preceded final admission/config changes; its own source snapshot remains in sql-research-domain.json.", + "Kubernetes manifests parsed as YAML; no cluster apply, rollout or scaling experiment performed.", + "Go local tests: 1.27.1; runtime image: 1.26.1; remote CI not run.", + "After container fault/load runs, only Go comments, test skip guards, and removal of unused Cobra dependencies changed; current files have fresh race/process/smoke/per-file coverage. Original container IDs and measurement snapshots are retained." + ], + "final_go_verification_snapshot_sha256": "5a20eb5c9a0e03c77eb1f188628947738071edc0e511c898f1d9f11dce34255a", + "final_go_verification_files_sha256": { + "cmd/server/app.go": "2c8e791d08fca312f52a40e082b18dc82676e891df57c04fbca1334d5edcfa26", + "cmd/server/app_test.go": "8fabb622999b681eb42452bfd349f71b53ad979e41f2ae57189d34c099bb3ee2", + "cmd/server/commands.go": "7290636ea31539d87bd97bb78cb28658409da966be8983e748ce1701f6f9f8f6", + "cmd/server/healthcheck.go": "b0a0c1689dfe2db5abc889af13d7adb00a1d4f3d260b5ebe6d5f529cb5983a0e", + "cmd/server/healthcheck_test.go": "900039906536a81de51dc45af3904a7e44b4739d56690dd59f915d03d092c7e9", + "cmd/server/logger.go": "43ad9caf2260d8551b8b3e149681c5e66770e9901d72de41b81746cb0cac47ec", + "cmd/server/main.go": "c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495", + "cmd/server/persistence.go": "06b304d8f0cad20c206edbef8becab283c50c1722fd81c56a06f018dfe03bb7f", + "cmd/server/persistence_test.go": "aaf096a8c0abb9e6860d5cd620a5b0580c130276374a09f21ac3a7790273385f", + "internal/admission/distributed.go": "41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d", + "internal/admission/limiter.go": "a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4", + "internal/admission/limiter_test.go": "d52fb501e76ddb23c645c1aaa599e32da9d01e50064c9ca97ac0e320ffc7f0c8", + "internal/config/config.go": "8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa", + "internal/config/config_test.go": "0181673dcc4db2557783941aa8c5b3f61bc0ca6b5196d87e69df000346c40391", + "internal/config/controller.go": "e784d7b934c4604065cd00bf4ff2b0c74741e759b1b7c81162adfc206d160153", + "internal/config/environment.go": "027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3", + "internal/config/logger.go": "3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988", + "internal/config/memory.go": "86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0", + "internal/config/persistence.go": "671f92c52c827989ce194f3928b02f707292022bb97d3c483410e97cf626b4af", + "internal/config/persistence_test.go": "7377c7fc286e04292b7c82e4e286cadf409ce833079f794a501456024e73434a", + "internal/controller/fx.go": "af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a", + "internal/controller/http/fiber/auth.go": "3107673b329dbe7934a29679024a18e3baada2cc99bee4d0ddbba0f9fd93edf9", + "internal/controller/http/fiber/auth_test.go": "960cd6ea803ea4ef9b0231ce557fc5e792921aae343f33da6e8aca12495da39f", + "internal/controller/http/fiber/chats_test.go": "9c092ba7bca191f25c3ba9c9a5d1ca844126bee740a4c0262b776e947263ac68", + "internal/controller/http/fiber/configure.go": "be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd", + "internal/controller/http/fiber/controller.go": "fd0d06ac838c8ceca1189303b98ce006ca1298381de49fe6d790d0f0f4007d3e", + "internal/controller/http/fiber/controller_test.go": "151fb360bc3f7309678961b7739c5d905f3430bc4e63fb6c9b26495e12ab7227", + "internal/controller/http/fiber/decode.go": "bb4216cb6c5813b66b51dc99a53f8cf09982789155305a099c321dd12fa8e2de", + "internal/controller/http/fiber/dependencies.go": "6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d", + "internal/controller/http/fiber/error_codes.go": "3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41", + "internal/controller/http/fiber/error_registry.go": "9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a", + "internal/controller/http/fiber/errors.go": "d502e2a9f7fe3980c10c2760c31711794898c539d07b43b02497dc2cfb870358", + "internal/controller/http/fiber/errors_test.go": "81e95e02b6e41929bf8e73f65e2d4921fc6471293815d590d38ad7d849106f3c", + "internal/controller/http/fiber/fixtures_auth_test.go": "49bb58b260f2df9473d8e0ae01b8c3c742e4266db00d64fe5e999730aba42a80", + "internal/controller/http/fiber/handlers.go": "59e3f16adc94b7426c74e2f40b5ff18a9129c80fc619cb8144110bdeec095021", + "internal/controller/http/fiber/headers.go": "d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd", + "internal/controller/http/fiber/health.go": "6d18f3c4be98e70a7e61d82b014b6db9b3a5e594c9b5f50ecea88f89bd6917cd", + "internal/controller/http/fiber/lifecycle.go": "f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08", + "internal/controller/http/fiber/lifecycle_test.go": "496f50e5693456574614b8a47086a550018884adb37919ce82abf8c4e7e5254d", + "internal/controller/http/fiber/mapping.go": "f63d4b0e2ee5f62c4d0d8c4b26a8734d68230af4577e3c6cb71a92525c3c8681", + "internal/controller/http/fiber/messages_test.go": "d848e00aff04d7a3339ca1847f47cad59fb7c05085f6cfb1965b27df516acdd6", + "internal/controller/http/fiber/middleware.go": "34fd687af80730601ba9276ef606fee76df84d14b4400a65ec5b804897673536", + "internal/controller/http/fiber/middleware_test.go": "5259d44ea6c7d4e1776f5b66e00408d1450fdf859e2017bf14937d3020f3dcff", + "internal/controller/http/fiber/public_errors.go": "d806c2d026a8ff2fc54d60b62c062e80a3532e652fcfa5c3105684ba17cc9f67", + "internal/controller/http/fiber/public_errors_test.go": "47089b63442f02d6e637a8dd785e323e97efb15fd82d2ffa303e7e10de4876cd", + "internal/controller/http/fiber/routes.go": "826fe61b8d59465de7190c175b6abaa118f4a7deacdb1b9c628e25bb7f4feb3b", + "internal/controller/http/fiber/users_test.go": "0b3fad8fc87f561573bf4ee906a48a8fb317385ecc7600bdca3cc61992fa9253", + "internal/controller/interface.go": "24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68", + "internal/cursor/codec.go": "a5bc7aac6d1764929fb11365c9f8b6a45ff65e47b3a317a7ccd9ec6dd1b2713a", + "internal/cursor/codec_test.go": "a611b59197a205fd21fd94077577f2db7024266cd5ce8a5bfb18a85196bd357b", + "internal/hashring/ring.go": "e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c", + "internal/hashring/ring_test.go": "606cdf84342b97a63eedfb9cd37aa7c99a489eee54641d8645be930a9ce6be0d", + "internal/model/dto/models.go": "e2ecd732848d10f4471567c9603aa7359fcb1af7b2708ead477f4949f7a2fa4a", + "internal/model/dto/session.go": "896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb", + "internal/model/http/models.go": "8c183b065bc3ab4cad20570eab79f334ca75a3309186fdf832fb1aa598894465", + "internal/password/password.go": "fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76", + "internal/password/password_test.go": "1ad8dcb7d055fcb8da56d10e1089b47fe1b9cbf848381ded1a4048f8fd41278a", + "internal/service/auth.go": "ede0474befff6773779dd448e9b42a98bd2edb12033b65366e5f65618ec4885e", + "internal/service/authentication/service.go": "1cc82be87998dc9b66216965dc3ac37aa6c210c1007fc46a2a0bd698e9cb6167", + "internal/service/authentication/service_test.go": "c77137c6799dc1f9012387e45c21414ced2d7e0923b6f2750a09f61b76c6523a", + "internal/service/cache.go": "55baf7ba65292ae6a75b7a6af8d304886f35c7ad854b8d700251d6f32c964dbf", + "internal/service/cursor.go": "07244e89d9948087318df2dfecfb3a648c217bc313fb033748f5562e08ba8a95", + "internal/service/errors.go": "e19c47379f63a5ee7e24b9b0fded1eb326ea231392b4e27c324d205d4c620f7d", + "internal/service/interface.go": "017b13007719a32a8eec26527848231381590e5632790bedec66a126776bad6e", + "internal/service/production/access.go": "fc191b98aaf0488cb60f258c3ce9788708818c7f299a10f80e91568adabd05e5", + "internal/service/production/cache_test.go": "af0659140715e467ab15388cc75aea8b2ff09b8edbbd5dc90aa6d3f5c24bf5bf", + "internal/service/production/chats.go": "881f9269ad84ab5dc091fdec8ad6c36bebd2eaac0da0685b8d333216e0a2dd16", + "internal/service/production/chats_page_test.go": "8eb5b603aeb7be2d5e5af859762610e26c8ad7c05fa222e04802950dd71f9c21", + "internal/service/production/chats_test.go": "e7d4fa61a14f7cb4ba421ed5e83d794a85b42fac597e269807d564c830e2cbb8", + "internal/service/production/creation.go": "fe5940f705df32902151d51f82c7f9f1df3e274e62413d9e1b54f2a512707d48", + "internal/service/production/errors.go": "7495818188cc13028d9400dfa18005e9aa334ac048b7a84150dd2b6ddb28d796", + "internal/service/production/fixture_test.go": "007b27ba3005a3040283b35b7640523bc8ae04ada89b2731396b1559c3b20075", + "internal/service/production/members.go": "1f5c9335bf4cf5b9f4137454e3ca22975e7c6c7118e4e60bb470851f8a7cd61e", + "internal/service/production/messages.go": "6bdd523dd8be7ce139a0a7f2c9ee16d8d2f03e4d15ed00e7a31658c23fb97c17", + "internal/service/production/messages_page_test.go": "7b82f74aedb2f26079cce497778302246e9166c365508e37266a97078df5ca5c", + "internal/service/production/messages_test.go": "6722838a6c117f76fb2710d664ec4ce9945479f18013af18437cf93814351d93", + "internal/service/production/pages.go": "4306cd592bdcd2dd5c31eeadc0dc5e1a59b275ffa6de091032edf644171020c5", + "internal/service/production/pages_test.go": "f0611bc8ad150fcac5505a6696bd293a144274431fb71b3e96f16a8229b85bcc", + "internal/service/production/pagination.go": "4cb0d47ef9cc020e608f93a8257b6d65136f6f74b86c3f591f19dad688fc7bf0", + "internal/service/production/pagination_test.go": "1886cbbaa88de20d0e21bf6c1c35fde64164547fa86c1fb74860c93f59b5fc9b", + "internal/service/production/service.go": "70fb90d812432e321c4fca1b1e2141cfad91453e294f4efda60c0898be686d7d", + "internal/service/production/service_test.go": "b8ab1e6e92a365f38fb5ac660e311a00fea6a458c6c9cd9c8184dbaebb419f50", + "internal/service/production/users.go": "50d873980bdc97a799c2e61a4b25c5bd222a32bd7baed28590510ef373ac0461", + "internal/service/production/users_test.go": "04e0cb7a51877014ef23a8063ca435e3eb5e98fb78902ff166abc08139287315", + "internal/service/production/validation.go": "6aa0ff490fe8fca8b906b5073e0914a64369ddfc7d0648d895cc41cb69cdd2e0", + "internal/store/interface.go": "ea599de0e0d2a0be7de7b0835307a4d1852db16a49bfad3636f7c30b85181fce", + "internal/store/memory/capacity.go": "ac2aafe9f19706ff39b16a4ca1b1e142f6e52bef160ef591f9f2120d106ffd51", + "internal/store/memory/chats.go": "150851ac6a0d5da8835a9aaaa7c1156b075e5e3dd962698fb483b0afa8a2097f", + "internal/store/memory/chats_test.go": "3036029e86462d8cf52aad993c4f9eff62a5cf0454e757b871abfd5b4902c9f5", + "internal/store/memory/messages.go": "94f2a5ce429aa8280e1333760309fd1d02b314310cbdea495aef56a63ed145b1", + "internal/store/memory/messages_test.go": "76f977bbabec7550093ca9d376efc9686345198cbee5e13ce31d38dcd425a469", + "internal/store/memory/ordering.go": "4aef07be1cb907cfa7a4a3d78060d8be57c9ff566c16e729dea9b0db68c7dfae", + "internal/store/memory/store.go": "f463d530955bfe5793fb9a4ad93d6615a3ce923d1d4719b8c515f487c96997ca", + "internal/store/memory/store_test.go": "b7f8237e22eac473ad47cd879238aed7ed16e08b28a6ff3029ddcc58072dfe0e", + "internal/store/memory/users.go": "1652a23bc8fc29a6ef00851a19d4547b660f3bfcce9d458b7381db5b3f30778c", + "internal/store/memory/users_test.go": "dc9a73504116b7e54d38a4e3b8c88ed1aa4c1144efdb9bb3ac671e0e1182d9a3", + "internal/store/postgres/chats.go": "b9d69046cd919957434da02c635d259c8e36f27371270afedc312947eb5bb615", + "internal/store/postgres/messages.go": "1ab5dd2f8d81697a57ee89e1969995e52bfccc0f3f25a5c480822e41313988f1", + "internal/store/postgres/migrations/001_initial.sql": "8b8bf6a255cc48cee4b3e4adc94c23cf6955ecf5dfba689bba973dfccbd1b1cb", + "internal/store/postgres/sessions.go": "6f7f2e86822d806640888da990716279659fe90e5a74b3b0d5454a5155d0334b", + "internal/store/postgres/store.go": "5f3e022a414103198a1ab8e62f337e67c22afd1afddda400884b79a5e51488a2", + "internal/store/postgres/store_test.go": "538f1739eae4c276aa6b5df9aa8c4f4c3aca4a3043a71650256f257ffaaed029", + "internal/store/postgres/users.go": "2721381975755efe2a4f14a8df3c1189d2dcc6c7933fc25292977014c26aa220", + "internal/strictjson/decode.go": "ef9bfaf3bd684fded87c92a15b3e5c706a794caf04cc4ef711c4185e9c7fb12a", + "internal/strictjson/decode_test.go": "ea6273526572b4bfcf681ef2659ea2c1ec74bfedeb5e9bdbd83ebfabe0647bf9", + "internal/valkey/admission.go": "4baa4e399be201189371d1ace6169e56958251386624af4996fac04e0ab5d1f7", + "internal/valkey/cache.go": "693b866a740b6d5f765221be4c6489391821d4b58942cf0ff36030163dbae6a9", + "internal/valkey/client.go": "86acf0827e1d29993eda7ee62a8fa42b02d707330a94a70f5a3933911407e882", + "internal/valkey/client_test.go": "b39e08ecc720e1d4fc81d342fa15192c0a0a82e849231161c1e0d2da2d8f625d" + }, + "module_files_sha256": { + "go.mod": "d11057a32389466a7fae1eb0b4ad09440c2631db12908222a83378e2d0284ea9", + "go.sum": "d3449535c0ad9290b26a9a094daccaa695c7922efcfa7675a2c35d1f962193f6" + } +} diff --git a/evidence/fault-contract.txt b/evidence/fault-contract.txt new file mode 100644 index 00000000..9a553306 --- /dev/null +++ b/evidence/fault-contract.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/fault-coverage-per-file.json b/evidence/fault-coverage-per-file.json new file mode 100644 index 00000000..30bd5e1a --- /dev/null +++ b/evidence/fault-coverage-per-file.json @@ -0,0 +1,73 @@ +{"threshold_per_file":90,"files":[ +{"file":"internal/cursor/codec.go","statements":33,"covered":31,"percent":93.93939394,"sha256":"a5bc7aac6d1764929fb11365c9f8b6a45ff65e47b3a317a7ccd9ec6dd1b2713a"}, +{"file":"internal/valkey/client.go","statements":35,"covered":34,"percent":97.14285714,"sha256":"f50de7f2ac53fae218eb7c580436d5b726de5abe3a9cc6f9696f28b52ad6ec07"}, +{"file":"internal/controller/http/fiber/handlers.go","statements":37,"covered":36,"percent":97.29729730,"sha256":"b5473469ee1bd63610bc7b1bc167ecf01633dc5f06dae64b7816e8123ee0733e"}, +{"file":"internal/service/production/members.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"652833512d878ee000da0cdb278f25245a3ce79bf2c1638d62621126d881be25"}, +{"file":"internal/service/production/creation.go","statements":12,"covered":12,"percent":100.00000000,"sha256":"13f76cd64c9aec923504e077f1db74ff66a96fb72523dd5e1a2cc29efd0682d5"}, +{"file":"internal/controller/interface.go","statements":0,"covered":0,"percent":null,"sha256":"24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68"}, +{"file":"internal/model/http/models.go","statements":0,"covered":0,"percent":null,"sha256":"8c183b065bc3ab4cad20570eab79f334ca75a3309186fdf832fb1aa598894465"}, +{"file":"internal/config/config.go","statements":17,"covered":17,"percent":100.00000000,"sha256":"8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa"}, +{"file":"internal/service/production/messages.go","statements":18,"covered":18,"percent":100.00000000,"sha256":"99a25471826d78b0655be2e4ccfcc1fd0b79ba15454f0fd66a5cf06dcdba9e9c"}, +{"file":"internal/service/production/service.go","statements":10,"covered":10,"percent":100.00000000,"sha256":"6592e1bd6979036609d052c85b4f73484a0148a5592a3ef415557c1779104d60"}, +{"file":"internal/service/errors.go","statements":0,"covered":0,"percent":null,"sha256":"9dd4d2998e37c48e104298ae7bc9f311f193ff5212608f9c579cd569941d5054"}, +{"file":"cmd/server/logger.go","statements":10,"covered":9,"percent":90.00000000,"sha256":"fd0801324362cb74dd1b9d78d9dcc001d9e107e4a329cb48b0390dd33fa641cb"}, +{"file":"internal/model/dto/session.go","statements":0,"covered":0,"percent":null,"sha256":"896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb"}, +{"file":"internal/service/production/pagination.go","statements":21,"covered":21,"percent":100.00000000,"sha256":"ef3da5e89d7a1f8798d006760db07409df185b9315a16cdebec6bb22afedbccf"}, +{"file":"internal/service/production/validation.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"4adb55d349befbc2a1e79b40c5547e22f558cbe10f9866b8fe9ddfbebabb6699"}, +{"file":"cmd/server/healthcheck.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"29e339c55781d61de8e30fa07b9b21927d9553f7d3f6a63f43c49e86977b2503"}, +{"file":"internal/store/memory/capacity.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"70d7def3fab2ab41f71b6b88dea8bd4181d4ea619f17daa795c7097ba056bd7c"}, +{"file":"internal/service/cache.go","statements":0,"covered":0,"percent":null,"sha256":"e43e37991f18f27738877538e9c8304d06e18fa5cd8c773273d3d70185c6c5eb"}, +{"file":"internal/service/production/pages.go","statements":17,"covered":16,"percent":94.11764706,"sha256":"9d8c2d2ed63382586c5e0e405cd90e02e96cbbc05e1fa4e00e80821a7fdc031f"}, +{"file":"internal/config/environment.go","statements":14,"covered":14,"percent":100.00000000,"sha256":"027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3"}, +{"file":"internal/model/dto/models.go","statements":0,"covered":0,"percent":null,"sha256":"e2ecd732848d10f4471567c9603aa7359fcb1af7b2708ead477f4949f7a2fa4a"}, +{"file":"internal/valkey/cache.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"cb8805b347358fe683baa2927ff00a454a6fd928c7899170aa69493ac004199d"}, +{"file":"internal/service/interface.go","statements":0,"covered":0,"percent":null,"sha256":"30dd7d5ce30c7fa0c9b54dc38bdee15b71e7afd2c32aac1675b966585bebb203"}, +{"file":"internal/controller/http/fiber/routes.go","statements":56,"covered":56,"percent":100.00000000,"sha256":"826fe61b8d59465de7190c175b6abaa118f4a7deacdb1b9c628e25bb7f4feb3b"}, +{"file":"internal/controller/http/fiber/health.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"7328c3474e6036acbe8c2c0adb91d26e3822ef003d0c2214c89f39a27f2538b2"}, +{"file":"internal/service/auth.go","statements":0,"covered":0,"percent":null,"sha256":"c39b43224191bb74e3deb2c24830de9e8e17f5778f6e03d301893973d661f068"}, +{"file":"internal/admission/limiter.go","statements":16,"covered":16,"percent":100.00000000,"sha256":"a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4"}, +{"file":"internal/service/production/chats.go","statements":22,"covered":22,"percent":100.00000000,"sha256":"97f7d01d0b2c679910176b473c722f21996f79a164b209f0d71b3f240eaa4100"}, +{"file":"internal/config/logger.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988"}, +{"file":"internal/store/postgres/sessions.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"889a63b51b29012f4ae5499d1c0577fe29f2f2959b05629f8e123715cfc1f75f"}, +{"file":"internal/store/memory/chats.go","statements":31,"covered":31,"percent":100.00000000,"sha256":"8da28709d323b71c4e1a301f4f4e4401568ac50c052abe812a145e19ada8115e"}, +{"file":"internal/store/memory/messages.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"7e01358be57c6608f3fce2b72a76bb870a7d9ef76b035dfd473bd5f89abe0745"}, +{"file":"internal/controller/http/fiber/dependencies.go","statements":0,"covered":0,"percent":null,"sha256":"6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d"}, +{"file":"cmd/server/app.go","statements":8,"covered":8,"percent":100.00000000,"sha256":"f66db68f6697b4066bbfb6c8884851d0c1f6736a664a7711ab2249583e5180cf"}, +{"file":"internal/store/postgres/chats.go","statements":26,"covered":24,"percent":92.30769231,"sha256":"6bfacaeabe25f14cc400f3ce83aca807692872c4d364797abf20969e65cdf6a4"}, +{"file":"internal/controller/http/fiber/auth.go","statements":29,"covered":29,"percent":100.00000000,"sha256":"fa9da03281a9efc946f5ef3cbd768b18d37880f29fff9755ed347f5308f8c8a9"}, +{"file":"cmd/server/commands.go","statements":6,"covered":6,"percent":100.00000000,"sha256":"7290636ea31539d87bd97bb78cb28658409da966be8983e748ce1701f6f9f8f6"}, +{"file":"internal/controller/http/fiber/error_codes.go","statements":0,"covered":0,"percent":null,"sha256":"3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41"}, +{"file":"internal/controller/http/fiber/controller.go","statements":10,"covered":10,"percent":100.00000000,"sha256":"4a74bc4bfc6955ab1bf9a3a8e933381a807b5eafdd9049480be3486f87f1032e"}, +{"file":"internal/config/controller.go","statements":24,"covered":23,"percent":95.83333333,"sha256":"e784d7b934c4604065cd00bf4ff2b0c74741e759b1b7c81162adfc206d160153"}, +{"file":"internal/controller/http/fiber/error_registry.go","statements":2,"covered":2,"percent":100.00000000,"sha256":"9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a"}, +{"file":"internal/service/production/access.go","statements":27,"covered":27,"percent":100.00000000,"sha256":"4d39d5ad2ae82c62637d5f2a0a9d5030569ffe65a23eeecba6c1229c35feefd0"}, +{"file":"internal/password/password.go","statements":18,"covered":17,"percent":94.44444444,"sha256":"fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76"}, +{"file":"internal/controller/http/fiber/middleware.go","statements":34,"covered":33,"percent":97.05882353,"sha256":"d551a81ada306536a235fe684170e68613b72a847b6d16d3195edabd83e250aa"}, +{"file":"internal/controller/fx.go","statements":1,"covered":1,"percent":100.00000000,"sha256":"af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a"}, +{"file":"internal/strictjson/decode.go","statements":37,"covered":36,"percent":97.29729730,"sha256":"ef9bfaf3bd684fded87c92a15b3e5c706a794caf04cc4ef711c4185e9c7fb12a"}, +{"file":"internal/store/memory/ordering.go","statements":6,"covered":6,"percent":100.00000000,"sha256":"b5a20aa3473c42d06ad1b26a318afcc94e7397d34c106844bcf69eebaf210747"}, +{"file":"internal/controller/http/fiber/decode.go","statements":6,"covered":6,"percent":100.00000000,"sha256":"edc7124058479046b7f2ac3db7ff84a7bfb4602265c549cf7808906d6fb48dfb"}, +{"file":"internal/store/postgres/messages.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"45984d4dd4548f3ed96557bf5f8dac8b3b9fdf729e2b1296ef39f7860f0410db"}, +{"file":"internal/config/persistence.go","statements":15,"covered":15,"percent":100.00000000,"sha256":"671f92c52c827989ce194f3928b02f707292022bb97d3c483410e97cf626b4af"}, +{"file":"internal/service/production/errors.go","statements":5,"covered":5,"percent":100.00000000,"sha256":"fd37a3018f9d7ab72bc8d2b130be94967c4becd2bb09033cfb3caf26d4a5142d"}, +{"file":"internal/hashring/ring.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c"}, +{"file":"internal/admission/distributed.go","statements":0,"covered":0,"percent":null,"sha256":"41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d"}, +{"file":"internal/store/memory/store.go","statements":3,"covered":3,"percent":100.00000000,"sha256":"473cd854d928b02b5a5f50dd7eae87c3f644259b1db0a0ad1e653f3691828c9e"}, +{"file":"internal/store/interface.go","statements":0,"covered":0,"percent":null,"sha256":"7e48fc1130123b259ce4c7d8b699262728d73ba0756c4607e0ad8ec4100c0e4b"}, +{"file":"cmd/server/main.go","statements":3,"covered":3,"percent":100.00000000,"sha256":"c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495"}, +{"file":"internal/store/postgres/store.go","statements":46,"covered":43,"percent":93.47826087,"sha256":"697b8e9bd462b88b6a3d0e5027b1a6157cbb5567f42042b561ffff8274d4faae"}, +{"file":"internal/controller/http/fiber/mapping.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"dfb7cb698cd2fa6b592d04f0986416a0ec58004be23deb3d44a5f55a9ea698e1"}, +{"file":"internal/controller/http/fiber/public_errors.go","statements":13,"covered":12,"percent":92.30769231,"sha256":"eb6b147bbfe46b7ea519d3d65d813e8b28eeaa735dbb77ffa74bae285bc91536"}, +{"file":"internal/controller/http/fiber/errors.go","statements":28,"covered":28,"percent":100.00000000,"sha256":"dbefa0ce973d65b269dfc5f229799b2c5bf16a99547d348eaf6668660a536fcf"}, +{"file":"internal/store/postgres/users.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"034cd07af2e065a3a49ff8cca619ce1f4aaef96758a1fa0d12d1fb1319dcf9e9"}, +{"file":"internal/service/production/users.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"b1bec2c45ca926d193f7956ae3e3ae0868e4e0f722577d0095c737c2484e4da5"}, +{"file":"internal/service/authentication/service.go","statements":48,"covered":47,"percent":97.91666667,"sha256":"398b9c206556e2cd0f57f8ebd0757ab50e061683483d63a3f4ed33d1978bb27d"}, +{"file":"internal/store/memory/users.go","statements":22,"covered":21,"percent":95.45454545,"sha256":"750fbcdb34c66262c9b39f535a7d0acb3403f85d1158e9719356fc312b7ec932"}, +{"file":"cmd/server/persistence.go","statements":18,"covered":18,"percent":100.00000000,"sha256":"e109fb168675a92f990a1c983656623b150ed866062caf718e6b1a1068e19f46"}, +{"file":"internal/controller/http/fiber/configure.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd"}, +{"file":"internal/service/cursor.go","statements":0,"covered":0,"percent":null,"sha256":"478c8c9aca24d0fc7c471dfba43dcdd3c5b78a9d2c4d97c87fbcc058640c99d0"}, +{"file":"internal/controller/http/fiber/lifecycle.go","statements":24,"covered":22,"percent":91.66666667,"sha256":"f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08"}, +{"file":"internal/controller/http/fiber/headers.go","statements":0,"covered":0,"percent":null,"sha256":"d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd"}, +{"file":"internal/config/memory.go","statements":11,"covered":11,"percent":100.00000000,"sha256":"86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0"}, +{"file":"internal/valkey/admission.go","statements":45,"covered":45,"percent":100.00000000,"sha256":"a25eb9130eeb832411fd7ab8a359a6d4e0ba39f7e12b71ec62917594293343f0"} +],"passed":true} diff --git a/evidence/fault-coverage.txt b/evidence/fault-coverage.txt new file mode 100644 index 00000000..743e22e6 --- /dev/null +++ b/evidence/fault-coverage.txt @@ -0,0 +1,92 @@ +GO="go" scripts/coverage.sh +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/cmd/server 2.112s coverage: 31.0% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission 1.352s coverage: 1.5% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config 1.352s coverage: 7.6% of statements in ./... + gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/controller coverage: 0.0% of statements +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/controller/http/fiber 1.607s coverage: 55.5% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor 1.350s coverage: 2.8% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/hashring 1.919s coverage: 1.8% of statements in ./... +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto [no test files] +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/http [no test files] +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/password 2.497s coverage: 1.6% of statements in ./... +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service [no test files] +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service/authentication 1.352s coverage: 4.9% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service/production 1.369s coverage: 19.1% of statements in ./... +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store [no test files] +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store/memory 1.356s coverage: 8.4% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store/postgres 2.388s coverage: 11.0% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/strictjson 1.255s coverage: 3.3% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/valkey 1.334s coverage: 10.6% of statements in ./... +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/student-tests 1.313s coverage: 0.0% of statements in ./... +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. + 93.94% internal/cursor/codec.go + 97.14% internal/valkey/client.go + 97.30% internal/controller/http/fiber/handlers.go + 100.00% internal/service/production/members.go + 100.00% internal/service/production/creation.go + N/A internal/controller/interface.go + N/A internal/model/http/models.go + 100.00% internal/config/config.go + 100.00% internal/service/production/messages.go + 100.00% internal/service/production/service.go + N/A internal/service/errors.go + 90.00% cmd/server/logger.go + N/A internal/model/dto/session.go + 100.00% internal/service/production/pagination.go + 100.00% internal/service/production/validation.go + 94.74% cmd/server/healthcheck.go + 100.00% internal/store/memory/capacity.go + N/A internal/service/cache.go + 94.12% internal/service/production/pages.go + 100.00% internal/config/environment.go + N/A internal/model/dto/models.go + 94.74% internal/valkey/cache.go + N/A internal/service/interface.go + 100.00% internal/controller/http/fiber/routes.go + 100.00% internal/controller/http/fiber/health.go + N/A internal/service/auth.go + 100.00% internal/admission/limiter.go + 100.00% internal/service/production/chats.go + 100.00% internal/config/logger.go + 100.00% internal/store/postgres/sessions.go + 100.00% internal/store/memory/chats.go + 94.74% internal/store/memory/messages.go + N/A internal/controller/http/fiber/dependencies.go + 100.00% cmd/server/app.go + 92.31% internal/store/postgres/chats.go + 100.00% internal/controller/http/fiber/auth.go + 100.00% cmd/server/commands.go + N/A internal/controller/http/fiber/error_codes.go + 100.00% internal/controller/http/fiber/controller.go + 95.83% internal/config/controller.go + 100.00% internal/controller/http/fiber/error_registry.go + 100.00% internal/service/production/access.go + 94.44% internal/password/password.go + 97.06% internal/controller/http/fiber/middleware.go + 100.00% internal/controller/fx.go + 97.30% internal/strictjson/decode.go + 100.00% internal/store/memory/ordering.go + 100.00% internal/controller/http/fiber/decode.go + 95.24% internal/store/postgres/messages.go + 100.00% internal/config/persistence.go + 100.00% internal/service/production/errors.go + 95.24% internal/hashring/ring.go + N/A internal/admission/distributed.go + 100.00% internal/store/memory/store.go + N/A internal/store/interface.go + 100.00% cmd/server/main.go + 93.48% internal/store/postgres/store.go + 100.00% internal/controller/http/fiber/mapping.go + 92.31% internal/controller/http/fiber/public_errors.go + 100.00% internal/controller/http/fiber/errors.go + 95.24% internal/store/postgres/users.go + 100.00% internal/service/production/users.go + 97.92% internal/service/authentication/service.go + 95.45% internal/store/memory/users.go + 100.00% cmd/server/persistence.go + 100.00% internal/controller/http/fiber/configure.go + N/A internal/service/cursor.go + 91.67% internal/controller/http/fiber/lifecycle.go + N/A internal/controller/http/fiber/headers.go + 100.00% internal/config/memory.go + 100.00% internal/valkey/admission.go diff --git a/evidence/fault-lint.txt b/evidence/fault-lint.txt new file mode 100644 index 00000000..18235ca9 --- /dev/null +++ b/evidence/fault-lint.txt @@ -0,0 +1,2 @@ +golangci-lint run ./... +0 issues. diff --git a/evidence/fault-regression.txt b/evidence/fault-regression.txt new file mode 100644 index 00000000..283d50d8 --- /dev/null +++ b/evidence/fault-regression.txt @@ -0,0 +1,27 @@ +scripts/test-faults.sh +UTC 2026-10-16T07:16:07Z +b90581f613aa82866be2dce08afe725d9a7426a9 +6bfacaeabe25f14cc400f3ce83aca807692872c4d364797abf20969e65cdf6a4 internal/store/postgres/chats.go +1d0179aa490fa03ed545141f9dc5b40e454a197689a8a40c244358d9ed3f229e internal/store/postgres/errors_test.go +45984d4dd4548f3ed96557bf5f8dac8b3b9fdf729e2b1296ef39f7860f0410db internal/store/postgres/messages.go +889a63b51b29012f4ae5499d1c0577fe29f2f2959b05629f8e123715cfc1f75f internal/store/postgres/sessions.go +697b8e9bd462b88b6a3d0e5027b1a6157cbb5567f42042b561ffff8274d4faae internal/store/postgres/store.go +601c9cde6c08314c6107bfaa79cbcc50e02768d38998d921ae825d0877cdc729 internal/store/postgres/store_test.go +034cd07af2e065a3a49ff8cca619ce1f4aaef96758a1fa0d12d1fb1319dcf9e9 internal/store/postgres/users.go +9dd4d2998e37c48e104298ae7bc9f311f193ff5212608f9c579cd569941d5054 internal/service/errors.go +7e48fc1130123b259ce4c7d8b699262728d73ba0756c4607e0ad8ec4100c0e4b internal/store/interface.go +eb6b147bbfe46b7ea519d3d65d813e8b28eeaa735dbb77ffa74bae285bc91536 internal/controller/http/fiber/public_errors.go +97614aa2647c42caecc9ab265673702e4c7eede8d0f2281acf16f44ac1d0e6da scripts/test-faults.sh +PASS: postgres stop authenticated history => 503 unavailable (0.001530s) +PASS: postgres stop rejects anonymous/spoofed/malformed/unknown identity; liveness=200 readiness=503 +PASS: postgres stop recovery preserves the original session and message +PASS: postgres pause authenticated history => 503 unavailable (0.507818s) +PASS: postgres pause rejects anonymous/spoofed/malformed/unknown identity; liveness=200 readiness=503 +PASS: postgres pause recovery preserves the original session and message +PASS: valkey stop authenticated history => 503 unavailable (0.503123s) +PASS: valkey stop rejects anonymous/spoofed/malformed/unknown identity; liveness=200 readiness=503 +PASS: valkey stop recovery preserves the original session and message +PASS: valkey pause authenticated history => 503 unavailable (0.506513s) +PASS: valkey pause rejects anonymous/spoofed/malformed/unknown identity; liveness=200 readiness=503 +PASS: valkey pause recovery preserves the original session and message +PASS: real dependency fault scenarios completed diff --git a/evidence/fault-vet.txt b/evidence/fault-vet.txt new file mode 100644 index 00000000..8b94ad53 --- /dev/null +++ b/evidence/fault-vet.txt @@ -0,0 +1 @@ +go vet ./... diff --git a/evidence/gitea-transfer-lint.txt b/evidence/gitea-transfer-lint.txt new file mode 100644 index 00000000..18235ca9 --- /dev/null +++ b/evidence/gitea-transfer-lint.txt @@ -0,0 +1,2 @@ +golangci-lint run ./... +0 issues. diff --git a/evidence/gitea-transfer-tests.txt b/evidence/gitea-transfer-tests.txt new file mode 100644 index 00000000..3038f51e --- /dev/null +++ b/evidence/gitea-transfer-tests.txt @@ -0,0 +1,33 @@ +go version go1.27.1 darwin/arm64 +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/cmd/server 4.207s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission 3.911s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config 4.066s +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/controller [no test files] +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/controller/http/fiber 4.185s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor 4.074s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/hashring 4.359s +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto [no test files] +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/http [no test files] +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/password 5.055s +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service [no test files] +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service/authentication 4.066s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service/production 4.077s +? gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store [no test files] +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store/memory 4.104s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store/postgres 4.112s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/strictjson 1.352s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/valkey 1.341s +ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/student-tests 1.361s + +Transfer verification, 2026-10-15: +PASS: go build ./... +PASS: go vet ./... +PASS: make check +PASS: make chart-check +PASS: make lint (0 issues; gitea-transfer-lint.txt) +PASS: git diff --check +PASS: 182 solution files transferred; contents match source except module/import rename and migration notes +PASS: destination README/COURSE/CONTRIBUTING/MAINTAINERS/contracts/tests/public scripts unchanged +PASS: cloned lab3–6 working trees clean +Integration dependencies were not configured; PostgreSQL/Valkey integration cases were skipped. +No cluster rollout, image build, Git commit or push was performed during transfer. diff --git a/evidence/go-lint.txt b/evidence/go-lint.txt new file mode 100644 index 00000000..6a3ebaa7 --- /dev/null +++ b/evidence/go-lint.txt @@ -0,0 +1 @@ +0 issues. diff --git a/evidence/go-tests-coverage.txt b/evidence/go-tests-coverage.txt new file mode 100644 index 00000000..e4040918 --- /dev/null +++ b/evidence/go-tests-coverage.txt @@ -0,0 +1,21 @@ +ok gitflic.ru/vlad_marlo/mtusi2026lab2/cmd/server 2.361s coverage: 30.8% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/admission 1.443s coverage: 1.5% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/config 1.524s coverage: 7.6% of statements in ./... + gitflic.ru/vlad_marlo/mtusi2026lab2/internal/controller coverage: 0.0% of statements +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/controller/http/fiber 1.688s coverage: 55.8% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/cursor 1.632s coverage: 2.9% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/hashring 2.069s coverage: 1.8% of statements in ./... +? gitflic.ru/vlad_marlo/mtusi2026lab2/internal/model/dto [no test files] +? gitflic.ru/vlad_marlo/mtusi2026lab2/internal/model/http [no test files] +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/password 3.007s coverage: 1.6% of statements in ./... +? gitflic.ru/vlad_marlo/mtusi2026lab2/internal/service [no test files] +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/service/authentication 1.465s coverage: 5.0% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/service/production 1.334s coverage: 19.2% of statements in ./... +? gitflic.ru/vlad_marlo/mtusi2026lab2/internal/store [no test files] +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/store/memory 1.630s coverage: 8.5% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/store/postgres 2.916s coverage: 10.4% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/strictjson 1.270s coverage: 3.3% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/valkey 1.377s coverage: 10.7% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/student-tests 1.352s coverage: 0.0% of statements in ./... +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. +PASS: every executable Go file has >=90% statement coverage diff --git a/evidence/hashring.txt b/evidence/hashring.txt new file mode 100644 index 00000000..f6dfe4f7 --- /dev/null +++ b/evidence/hashring.txt @@ -0,0 +1,5 @@ +=== RUN TestExpansionMovesOnlyKeysOwnedByNewNode + ring_test.go:33: 100000 keys: moved=33007 fraction=0.33007 +--- PASS: TestExpansionMovesOnlyKeysOwnedByNewNode (0.02s) +PASS +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/hashring 0.294s diff --git a/evidence/helm-coverage-per-file.json b/evidence/helm-coverage-per-file.json new file mode 100644 index 00000000..3e55b308 --- /dev/null +++ b/evidence/helm-coverage-per-file.json @@ -0,0 +1,73 @@ +{"threshold_per_file":90,"files":[ +{"file":"internal/store/postgres/chats.go","statements":26,"covered":24,"percent":92.30769231,"sha256":"b9d69046cd919957434da02c635d259c8e36f27371270afedc312947eb5bb615"}, +{"file":"internal/store/memory/chats.go","statements":31,"covered":31,"percent":100.00000000,"sha256":"150851ac6a0d5da8835a9aaaa7c1156b075e5e3dd962698fb483b0afa8a2097f"}, +{"file":"internal/controller/http/fiber/headers.go","statements":0,"covered":0,"percent":null,"sha256":"d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd"}, +{"file":"internal/controller/http/fiber/decode.go","statements":6,"covered":6,"percent":100.00000000,"sha256":"bb4216cb6c5813b66b51dc99a53f8cf09982789155305a099c321dd12fa8e2de"}, +{"file":"internal/controller/http/fiber/error_registry.go","statements":2,"covered":2,"percent":100.00000000,"sha256":"9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a"}, +{"file":"internal/store/interface.go","statements":0,"covered":0,"percent":null,"sha256":"ea599de0e0d2a0be7de7b0835307a4d1852db16a49bfad3636f7c30b85181fce"}, +{"file":"internal/controller/fx.go","statements":1,"covered":1,"percent":100.00000000,"sha256":"af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a"}, +{"file":"internal/controller/http/fiber/handlers.go","statements":37,"covered":36,"percent":97.29729730,"sha256":"59e3f16adc94b7426c74e2f40b5ff18a9129c80fc619cb8144110bdeec095021"}, +{"file":"internal/controller/http/fiber/errors.go","statements":28,"covered":28,"percent":100.00000000,"sha256":"d502e2a9f7fe3980c10c2760c31711794898c539d07b43b02497dc2cfb870358"}, +{"file":"internal/service/production/validation.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"6aa0ff490fe8fca8b906b5073e0914a64369ddfc7d0648d895cc41cb69cdd2e0"}, +{"file":"internal/hashring/ring.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c"}, +{"file":"cmd/server/main.go","statements":3,"covered":3,"percent":100.00000000,"sha256":"c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495"}, +{"file":"internal/service/production/pagination.go","statements":21,"covered":21,"percent":100.00000000,"sha256":"4cb0d47ef9cc020e608f93a8257b6d65136f6f74b86c3f591f19dad688fc7bf0"}, +{"file":"internal/config/persistence.go","statements":15,"covered":15,"percent":100.00000000,"sha256":"671f92c52c827989ce194f3928b02f707292022bb97d3c483410e97cf626b4af"}, +{"file":"internal/controller/http/fiber/controller.go","statements":10,"covered":10,"percent":100.00000000,"sha256":"fd0d06ac838c8ceca1189303b98ce006ca1298381de49fe6d790d0f0f4007d3e"}, +{"file":"internal/valkey/admission.go","statements":45,"covered":45,"percent":100.00000000,"sha256":"4baa4e399be201189371d1ace6169e56958251386624af4996fac04e0ab5d1f7"}, +{"file":"internal/service/production/users.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"50d873980bdc97a799c2e61a4b25c5bd222a32bd7baed28590510ef373ac0461"}, +{"file":"internal/store/postgres/store.go","statements":39,"covered":36,"percent":92.30769231,"sha256":"5f3e022a414103198a1ab8e62f337e67c22afd1afddda400884b79a5e51488a2"}, +{"file":"internal/cursor/codec.go","statements":33,"covered":31,"percent":93.93939394,"sha256":"a5bc7aac6d1764929fb11365c9f8b6a45ff65e47b3a317a7ccd9ec6dd1b2713a"}, +{"file":"internal/controller/http/fiber/middleware.go","statements":34,"covered":33,"percent":97.05882353,"sha256":"34fd687af80730601ba9276ef606fee76df84d14b4400a65ec5b804897673536"}, +{"file":"cmd/server/persistence.go","statements":18,"covered":18,"percent":100.00000000,"sha256":"06b304d8f0cad20c206edbef8becab283c50c1722fd81c56a06f018dfe03bb7f"}, +{"file":"internal/store/postgres/sessions.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"6f7f2e86822d806640888da990716279659fe90e5a74b3b0d5454a5155d0334b"}, +{"file":"internal/store/memory/store.go","statements":3,"covered":3,"percent":100.00000000,"sha256":"f463d530955bfe5793fb9a4ad93d6615a3ce923d1d4719b8c515f487c96997ca"}, +{"file":"internal/model/http/models.go","statements":0,"covered":0,"percent":null,"sha256":"8c183b065bc3ab4cad20570eab79f334ca75a3309186fdf832fb1aa598894465"}, +{"file":"internal/service/production/members.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"1f5c9335bf4cf5b9f4137454e3ca22975e7c6c7118e4e60bb470851f8a7cd61e"}, +{"file":"internal/store/postgres/users.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"2721381975755efe2a4f14a8df3c1189d2dcc6c7933fc25292977014c26aa220"}, +{"file":"internal/store/memory/users.go","statements":22,"covered":21,"percent":95.45454545,"sha256":"1652a23bc8fc29a6ef00851a19d4547b660f3bfcce9d458b7381db5b3f30778c"}, +{"file":"internal/store/memory/capacity.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"ac2aafe9f19706ff39b16a4ca1b1e142f6e52bef160ef591f9f2120d106ffd51"}, +{"file":"internal/model/dto/session.go","statements":0,"covered":0,"percent":null,"sha256":"896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb"}, +{"file":"internal/controller/http/fiber/dependencies.go","statements":0,"covered":0,"percent":null,"sha256":"6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d"}, +{"file":"internal/config/memory.go","statements":11,"covered":11,"percent":100.00000000,"sha256":"86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0"}, +{"file":"internal/service/production/service.go","statements":10,"covered":10,"percent":100.00000000,"sha256":"70fb90d812432e321c4fca1b1e2141cfad91453e294f4efda60c0898be686d7d"}, +{"file":"cmd/server/logger.go","statements":10,"covered":9,"percent":90.00000000,"sha256":"43ad9caf2260d8551b8b3e149681c5e66770e9901d72de41b81746cb0cac47ec"}, +{"file":"cmd/server/commands.go","statements":6,"covered":6,"percent":100.00000000,"sha256":"7290636ea31539d87bd97bb78cb28658409da966be8983e748ce1701f6f9f8f6"}, +{"file":"internal/valkey/client.go","statements":35,"covered":34,"percent":97.14285714,"sha256":"86acf0827e1d29993eda7ee62a8fa42b02d707330a94a70f5a3933911407e882"}, +{"file":"internal/service/cursor.go","statements":0,"covered":0,"percent":null,"sha256":"07244e89d9948087318df2dfecfb3a648c217bc313fb033748f5562e08ba8a95"}, +{"file":"cmd/server/app.go","statements":8,"covered":8,"percent":100.00000000,"sha256":"2c8e791d08fca312f52a40e082b18dc82676e891df57c04fbca1334d5edcfa26"}, +{"file":"internal/controller/http/fiber/configure.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd"}, +{"file":"internal/config/config.go","statements":17,"covered":17,"percent":100.00000000,"sha256":"8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa"}, +{"file":"internal/model/dto/models.go","statements":0,"covered":0,"percent":null,"sha256":"e2ecd732848d10f4471567c9603aa7359fcb1af7b2708ead477f4949f7a2fa4a"}, +{"file":"internal/controller/interface.go","statements":0,"covered":0,"percent":null,"sha256":"24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68"}, +{"file":"internal/service/interface.go","statements":0,"covered":0,"percent":null,"sha256":"017b13007719a32a8eec26527848231381590e5632790bedec66a126776bad6e"}, +{"file":"internal/controller/http/fiber/lifecycle.go","statements":24,"covered":22,"percent":91.66666667,"sha256":"f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08"}, +{"file":"internal/store/postgres/messages.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"1ab5dd2f8d81697a57ee89e1969995e52bfccc0f3f25a5c480822e41313988f1"}, +{"file":"internal/store/memory/messages.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"94f2a5ce429aa8280e1333760309fd1d02b314310cbdea495aef56a63ed145b1"}, +{"file":"internal/service/cache.go","statements":0,"covered":0,"percent":null,"sha256":"55baf7ba65292ae6a75b7a6af8d304886f35c7ad854b8d700251d6f32c964dbf"}, +{"file":"internal/admission/limiter.go","statements":16,"covered":16,"percent":100.00000000,"sha256":"a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4"}, +{"file":"internal/valkey/cache.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"693b866a740b6d5f765221be4c6489391821d4b58942cf0ff36030163dbae6a9"}, +{"file":"internal/controller/http/fiber/routes.go","statements":56,"covered":56,"percent":100.00000000,"sha256":"826fe61b8d59465de7190c175b6abaa118f4a7deacdb1b9c628e25bb7f4feb3b"}, +{"file":"internal/controller/http/fiber/health.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"6d18f3c4be98e70a7e61d82b014b6db9b3a5e594c9b5f50ecea88f89bd6917cd"}, +{"file":"internal/service/auth.go","statements":0,"covered":0,"percent":null,"sha256":"ede0474befff6773779dd448e9b42a98bd2edb12033b65366e5f65618ec4885e"}, +{"file":"cmd/server/healthcheck.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"b0a0c1689dfe2db5abc889af13d7adb00a1d4f3d260b5ebe6d5f529cb5983a0e"}, +{"file":"internal/service/production/pages.go","statements":17,"covered":16,"percent":94.11764706,"sha256":"4306cd592bdcd2dd5c31eeadc0dc5e1a59b275ffa6de091032edf644171020c5"}, +{"file":"internal/service/production/creation.go","statements":12,"covered":12,"percent":100.00000000,"sha256":"fe5940f705df32902151d51f82c7f9f1df3e274e62413d9e1b54f2a512707d48"}, +{"file":"internal/service/errors.go","statements":0,"covered":0,"percent":null,"sha256":"e19c47379f63a5ee7e24b9b0fded1eb326ea231392b4e27c324d205d4c620f7d"}, +{"file":"internal/service/production/messages.go","statements":18,"covered":18,"percent":100.00000000,"sha256":"6bdd523dd8be7ce139a0a7f2c9ee16d8d2f03e4d15ed00e7a31658c23fb97c17"}, +{"file":"internal/controller/http/fiber/error_codes.go","statements":0,"covered":0,"percent":null,"sha256":"3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41"}, +{"file":"internal/service/production/chats.go","statements":22,"covered":22,"percent":100.00000000,"sha256":"881f9269ad84ab5dc091fdec8ad6c36bebd2eaac0da0685b8d333216e0a2dd16"}, +{"file":"internal/controller/http/fiber/mapping.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"f63d4b0e2ee5f62c4d0d8c4b26a8734d68230af4577e3c6cb71a92525c3c8681"}, +{"file":"internal/config/controller.go","statements":24,"covered":23,"percent":95.83333333,"sha256":"e784d7b934c4604065cd00bf4ff2b0c74741e759b1b7c81162adfc206d160153"}, +{"file":"internal/store/memory/ordering.go","statements":6,"covered":6,"percent":100.00000000,"sha256":"4aef07be1cb907cfa7a4a3d78060d8be57c9ff566c16e729dea9b0db68c7dfae"}, +{"file":"internal/service/production/access.go","statements":27,"covered":27,"percent":100.00000000,"sha256":"fc191b98aaf0488cb60f258c3ce9788708818c7f299a10f80e91568adabd05e5"}, +{"file":"internal/service/authentication/service.go","statements":48,"covered":47,"percent":97.91666667,"sha256":"1cc82be87998dc9b66216965dc3ac37aa6c210c1007fc46a2a0bd698e9cb6167"}, +{"file":"internal/controller/http/fiber/auth.go","statements":29,"covered":29,"percent":100.00000000,"sha256":"3107673b329dbe7934a29679024a18e3baada2cc99bee4d0ddbba0f9fd93edf9"}, +{"file":"internal/config/logger.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988"}, +{"file":"internal/controller/http/fiber/public_errors.go","statements":12,"covered":11,"percent":91.66666667,"sha256":"d806c2d026a8ff2fc54d60b62c062e80a3532e652fcfa5c3105684ba17cc9f67"}, +{"file":"internal/password/password.go","statements":18,"covered":17,"percent":94.44444444,"sha256":"fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76"}, +{"file":"internal/admission/distributed.go","statements":0,"covered":0,"percent":null,"sha256":"41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d"}, +{"file":"internal/strictjson/decode.go","statements":37,"covered":36,"percent":97.29729730,"sha256":"ef9bfaf3bd684fded87c92a15b3e5c706a794caf04cc4ef711c4185e9c7fb12a"}, +{"file":"internal/config/environment.go","statements":14,"covered":14,"percent":100.00000000,"sha256":"027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3"}, +{"file":"internal/service/production/errors.go","statements":5,"covered":5,"percent":100.00000000,"sha256":"7495818188cc13028d9400dfa18005e9aa334ac048b7a84150dd2b6ddb28d796"} +],"passed":true} diff --git a/evidence/helm-coverage.txt b/evidence/helm-coverage.txt new file mode 100644 index 00000000..ae1cca3b --- /dev/null +++ b/evidence/helm-coverage.txt @@ -0,0 +1,92 @@ +GO="go" scripts/coverage.sh +ok gitflic.ru/vlad_marlo/mtusi2026lab2/cmd/server 2.018s coverage: 31.2% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/admission (cached) coverage: 1.5% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/config 1.268s coverage: 7.6% of statements in ./... + gitflic.ru/vlad_marlo/mtusi2026lab2/internal/controller coverage: 0.0% of statements +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/controller/http/fiber (cached) coverage: 55.8% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/cursor (cached) coverage: 2.9% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/hashring (cached) coverage: 1.8% of statements in ./... +? gitflic.ru/vlad_marlo/mtusi2026lab2/internal/model/dto [no test files] +? gitflic.ru/vlad_marlo/mtusi2026lab2/internal/model/http [no test files] +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/password (cached) coverage: 1.6% of statements in ./... +? gitflic.ru/vlad_marlo/mtusi2026lab2/internal/service [no test files] +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/service/authentication (cached) coverage: 5.0% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/service/production (cached) coverage: 19.2% of statements in ./... +? gitflic.ru/vlad_marlo/mtusi2026lab2/internal/store [no test files] +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/store/memory (cached) coverage: 8.5% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/store/postgres 1.803s coverage: 10.4% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/strictjson (cached) coverage: 3.3% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/internal/valkey 1.385s coverage: 10.7% of statements in ./... +ok gitflic.ru/vlad_marlo/mtusi2026lab2/student-tests (cached) coverage: 0.0% of statements in ./... +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. + 92.31% internal/store/postgres/chats.go + 100.00% internal/store/memory/chats.go + N/A internal/controller/http/fiber/headers.go + 100.00% internal/controller/http/fiber/decode.go + 100.00% internal/controller/http/fiber/error_registry.go + N/A internal/store/interface.go + 100.00% internal/controller/fx.go + 97.30% internal/controller/http/fiber/handlers.go + 100.00% internal/controller/http/fiber/errors.go + 100.00% internal/service/production/validation.go + 95.24% internal/hashring/ring.go + 100.00% cmd/server/main.go + 100.00% internal/service/production/pagination.go + 100.00% internal/config/persistence.go + 100.00% internal/controller/http/fiber/controller.go + 100.00% internal/valkey/admission.go + 100.00% internal/service/production/users.go + 92.31% internal/store/postgres/store.go + 93.94% internal/cursor/codec.go + 97.06% internal/controller/http/fiber/middleware.go + 100.00% cmd/server/persistence.go + 100.00% internal/store/postgres/sessions.go + 100.00% internal/store/memory/store.go + N/A internal/model/http/models.go + 100.00% internal/service/production/members.go + 95.24% internal/store/postgres/users.go + 95.45% internal/store/memory/users.go + 100.00% internal/store/memory/capacity.go + N/A internal/model/dto/session.go + N/A internal/controller/http/fiber/dependencies.go + 100.00% internal/config/memory.go + 100.00% internal/service/production/service.go + 90.00% cmd/server/logger.go + 100.00% cmd/server/commands.go + 97.14% internal/valkey/client.go + N/A internal/service/cursor.go + 100.00% cmd/server/app.go + 100.00% internal/controller/http/fiber/configure.go + 100.00% internal/config/config.go + N/A internal/model/dto/models.go + N/A internal/controller/interface.go + N/A internal/service/interface.go + 91.67% internal/controller/http/fiber/lifecycle.go + 95.24% internal/store/postgres/messages.go + 94.74% internal/store/memory/messages.go + N/A internal/service/cache.go + 100.00% internal/admission/limiter.go + 94.74% internal/valkey/cache.go + 100.00% internal/controller/http/fiber/routes.go + 100.00% internal/controller/http/fiber/health.go + N/A internal/service/auth.go + 94.74% cmd/server/healthcheck.go + 94.12% internal/service/production/pages.go + 100.00% internal/service/production/creation.go + N/A internal/service/errors.go + 100.00% internal/service/production/messages.go + N/A internal/controller/http/fiber/error_codes.go + 100.00% internal/service/production/chats.go + 100.00% internal/controller/http/fiber/mapping.go + 95.83% internal/config/controller.go + 100.00% internal/store/memory/ordering.go + 100.00% internal/service/production/access.go + 97.92% internal/service/authentication/service.go + 100.00% internal/controller/http/fiber/auth.go + 100.00% internal/config/logger.go + 91.67% internal/controller/http/fiber/public_errors.go + 94.44% internal/password/password.go + N/A internal/admission/distributed.go + 97.30% internal/strictjson/decode.go + 100.00% internal/config/environment.go + 100.00% internal/service/production/errors.go diff --git a/evidence/helm-deployment.txt b/evidence/helm-deployment.txt new file mode 100644 index 00000000..6200f99f --- /dev/null +++ b/evidence/helm-deployment.txt @@ -0,0 +1,89 @@ +UTC: 2026-10-07T14:05:13Z +Context: dev; namespace: highload-applications; release: lab2 +Initial adoption attempt (failure retained): +Release "lab2" does not exist. Installing it now. +Error: conflict occurred while applying object highload-applications/postgres apps/v1, Kind=StatefulSet: Apply failed with 1 conflict: conflict with "kubectl-client-side-apply" using apps/v1: .spec.volumeClaimTemplates && conflict occurred while applying object highload-applications/valkey apps/v1, Kind=StatefulSet: Apply failed with 1 conflict: conflict with "kubectl-client-side-apply" using apps/v1: .spec.volumeClaimTemplates +Retry with client-side apply: +Release "lab2" has been upgraded. Happy Helming! +NAME: lab2 +LAST DEPLOYED: Wed Oct 7 16:55:02 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 2 +DESCRIPTION: Upgrade complete +TEST SUITE: None +Repeated upgrade: +helm upgrade --install "lab2" charts/messenger --kube-context "dev" -n "highload-applications" --create-namespace -f "charts/messenger/values.yaml" --wait --timeout 180s +Release "lab2" has been upgraded. Happy Helming! +NAME: lab2 +LAST DEPLOYED: Wed Oct 7 16:55:41 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 3 +DESCRIPTION: Upgrade complete +TEST SUITE: None +PASS: all four PVC UIDs unchanged across adoption, restart and reshard 3->2->3 +NAME UID VOLUME +data-postgres-0 b592cc47-82be-4635-afa4-d65e3246e82a pvc-b592cc47-82be-4635-afa4-d65e3246e82a +data-valkey-0 fafeeae5-f6f6-487d-ba50-15d50f9678c7 pvc-fafeeae5-f6f6-487d-ba50-15d50f9678c7 +data-valkey-1 a39c3e41-fae2-4096-b83f-807aada803e9 pvc-a39c3e41-fae2-4096-b83f-807aada803e9 +data-valkey-2 ad5c9d15-ae01-409e-ad11-7f7f7b42e7fe pvc-ad5c9d15-ae01-409e-ad11-7f7f7b42e7fe +Data counts immediately before/after adoption (users|messages|sessions): +21|10|18 +21|10|18 +PASS: ordinary upgrade rejected live topology change: +Error: UPGRADE FAILED: execution error at (messenger/templates/guard.yaml:5:4): Changing shards requires drained API: use make reshard SHARDS=2 or SHARDS=3 +PASS: full restart changed UID of every API/PostgreSQL/Valkey pod: +[ + { + "name": "api-b97b8fd5c-5q97w", + "uid": "62df6b84-8f49-427f-ab57-0763ab746bb8" + }, + { + "name": "postgres-0", + "uid": "3f8b6638-9e4f-4004-85de-b8a51624b35a" + }, + { + "name": "valkey-0", + "uid": "462a6c71-ac57-4afb-9269-53e81d22fb04" + }, + { + "name": "valkey-1", + "uid": "f9bf5ec7-5da4-46d3-88c4-810b2d16a286" + }, + { + "name": "valkey-2", + "uid": "d27c9814-3f9c-4b31-9961-4ff728fa45f8" + } +] +[ + { + "name": "api-b97b8fd5c-kz2nh", + "uid": "084b7261-6a07-4a61-9f61-6ecbac605edf" + }, + { + "name": "postgres-0", + "uid": "fd274452-2236-44a9-b30d-978ae06623ba" + }, + { + "name": "valkey-0", + "uid": "370b84f2-04f6-40ce-a057-e1f577a902fa" + }, + { + "name": "valkey-1", + "uid": "750bd2bb-0b03-4479-92f4-70c60ee0aa56" + }, + { + "name": "valkey-2", + "uid": "b9f8dcb6-fd91-4959-83a6-3247c4dfc53d" + } +] +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +lab2 highload-applications 9 2026-10-07 17:00:05.477871 +0300 MSK deployed messenger-0.1.0 lab2 +NAME READY STATUS RESTARTS AGE +api-b97b8fd5c-kz2nh 1/1 Running 0 6s +postgres-0 1/1 Running 0 27s +valkey-0 1/1 Running 0 9s +valkey-1 1/1 Running 0 23s +valkey-2 1/1 Running 0 27s +cr.yandex/crpv8disueqk68pv29jg/mtusi2026lab2@sha256:bd5a0157693a9c288e3691c6d187a7314a798a91ff42a36228c7381cc5ce6496 diff --git a/evidence/helm-persistence.txt b/evidence/helm-persistence.txt new file mode 100644 index 00000000..793b001d --- /dev/null +++ b/evidence/helm-persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/helm-reshard-three.txt b/evidence/helm-reshard-three.txt new file mode 100644 index 00000000..f238db98 --- /dev/null +++ b/evidence/helm-reshard-three.txt @@ -0,0 +1,27 @@ +SHARDS="3" scripts/scale-shards.sh +Release "lab2" has been upgraded. Happy Helming! +NAME: lab2 +LAST DEPLOYED: Wed Oct 7 16:59:17 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 7 +DESCRIPTION: Upgrade complete +TEST SUITE: None +Release "lab2" has been upgraded. Happy Helming! +NAME: lab2 +LAST DEPLOYED: Wed Oct 7 16:59:51 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 8 +DESCRIPTION: Upgrade complete +TEST SUITE: None +1 +Release "lab2" has been upgraded. Happy Helming! +NAME: lab2 +LAST DEPLOYED: Wed Oct 7 17:00:05 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 9 +DESCRIPTION: Upgrade complete +TEST SUITE: None +Ring updated. Set valkey.shards=3 in your values file before the next make deploy. diff --git a/evidence/helm-reshard-two.txt b/evidence/helm-reshard-two.txt new file mode 100644 index 00000000..fc069e89 --- /dev/null +++ b/evidence/helm-reshard-two.txt @@ -0,0 +1,28 @@ +SHARDS="2" scripts/scale-shards.sh +Release "lab2" has been upgraded. Happy Helming! +NAME: lab2 +LAST DEPLOYED: Wed Oct 7 16:58:25 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 4 +DESCRIPTION: Upgrade complete +TEST SUITE: None +pod/api-b97b8fd5c-d8p8k condition met +Release "lab2" has been upgraded. Happy Helming! +NAME: lab2 +LAST DEPLOYED: Wed Oct 7 16:59:01 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 5 +DESCRIPTION: Upgrade complete +TEST SUITE: None +1 +Release "lab2" has been upgraded. Happy Helming! +NAME: lab2 +LAST DEPLOYED: Wed Oct 7 16:59:04 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 6 +DESCRIPTION: Upgrade complete +TEST SUITE: None +Ring updated. Set valkey.shards=2 in your values file before the next make deploy. diff --git a/evidence/helm-smoke-three.txt b/evidence/helm-smoke-three.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/helm-smoke-three.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/helm-smoke-two.txt b/evidence/helm-smoke-two.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/helm-smoke-two.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/helm-smoke.txt b/evidence/helm-smoke.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/helm-smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/image-build.json b/evidence/image-build.json new file mode 100644 index 00000000..5a957ebe --- /dev/null +++ b/evidence/image-build.json @@ -0,0 +1,20 @@ +{ + "buildx.build.provenance": { + "buildType": "", + "invocation": { + "configSource": {}, + "parameters": {}, + "environment": { + "platform": "" + } + } + }, + "buildx.build.ref": "asisti-builder/asisti-builder0/odzr94z3rs2nxze2b46kn7pa1", + "containerimage.descriptor": { + "mediaType": "application/vnd.oci.image.index.v1+json", + "digest": "sha256:bd5a0157693a9c288e3691c6d187a7314a798a91ff42a36228c7381cc5ce6496", + "size": 855 + }, + "containerimage.digest": "sha256:bd5a0157693a9c288e3691c6d187a7314a798a91ff42a36228c7381cc5ce6496", + "image.name": "cr.yandex/crpv8disueqk68pv29jg/mtusi2026lab2:src-f83270eb02dcfc92bdb0" +} \ No newline at end of file diff --git a/evidence/k8s-deployment.json b/evidence/k8s-deployment.json new file mode 100644 index 00000000..39e16485 --- /dev/null +++ b/evidence/k8s-deployment.json @@ -0,0 +1,139 @@ +{ + "date_utc": "2026-10-07T13:13:07.703484+00:00", + "context": "dev", + "namespace": "highload-applications", + "kubernetes_version": "v1.33.13", + "image": "cr.yandex/crpv8disueqk68pv29jg/mtusi2026lab2@sha256:bd5a0157693a9c288e3691c6d187a7314a798a91ff42a36228c7381cc5ce6496", + "deployment_available": 1, + "shards": "shard0=valkey-0.valkey:6379,shard1=valkey-1.valkey:6379,shard2=valkey-2.valkey:6379", + "old_namespace_absent": true, + "pods": [ + { + "name": "api-5c96c76fdd-4s6wj", + "uid": "b848a26b-3d63-481c-b8cf-9443247c0996", + "node": "dev.asisti.tech", + "phase": "Running", + "containers": [ + { + "name": "api", + "ready": true, + "restarts": 0, + "image_id": "cr.yandex/crpv8disueqk68pv29jg/mtusi2026lab2@sha256:bd5a0157693a9c288e3691c6d187a7314a798a91ff42a36228c7381cc5ce6496" + } + ] + }, + { + "name": "postgres-0", + "uid": "c2356c9a-9a8c-4cfe-998b-b16e4a302d7d", + "node": "dev.asisti.tech", + "phase": "Running", + "containers": [ + { + "name": "postgres", + "ready": true, + "restarts": 0, + "image_id": "docker.io/library/postgres@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94" + } + ] + }, + { + "name": "valkey-0", + "uid": "2b32977b-6ca9-41db-bb67-a5b851f214fc", + "node": "dev.asisti.tech", + "phase": "Running", + "containers": [ + { + "name": "valkey", + "ready": true, + "restarts": 0, + "image_id": "docker.io/valkey/valkey@sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773" + } + ] + }, + { + "name": "valkey-1", + "uid": "fb91293f-3f1b-48b3-b47a-f6d41ca2b3e8", + "node": "marlosrv0", + "phase": "Running", + "containers": [ + { + "name": "valkey", + "ready": true, + "restarts": 0, + "image_id": "docker.io/valkey/valkey@sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773" + } + ] + }, + { + "name": "valkey-2", + "uid": "2aa36d1b-8039-4a69-9e94-62d1ce2127ae", + "node": "srv0.agapov.space", + "phase": "Running", + "containers": [ + { + "name": "valkey", + "ready": true, + "restarts": 0, + "image_id": "docker.io/valkey/valkey@sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773" + } + ] + } + ], + "persistent_volumes": [ + { + "claim": "data-postgres-0", + "uid": "b592cc47-82be-4635-afa4-d65e3246e82a", + "phase": "Bound", + "capacity": { + "storage": "2Gi" + }, + "storage_class": "microk8s-hostpath", + "volume": "pvc-b592cc47-82be-4635-afa4-d65e3246e82a" + }, + { + "claim": "data-valkey-0", + "uid": "fafeeae5-f6f6-487d-ba50-15d50f9678c7", + "phase": "Bound", + "capacity": { + "storage": "1Gi" + }, + "storage_class": "microk8s-hostpath", + "volume": "pvc-fafeeae5-f6f6-487d-ba50-15d50f9678c7" + }, + { + "claim": "data-valkey-1", + "uid": "a39c3e41-fae2-4096-b83f-807aada803e9", + "phase": "Bound", + "capacity": { + "storage": "1Gi" + }, + "storage_class": "microk8s-hostpath", + "volume": "pvc-a39c3e41-fae2-4096-b83f-807aada803e9" + }, + { + "claim": "data-valkey-2", + "uid": "ad5c9d15-ae01-409e-ad11-7f7f7b42e7fe", + "phase": "Bound", + "capacity": { + "storage": "1Gi" + }, + "storage_class": "microk8s-hostpath", + "volume": "pvc-ad5c9d15-ae01-409e-ad11-7f7f7b42e7fe" + } + ], + "checks": [ + "private_registry_pull", + "rollout", + "same_session_and_message_after_namespace_transfer", + "public_smoke_two_shards", + "full_persistence_two_shards", + "controlled_expansion_two_to_three", + "public_smoke_three_shards", + "full_persistence_three_shards" + ], + "limitations": [ + "Single API and PostgreSQL, hostpath PVCs, and one global Valkey coordinator do not provide host-failure HA.", + "First smoke immediately after scaling hit a disconnected port-forward tunnel; wait-ready plus repeated smoke succeeded.", + "Secret content, local key material, raw bearer tokens and database dumps are excluded." + ] +} diff --git a/evidence/k8s-highload-persistence-two-shards.txt b/evidence/k8s-highload-persistence-two-shards.txt new file mode 100644 index 00000000..793b001d --- /dev/null +++ b/evidence/k8s-highload-persistence-two-shards.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/k8s-highload-smoke-two-shards.txt b/evidence/k8s-highload-smoke-two-shards.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/k8s-highload-smoke-two-shards.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/k8s-namespace-move.json b/evidence/k8s-namespace-move.json new file mode 100644 index 00000000..62202253 --- /dev/null +++ b/evidence/k8s-namespace-move.json @@ -0,0 +1,17 @@ +{ + "date_utc": "2026-10-07T13:05:50.565190+00:00", + "context": "dev", + "source_namespace": "mtusi-lab2", + "target_namespace": "highload-applications", + "counts_columns": [ + "users", + "chats", + "messages", + "sessions" + ], + "counts_before": "9|3|4|8", + "counts_after": "9|3|4|8", + "same_bearer_session_valid": true, + "confirmed_message_preserved": true, + "dump_saved_to_repository": false +} diff --git a/evidence/k8s-persistence-three-shards.txt b/evidence/k8s-persistence-three-shards.txt new file mode 100644 index 00000000..793b001d --- /dev/null +++ b/evidence/k8s-persistence-three-shards.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/k8s-persistence-two-shards.txt b/evidence/k8s-persistence-two-shards.txt new file mode 100644 index 00000000..793b001d --- /dev/null +++ b/evidence/k8s-persistence-two-shards.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/k8s-scale-shards.txt b/evidence/k8s-scale-shards.txt new file mode 100644 index 00000000..985a89b2 --- /dev/null +++ b/evidence/k8s-scale-shards.txt @@ -0,0 +1,10 @@ +deployment.apps/api scaled +pod/api-5c96c76fdd-54snp condition met +statefulset.apps/valkey scaled +Waiting for 1 pods to be ready... +partitioned roll out complete: 3 new pods have been updated... +configmap/messenger-config patched +1 +deployment.apps/api scaled +Waiting for deployment "api" rollout to finish: 0 of 1 updated replicas are available... +deployment "api" successfully rolled out diff --git a/evidence/k8s-smoke-three-shards-first-attempt.txt b/evidence/k8s-smoke-three-shards-first-attempt.txt new file mode 100644 index 00000000..0f7a2d0f --- /dev/null +++ b/evidence/k8s-smoke-three-shards-first-attempt.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +FAIL: GET /health/live: connection/TLS failure (RemoteDisconnected) diff --git a/evidence/k8s-smoke-three-shards.txt b/evidence/k8s-smoke-three-shards.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/k8s-smoke-three-shards.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/k8s-smoke-two-shards.txt b/evidence/k8s-smoke-two-shards.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/k8s-smoke-two-shards.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/load-resources.json b/evidence/load-resources.json new file mode 100644 index 00000000..aea1f3eb --- /dev/null +++ b/evidence/load-resources.json @@ -0,0 +1,246 @@ +{ + "date_utc": "2026-10-07T12:15:22.525423+00:00", + "samples": [ + { + "elapsed_seconds": 2.6860946659871843, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "15.37%", + "Container": "lab2-codex-api", + "ID": "779f0c8b022a", + "MemPerc": "4.67%", + "MemUsage": "11.95MiB / 256MiB", + "Name": "lab2-codex-api", + "NetIO": "1.75MB / 4.1MB", + "PIDs": "7" + }, + { + "BlockIO": "0B / 606kB", + "CPUPerc": "5.33%", + "Container": "lab2-codex-pg", + "ID": "c9b65b8b3290", + "MemPerc": "0.34%", + "MemUsage": "30.62MiB / 8.722GiB", + "Name": "lab2-codex-pg", + "NetIO": "395kB / 229kB", + "PIDs": "11" + }, + { + "BlockIO": "0B / 7.41MB", + "CPUPerc": "6.18%", + "Container": "lab2-codex-valkey-0", + "ID": "45ccf9bbf6ef", + "MemPerc": "0.11%", + "MemUsage": "9.68MiB / 8.722GiB", + "Name": "lab2-codex-valkey-0", + "NetIO": "1.5MB / 181kB", + "PIDs": "5" + }, + { + "BlockIO": "0B / 24.6kB", + "CPUPerc": "0.09%", + "Container": "lab2-codex-valkey-1", + "ID": "39506ebb9902", + "MemPerc": "0.10%", + "MemUsage": "9.195MiB / 8.722GiB", + "Name": "lab2-codex-valkey-1", + "NetIO": "19kB / 6.16kB", + "PIDs": "5" + }, + { + "BlockIO": "0B / 356kB", + "CPUPerc": "1.51%", + "Container": "lab2-codex-valkey-2", + "ID": "66d3137ad3ba", + "MemPerc": "0.10%", + "MemUsage": "9.258MiB / 8.722GiB", + "Name": "lab2-codex-valkey-2", + "NetIO": "501kB / 40.1kB", + "PIDs": "5" + } + ] + }, + { + "elapsed_seconds": 5.820394332986325, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "12.44%", + "Container": "lab2-codex-api", + "ID": "779f0c8b022a", + "MemPerc": "5.60%", + "MemUsage": "14.32MiB / 256MiB", + "Name": "lab2-codex-api", + "NetIO": "5.06MB / 12MB", + "PIDs": "7" + }, + { + "BlockIO": "0B / 606kB", + "CPUPerc": "3.86%", + "Container": "lab2-codex-pg", + "ID": "c9b65b8b3290", + "MemPerc": "0.34%", + "MemUsage": "30.64MiB / 8.722GiB", + "Name": "lab2-codex-pg", + "NetIO": "1.08MB / 615kB", + "PIDs": "11" + }, + { + "BlockIO": "0B / 21.5MB", + "CPUPerc": "4.87%", + "Container": "lab2-codex-valkey-0", + "ID": "45ccf9bbf6ef", + "MemPerc": "0.11%", + "MemUsage": "9.484MiB / 8.722GiB", + "Name": "lab2-codex-valkey-0", + "NetIO": "4.43MB / 514kB", + "PIDs": "5" + }, + { + "BlockIO": "0B / 24.6kB", + "CPUPerc": "0.07%", + "Container": "lab2-codex-valkey-1", + "ID": "39506ebb9902", + "MemPerc": "0.10%", + "MemUsage": "9.195MiB / 8.722GiB", + "Name": "lab2-codex-valkey-1", + "NetIO": "19.1kB / 6.24kB", + "PIDs": "5" + }, + { + "BlockIO": "0B / 1.68MB", + "CPUPerc": "2.08%", + "Container": "lab2-codex-valkey-2", + "ID": "66d3137ad3ba", + "MemPerc": "0.10%", + "MemUsage": "9.285MiB / 8.722GiB", + "Name": "lab2-codex-valkey-2", + "NetIO": "3.14MB / 217kB", + "PIDs": "5" + } + ] + }, + { + "elapsed_seconds": 8.944398958003148, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "13.06%", + "Container": "lab2-codex-api", + "ID": "779f0c8b022a", + "MemPerc": "5.65%", + "MemUsage": "14.46MiB / 256MiB", + "Name": "lab2-codex-api", + "NetIO": "7.4MB / 17.6MB", + "PIDs": "7" + }, + { + "BlockIO": "0B / 705kB", + "CPUPerc": "4.20%", + "Container": "lab2-codex-pg", + "ID": "c9b65b8b3290", + "MemPerc": "0.34%", + "MemUsage": "30.7MiB / 8.722GiB", + "Name": "lab2-codex-pg", + "NetIO": "1.78MB / 1.02MB", + "PIDs": "11" + }, + { + "BlockIO": "0B / 36MB", + "CPUPerc": "5.13%", + "Container": "lab2-codex-valkey-0", + "ID": "45ccf9bbf6ef", + "MemPerc": "0.11%", + "MemUsage": "9.562MiB / 8.722GiB", + "Name": "lab2-codex-valkey-0", + "NetIO": "7.44MB / 859kB", + "PIDs": "5" + }, + { + "BlockIO": "0B / 24.6kB", + "CPUPerc": "0.06%", + "Container": "lab2-codex-valkey-1", + "ID": "39506ebb9902", + "MemPerc": "0.10%", + "MemUsage": "9.195MiB / 8.722GiB", + "Name": "lab2-codex-valkey-1", + "NetIO": "19.4kB / 6.38kB", + "PIDs": "5" + }, + { + "BlockIO": "0B / 3.53MB", + "CPUPerc": "2.09%", + "Container": "lab2-codex-valkey-2", + "ID": "66d3137ad3ba", + "MemPerc": "0.10%", + "MemUsage": "9.297MiB / 8.722GiB", + "Name": "lab2-codex-valkey-2", + "NetIO": "6.69MB / 457kB", + "PIDs": "5" + } + ] + }, + { + "elapsed_seconds": 12.100759791006567, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.09%", + "Container": "lab2-codex-api", + "ID": "779f0c8b022a", + "MemPerc": "5.67%", + "MemUsage": "14.52MiB / 256MiB", + "Name": "lab2-codex-api", + "NetIO": "10.7MB / 25.5MB", + "PIDs": "7" + }, + { + "BlockIO": "0B / 705kB", + "CPUPerc": "0.09%", + "Container": "lab2-codex-pg", + "ID": "c9b65b8b3290", + "MemPerc": "0.34%", + "MemUsage": "30.71MiB / 8.722GiB", + "Name": "lab2-codex-pg", + "NetIO": "2.27MB / 1.3MB", + "PIDs": "11" + }, + { + "BlockIO": "0B / 45.5MB", + "CPUPerc": "0.56%", + "Container": "lab2-codex-valkey-0", + "ID": "45ccf9bbf6ef", + "MemPerc": "0.11%", + "MemUsage": "9.578MiB / 8.722GiB", + "Name": "lab2-codex-valkey-0", + "NetIO": "9.39MB / 1.08MB", + "PIDs": "5" + }, + { + "BlockIO": "0B / 24.6kB", + "CPUPerc": "0.36%", + "Container": "lab2-codex-valkey-1", + "ID": "39506ebb9902", + "MemPerc": "0.10%", + "MemUsage": "9.195MiB / 8.722GiB", + "Name": "lab2-codex-valkey-1", + "NetIO": "19.5kB / 6.46kB", + "PIDs": "5" + }, + { + "BlockIO": "0B / 4.65MB", + "CPUPerc": "1.83%", + "Container": "lab2-codex-valkey-2", + "ID": "66d3137ad3ba", + "MemPerc": "0.10%", + "MemUsage": "9.281MiB / 8.722GiB", + "Name": "lab2-codex-valkey-2", + "NetIO": "8.46MB / 578kB", + "PIDs": "5" + } + ] + } + ], + "limitations": "Docker sampled CPU/RAM; no continuous tracing, warmup is the public bootstrap only; one user and one chat intentionally encounter per-user rate limiting." +} diff --git a/evidence/load.json b/evidence/load.json new file mode 100644 index 00000000..9d205cf3 --- /dev/null +++ b/evidence/load.json @@ -0,0 +1,17 @@ +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.103, + "concurrency": 4, + "successful_requests": 541, + "failed_requests": 7075, + "error_ratio": 0.928965, + "successful_rps": 53.549, + "successful_latency_ms": { + "p50": 8.096, + "p95": 11.024, + "p99": 13.451 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..749fd29b --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,2 @@ +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/registry-build.txt b/evidence/registry-build.txt new file mode 100644 index 00000000..8827c670 --- /dev/null +++ b/evidence/registry-build.txt @@ -0,0 +1,101 @@ +python3 scripts/registry.py login --key "/Users/marlo/key.json" --registry "cr.yandex" +Login Succeeded +docker buildx build --platform "linux/amd64" -f Dockerfile --target runtime --tag "cr.yandex/crpv8disueqk68pv29jg/mtusi2026lab2:src-f83270eb02dcfc92bdb0" --metadata-file evidence/image-build.json --push . +#0 building with "asisti-builder" instance using docker-container driver + +#1 [internal] load build definition from Dockerfile +#1 transferring dockerfile: 583B done +#1 DONE 0.0s + +#2 [internal] load metadata for docker.io/library/golang:1.26.1-alpine3.23 +#2 DONE 2.9s + +#3 [internal] load .dockerignore +#3 transferring context: 145B done +#3 DONE 0.0s + +#4 [internal] load build context +#4 transferring context: 301.24kB 0.0s done +#4 DONE 0.0s + +#5 [build 1/7] FROM docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 +#5 resolve docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 done +#5 sha256:13ee208a3600503f47e9ec1ced0e8abb825a045473b092f1fe872b81d9873706 0B / 126B 0.2s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 0B / 67.22MB 0.2s +#5 sha256:13ee208a3600503f47e9ec1ced0e8abb825a045473b092f1fe872b81d9873706 126B / 126B 0.3s done +#5 sha256:644a983862e3898a5575fef5c81590cbc92d1c1e1bf5f61112c0cd35e6b7be98 0B / 296.07kB 0.2s +#5 sha256:589002ba0eaed121a1dbf42f6648f29e5be55d5c8a6ee0f8eaa0285cc21ac153 0B / 3.86MB 0.2s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 7.34MB / 67.22MB 1.1s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 11.53MB / 67.22MB 1.2s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 15.73MB / 67.22MB 1.4s +#5 sha256:644a983862e3898a5575fef5c81590cbc92d1c1e1bf5f61112c0cd35e6b7be98 296.07kB / 296.07kB 1.2s done +#5 sha256:589002ba0eaed121a1dbf42f6648f29e5be55d5c8a6ee0f8eaa0285cc21ac153 1.05MB / 3.86MB 2.0s +#5 sha256:589002ba0eaed121a1dbf42f6648f29e5be55d5c8a6ee0f8eaa0285cc21ac153 2.10MB / 3.86MB 2.1s +#5 sha256:589002ba0eaed121a1dbf42f6648f29e5be55d5c8a6ee0f8eaa0285cc21ac153 3.86MB / 3.86MB 2.3s done +#5 extracting sha256:589002ba0eaed121a1dbf42f6648f29e5be55d5c8a6ee0f8eaa0285cc21ac153 0.1s done +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 23.07MB / 67.22MB 2.6s +#5 extracting sha256:644a983862e3898a5575fef5c81590cbc92d1c1e1bf5f61112c0cd35e6b7be98 0.0s done +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 28.31MB / 67.22MB 2.9s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 33.55MB / 67.22MB 3.2s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 37.75MB / 67.22MB 3.5s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 41.94MB / 67.22MB 3.9s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 46.14MB / 67.22MB 4.4s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 50.33MB / 67.22MB 4.7s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 55.57MB / 67.22MB 5.1s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 60.82MB / 67.22MB 5.6s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 65.01MB / 67.22MB 5.9s +#5 sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 67.22MB / 67.22MB 6.1s done +#5 extracting sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 +#5 extracting sha256:6fbff1d4eb7eece408734c05c8c63a49bb181871bc1280cff3f0e28d25a4ea28 1.2s done +#5 DONE 7.3s + +#5 [build 1/7] FROM docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 +#5 extracting sha256:13ee208a3600503f47e9ec1ced0e8abb825a045473b092f1fe872b81d9873706 done +#5 extracting sha256:4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1 done +#5 DONE 7.3s + +#6 [build 2/7] WORKDIR /src +#6 DONE 0.3s + +#7 [build 3/7] COPY go.mod go.sum ./ +#7 DONE 0.0s + +#8 [build 4/7] RUN go mod download +#8 DONE 10.6s + +#9 [build 5/7] COPY cmd/ ./cmd/ +#9 DONE 0.0s + +#10 [build 6/7] COPY internal/ ./internal/ +#10 DONE 0.0s + +#11 [build 7/7] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server +#11 DONE 40.9s + +#12 [runtime 1/1] COPY --from=build /out/server /server +#12 DONE 0.0s + +#13 exporting to image +#13 exporting layers +#13 exporting layers 0.3s done +#13 exporting manifest sha256:b013c1fb52e8130c08ab1409ceb8377e3a050dd7f9244b890281f9dfb68ae741 +#13 exporting manifest sha256:b013c1fb52e8130c08ab1409ceb8377e3a050dd7f9244b890281f9dfb68ae741 done +#13 exporting config sha256:c0f3ec4f575e359e4dcc8cdb674eda57b4bc086ca36205ee05f28ff0c46986ba done +#13 exporting attestation manifest sha256:5529abb366b394bb0b0cee8b0cbc90481c65510437a866e5677f794136bbdff3 done +#13 exporting manifest list sha256:bd5a0157693a9c288e3691c6d187a7314a798a91ff42a36228c7381cc5ce6496 done +#13 pushing layers +#13 ... + +#14 [auth] crpv8disueqk68pv29jg/mtusi2026lab2:pull,push token for cr.yandex +#14 DONE 0.0s + +#13 exporting to image +#13 pushing layers 1.6s done +#13 pushing manifest for cr.yandex/crpv8disueqk68pv29jg/mtusi2026lab2:src-f83270eb02dcfc92bdb0@sha256:bd5a0157693a9c288e3691c6d187a7314a798a91ff42a36228c7381cc5ce6496 +#13 pushing manifest for cr.yandex/crpv8disueqk68pv29jg/mtusi2026lab2:src-f83270eb02dcfc92bdb0@sha256:bd5a0157693a9c288e3691c6d187a7314a798a91ff42a36228c7381cc5ce6496 1.7s done +#13 DONE 3.6s + +#15 resolving provenance for metadata file +#15 DONE 0.0s + +View build details: docker-desktop://dashboard/build/asisti-builder/asisti-builder0/odzr94z3rs2nxze2b46kn7pa1 diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..92154196 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1 @@ +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/sql-research-domain.json b/evidence/sql-research-domain.json new file mode 100644 index 00000000..662cee68 --- /dev/null +++ b/evidence/sql-research-domain.json @@ -0,0 +1,1184 @@ +{ + "date_utc": "2026-10-07T11:54:58.801374+00:00", + "hypothesis": "A composite history index reduces late-page reads compared with a chat-only index, at an additional write cost.", + "method": "100000 synthetic messages: 90% in chat 1, 9% in chat 2, 1% in chat 3. Compare identical late-page SELECT and 1000-row INSERT EXPLAIN ANALYZE BUFFERS (rolled back), three repetitions after ANALYZE.", + "versions": { + "postgres": "PostgreSQL 17.6 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 14.2.0) 14.2.0, 64-bit" + }, + "limitations": "Single local Docker host; synthetic isolated schema using the actual application migration; logical backup requires a quiescent comparison dataset; no WAL/PITR; restore shares the same PostgreSQL instance but uses a new database.", + "variants": [ + { + "name": "chat_only", + "columns": "chat_id", + "select_sql": "SELECT id,chat_id,sender_id,text,created_at FROM research_9d526446.messages WHERE chat_id=md5('1')::uuid AND (created_at,id)>('2026-01-01Z'::timestamptz+85000*interval '1 microsecond',md5('85000')::uuid) ORDER BY created_at,id LIMIT 51", + "insert_sql": "INSERT INTO research_9d526446.messages SELECT md5(n::text)::uuid,md5('1')::uuid,'11111111-1111-4111-8111-111111111111','new-synthetic-'||n,'2026-01-01Z'::timestamptz+n*interval '1 microsecond' FROM generate_series(100001,101000) AS n", + "select_plans": [ + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3685.76, + "Total Cost": 3685.88, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 7.601, + "Actual Total Time": 7.607, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1241, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3685.76, + "Total Cost": 3719.53, + "Plan Rows": 13511, + "Plan Width": 71, + "Actual Startup Time": 7.6, + "Actual Total Time": 7.603, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1241, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 3235.0, + "Plan Rows": 13511, + "Plan Width": 71, + "Actual Startup Time": 6.144, + "Actual Total Time": 7.191, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1235, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 103, + "Shared Read Blocks": 1, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.608, + "Triggers": [], + "Execution Time": 7.646 + } + ], + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3724.55, + "Total Cost": 3724.68, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 8.31, + "Actual Total Time": 8.317, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1254, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3724.55, + "Total Cost": 3758.69, + "Plan Rows": 13653, + "Plan Width": 71, + "Actual Startup Time": 8.308, + "Actual Total Time": 8.311, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1254, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 3269.06, + "Plan Rows": 13653, + "Plan Width": 71, + "Actual Startup Time": 6.567, + "Actual Total Time": 7.899, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1248, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 104, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.68, + "Triggers": [], + "Execution Time": 8.36 + } + ], + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3766.35, + "Total Cost": 3766.48, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 8.553, + "Actual Total Time": 8.559, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3766.35, + "Total Cost": 3800.87, + "Plan Rows": 13807, + "Plan Width": 71, + "Actual Startup Time": 8.551, + "Actual Total Time": 8.553, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 3305.72, + "Plan Rows": 13807, + "Plan Width": 71, + "Actual Startup Time": 6.921, + "Actual Total Time": 8.184, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1262, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 104, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.66, + "Triggers": [], + "Execution Time": 8.604 + } + ] + ], + "insert_plans": [ + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 7.514, + "Actual Total Time": 7.515, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 6080, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 22, + "Shared Written Blocks": 19, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.081, + "Actual Total Time": 1.819, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 21, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.411, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_17391", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 7.609, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17396", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 7.276, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17401", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 7.618, + "Calls": 1000 + } + ], + "Execution Time": 30.26 + } + ], + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 7.615, + "Actual Total Time": 7.616, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 7091, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 15, + "Shared Written Blocks": 15, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.063, + "Actual Total Time": 1.659, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 21, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.385, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_17391", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 7.476, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17396", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 7.355, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17401", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 7.321, + "Calls": 1000 + } + ], + "Execution Time": 30.009 + } + ], + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 7.642, + "Actual Total Time": 7.643, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 7103, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 14, + "Shared Written Blocks": 14, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.072, + "Actual Total Time": 1.706, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 21, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.439, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_17391", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 7.438, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17396", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 6.98, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17401", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 7.291, + "Calls": 1000 + } + ], + "Execution Time": 29.615 + } + ] + ] + }, + { + "name": "history_keyset", + "columns": "chat_id,created_at,id", + "select_sql": "SELECT id,chat_id,sender_id,text,created_at FROM research_9d526446.messages WHERE chat_id=md5('1')::uuid AND (created_at,id)>('2026-01-01Z'::timestamptz+85000*interval '1 microsecond',md5('85000')::uuid) ORDER BY created_at,id LIMIT 51", + "insert_sql": "INSERT INTO research_9d526446.messages SELECT md5(n::text)::uuid,md5('1')::uuid,'11111111-1111-4111-8111-111111111111','new-synthetic-'||n,'2026-01-01Z'::timestamptz+n*interval '1 microsecond' FROM generate_series(100001,101000) AS n", + "select_plans": [ + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 11.78, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 0.085, + "Actual Total Time": 0.097, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 2985.49, + "Plan Rows": 13397, + "Plan Width": 71, + "Actual Startup Time": 0.084, + "Actual Total Time": 0.092, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 122, + "Shared Read Blocks": 1, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.71, + "Triggers": [], + "Execution Time": 0.136 + } + ], + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 11.8, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.028, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 3020.1, + "Plan Rows": 13534, + "Plan Width": 71, + "Actual Startup Time": 0.019, + "Actual Total Time": 0.025, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 115, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.469, + "Triggers": [], + "Execution Time": 0.055 + } + ], + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 11.78, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 0.018, + "Actual Total Time": 0.026, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 3048.66, + "Plan Rows": 13681, + "Plan Width": 71, + "Actual Startup Time": 0.018, + "Actual Total Time": 0.023, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 115, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.598, + "Triggers": [], + "Execution Time": 0.062 + } + ] + ], + "insert_plans": [ + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 7.335, + "Actual Total Time": 7.337, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 8151, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 29, + "Shared Written Blocks": 26, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.07, + "Actual Total Time": 1.075, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 21, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.39, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_17391", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 6.761, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17396", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 6.278, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17401", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 6.428, + "Calls": 1000 + } + ], + "Execution Time": 26.984 + } + ], + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 7.21, + "Actual Total Time": 7.21, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 8119, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 15, + "Shared Written Blocks": 15, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.042, + "Actual Total Time": 1.326, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 21, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.239, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_17391", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 8.345, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17396", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 7.26, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17401", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 7.663, + "Calls": 1000 + } + ], + "Execution Time": 30.715 + } + ], + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 6.15, + "Actual Total Time": 6.151, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 8149, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 13, + "Shared Written Blocks": 13, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 37.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.058, + "Actual Total Time": 1.152, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 21, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.542, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_17391", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 6.747, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17396", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 6.355, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_17401", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 6.588, + "Calls": 1000 + } + ], + "Execution Time": 26.067 + } + ] + ] + } + ], + "source_snapshot_sha256": "df5a6a8d97058191dfc0a2f1378a09a0d1d43c918f268c0b79e00579b317aa80", + "backup_seconds": 0.25334600001224317, + "backup_bytes": 15684575, + "restore_seconds": 0.46191787501447834, + "verification": { + "before": "100000|aad2b0e3a8548b1c909b9a7826835a07", + "after": "100000|aad2b0e3a8548b1c909b9a7826835a07", + "equal": true + }, + "samples": [ + { + "id": "c4ca4238-a0b9-2382-0dcc-509a6f75849b", + "chat_id": "c4ca4238-a0b9-2382-0dcc-509a6f75849b", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-1", + "created_at": "2026-01-01T00:00:00.000001+00:00" + }, + { + "id": "1017bfd4-6739-55ff-ee46-41ad3d481b1c", + "chat_id": "c4ca4238-a0b9-2382-0dcc-509a6f75849b", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-50000", + "created_at": "2026-01-01T00:00:00.05+00:00" + }, + { + "id": "e98ff526-ad76-393f-7dfb-9717aa548154", + "chat_id": "c4ca4238-a0b9-2382-0dcc-509a6f75849b", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-90000", + "created_at": "2026-01-01T00:00:00.09+00:00" + }, + { + "id": "5256ce97-fefe-0f76-9da7-cb6e350dfc0e", + "chat_id": "c81e728d-9d4c-2f63-6f06-7f89cc14862c", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-99000", + "created_at": "2026-01-01T00:00:00.099+00:00" + }, + { + "id": "14ee22ea-ba29-7944-c96a-fdbe5b16c65b", + "chat_id": "eccbc87e-4b5c-e2fe-2830-8fd9f2a7baf3", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-100000", + "created_at": "2026-01-01T00:00:00.1+00:00" + } + ] +} diff --git a/evidence/sql-research-helm.txt b/evidence/sql-research-helm.txt new file mode 100644 index 00000000..2ccbe5ba --- /dev/null +++ b/evidence/sql-research-helm.txt @@ -0,0 +1,1284 @@ +UTC: 2026-10-07T14:01:48Z +Hypothesis: composite index improves late-page reads, with additional write cost. +100000 rows, distribution 90/9/1%; three reads and 1000-row rollback writes per index. +Limits: 1 CPU, 512MiB; single local Docker instance; no concurrent writes or PITR. +Image: sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94 +2c8e791d08fca312f52a40e082b18dc82676e891df57c04fbca1334d5edcfa26 cmd/server/app.go +8fabb622999b681eb42452bfd349f71b53ad979e41f2ae57189d34c099bb3ee2 cmd/server/app_test.go +7290636ea31539d87bd97bb78cb28658409da966be8983e748ce1701f6f9f8f6 cmd/server/commands.go +b0a0c1689dfe2db5abc889af13d7adb00a1d4f3d260b5ebe6d5f529cb5983a0e cmd/server/healthcheck.go +900039906536a81de51dc45af3904a7e44b4739d56690dd59f915d03d092c7e9 cmd/server/healthcheck_test.go +43ad9caf2260d8551b8b3e149681c5e66770e9901d72de41b81746cb0cac47ec cmd/server/logger.go +c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495 cmd/server/main.go +06b304d8f0cad20c206edbef8becab283c50c1722fd81c56a06f018dfe03bb7f cmd/server/persistence.go +aaf096a8c0abb9e6860d5cd620a5b0580c130276374a09f21ac3a7790273385f cmd/server/persistence_test.go +41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d internal/admission/distributed.go +a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4 internal/admission/limiter.go +d52fb501e76ddb23c645c1aaa599e32da9d01e50064c9ca97ac0e320ffc7f0c8 internal/admission/limiter_test.go +8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa internal/config/config.go +0181673dcc4db2557783941aa8c5b3f61bc0ca6b5196d87e69df000346c40391 internal/config/config_test.go +e784d7b934c4604065cd00bf4ff2b0c74741e759b1b7c81162adfc206d160153 internal/config/controller.go +027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3 internal/config/environment.go +3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988 internal/config/logger.go +86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0 internal/config/memory.go +671f92c52c827989ce194f3928b02f707292022bb97d3c483410e97cf626b4af internal/config/persistence.go +7377c7fc286e04292b7c82e4e286cadf409ce833079f794a501456024e73434a internal/config/persistence_test.go +af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a internal/controller/fx.go +3107673b329dbe7934a29679024a18e3baada2cc99bee4d0ddbba0f9fd93edf9 internal/controller/http/fiber/auth.go +960cd6ea803ea4ef9b0231ce557fc5e792921aae343f33da6e8aca12495da39f internal/controller/http/fiber/auth_test.go +9c092ba7bca191f25c3ba9c9a5d1ca844126bee740a4c0262b776e947263ac68 internal/controller/http/fiber/chats_test.go +be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd internal/controller/http/fiber/configure.go +fd0d06ac838c8ceca1189303b98ce006ca1298381de49fe6d790d0f0f4007d3e internal/controller/http/fiber/controller.go +151fb360bc3f7309678961b7739c5d905f3430bc4e63fb6c9b26495e12ab7227 internal/controller/http/fiber/controller_test.go +bb4216cb6c5813b66b51dc99a53f8cf09982789155305a099c321dd12fa8e2de internal/controller/http/fiber/decode.go +6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d internal/controller/http/fiber/dependencies.go +3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41 internal/controller/http/fiber/error_codes.go +9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a internal/controller/http/fiber/error_registry.go +d502e2a9f7fe3980c10c2760c31711794898c539d07b43b02497dc2cfb870358 internal/controller/http/fiber/errors.go +81e95e02b6e41929bf8e73f65e2d4921fc6471293815d590d38ad7d849106f3c internal/controller/http/fiber/errors_test.go +49bb58b260f2df9473d8e0ae01b8c3c742e4266db00d64fe5e999730aba42a80 internal/controller/http/fiber/fixtures_auth_test.go +59e3f16adc94b7426c74e2f40b5ff18a9129c80fc619cb8144110bdeec095021 internal/controller/http/fiber/handlers.go +d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd internal/controller/http/fiber/headers.go +6d18f3c4be98e70a7e61d82b014b6db9b3a5e594c9b5f50ecea88f89bd6917cd internal/controller/http/fiber/health.go +f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08 internal/controller/http/fiber/lifecycle.go +496f50e5693456574614b8a47086a550018884adb37919ce82abf8c4e7e5254d internal/controller/http/fiber/lifecycle_test.go +f63d4b0e2ee5f62c4d0d8c4b26a8734d68230af4577e3c6cb71a92525c3c8681 internal/controller/http/fiber/mapping.go +d848e00aff04d7a3339ca1847f47cad59fb7c05085f6cfb1965b27df516acdd6 internal/controller/http/fiber/messages_test.go +34fd687af80730601ba9276ef606fee76df84d14b4400a65ec5b804897673536 internal/controller/http/fiber/middleware.go +5259d44ea6c7d4e1776f5b66e00408d1450fdf859e2017bf14937d3020f3dcff internal/controller/http/fiber/middleware_test.go +d806c2d026a8ff2fc54d60b62c062e80a3532e652fcfa5c3105684ba17cc9f67 internal/controller/http/fiber/public_errors.go +47089b63442f02d6e637a8dd785e323e97efb15fd82d2ffa303e7e10de4876cd internal/controller/http/fiber/public_errors_test.go +826fe61b8d59465de7190c175b6abaa118f4a7deacdb1b9c628e25bb7f4feb3b internal/controller/http/fiber/routes.go +0b3fad8fc87f561573bf4ee906a48a8fb317385ecc7600bdca3cc61992fa9253 internal/controller/http/fiber/users_test.go +24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68 internal/controller/interface.go +a5bc7aac6d1764929fb11365c9f8b6a45ff65e47b3a317a7ccd9ec6dd1b2713a internal/cursor/codec.go +a611b59197a205fd21fd94077577f2db7024266cd5ce8a5bfb18a85196bd357b internal/cursor/codec_test.go +e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c internal/hashring/ring.go +606cdf84342b97a63eedfb9cd37aa7c99a489eee54641d8645be930a9ce6be0d internal/hashring/ring_test.go +e2ecd732848d10f4471567c9603aa7359fcb1af7b2708ead477f4949f7a2fa4a internal/model/dto/models.go +896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb internal/model/dto/session.go +8c183b065bc3ab4cad20570eab79f334ca75a3309186fdf832fb1aa598894465 internal/model/http/models.go +fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76 internal/password/password.go +1ad8dcb7d055fcb8da56d10e1089b47fe1b9cbf848381ded1a4048f8fd41278a internal/password/password_test.go +ede0474befff6773779dd448e9b42a98bd2edb12033b65366e5f65618ec4885e internal/service/auth.go +1cc82be87998dc9b66216965dc3ac37aa6c210c1007fc46a2a0bd698e9cb6167 internal/service/authentication/service.go +c77137c6799dc1f9012387e45c21414ced2d7e0923b6f2750a09f61b76c6523a internal/service/authentication/service_test.go +55baf7ba65292ae6a75b7a6af8d304886f35c7ad854b8d700251d6f32c964dbf internal/service/cache.go +07244e89d9948087318df2dfecfb3a648c217bc313fb033748f5562e08ba8a95 internal/service/cursor.go +e19c47379f63a5ee7e24b9b0fded1eb326ea231392b4e27c324d205d4c620f7d internal/service/errors.go +017b13007719a32a8eec26527848231381590e5632790bedec66a126776bad6e internal/service/interface.go +fc191b98aaf0488cb60f258c3ce9788708818c7f299a10f80e91568adabd05e5 internal/service/production/access.go +af0659140715e467ab15388cc75aea8b2ff09b8edbbd5dc90aa6d3f5c24bf5bf internal/service/production/cache_test.go +881f9269ad84ab5dc091fdec8ad6c36bebd2eaac0da0685b8d333216e0a2dd16 internal/service/production/chats.go +8eb5b603aeb7be2d5e5af859762610e26c8ad7c05fa222e04802950dd71f9c21 internal/service/production/chats_page_test.go +e7d4fa61a14f7cb4ba421ed5e83d794a85b42fac597e269807d564c830e2cbb8 internal/service/production/chats_test.go +fe5940f705df32902151d51f82c7f9f1df3e274e62413d9e1b54f2a512707d48 internal/service/production/creation.go +7495818188cc13028d9400dfa18005e9aa334ac048b7a84150dd2b6ddb28d796 internal/service/production/errors.go +007b27ba3005a3040283b35b7640523bc8ae04ada89b2731396b1559c3b20075 internal/service/production/fixture_test.go +1f5c9335bf4cf5b9f4137454e3ca22975e7c6c7118e4e60bb470851f8a7cd61e internal/service/production/members.go +6bdd523dd8be7ce139a0a7f2c9ee16d8d2f03e4d15ed00e7a31658c23fb97c17 internal/service/production/messages.go +7b82f74aedb2f26079cce497778302246e9166c365508e37266a97078df5ca5c internal/service/production/messages_page_test.go +6722838a6c117f76fb2710d664ec4ce9945479f18013af18437cf93814351d93 internal/service/production/messages_test.go +4306cd592bdcd2dd5c31eeadc0dc5e1a59b275ffa6de091032edf644171020c5 internal/service/production/pages.go +f0611bc8ad150fcac5505a6696bd293a144274431fb71b3e96f16a8229b85bcc internal/service/production/pages_test.go +4cb0d47ef9cc020e608f93a8257b6d65136f6f74b86c3f591f19dad688fc7bf0 internal/service/production/pagination.go +1886cbbaa88de20d0e21bf6c1c35fde64164547fa86c1fb74860c93f59b5fc9b internal/service/production/pagination_test.go +70fb90d812432e321c4fca1b1e2141cfad91453e294f4efda60c0898be686d7d internal/service/production/service.go +b8ab1e6e92a365f38fb5ac660e311a00fea6a458c6c9cd9c8184dbaebb419f50 internal/service/production/service_test.go +50d873980bdc97a799c2e61a4b25c5bd222a32bd7baed28590510ef373ac0461 internal/service/production/users.go +04e0cb7a51877014ef23a8063ca435e3eb5e98fb78902ff166abc08139287315 internal/service/production/users_test.go +6aa0ff490fe8fca8b906b5073e0914a64369ddfc7d0648d895cc41cb69cdd2e0 internal/service/production/validation.go +ea599de0e0d2a0be7de7b0835307a4d1852db16a49bfad3636f7c30b85181fce internal/store/interface.go +ac2aafe9f19706ff39b16a4ca1b1e142f6e52bef160ef591f9f2120d106ffd51 internal/store/memory/capacity.go +150851ac6a0d5da8835a9aaaa7c1156b075e5e3dd962698fb483b0afa8a2097f internal/store/memory/chats.go +3036029e86462d8cf52aad993c4f9eff62a5cf0454e757b871abfd5b4902c9f5 internal/store/memory/chats_test.go +94f2a5ce429aa8280e1333760309fd1d02b314310cbdea495aef56a63ed145b1 internal/store/memory/messages.go +76f977bbabec7550093ca9d376efc9686345198cbee5e13ce31d38dcd425a469 internal/store/memory/messages_test.go +4aef07be1cb907cfa7a4a3d78060d8be57c9ff566c16e729dea9b0db68c7dfae internal/store/memory/ordering.go +f463d530955bfe5793fb9a4ad93d6615a3ce923d1d4719b8c515f487c96997ca internal/store/memory/store.go +b7f8237e22eac473ad47cd879238aed7ed16e08b28a6ff3029ddcc58072dfe0e internal/store/memory/store_test.go +1652a23bc8fc29a6ef00851a19d4547b660f3bfcce9d458b7381db5b3f30778c internal/store/memory/users.go +dc9a73504116b7e54d38a4e3b8c88ed1aa4c1144efdb9bb3ac671e0e1182d9a3 internal/store/memory/users_test.go +b9d69046cd919957434da02c635d259c8e36f27371270afedc312947eb5bb615 internal/store/postgres/chats.go +1ab5dd2f8d81697a57ee89e1969995e52bfccc0f3f25a5c480822e41313988f1 internal/store/postgres/messages.go +8b8bf6a255cc48cee4b3e4adc94c23cf6955ecf5dfba689bba973dfccbd1b1cb internal/store/postgres/migrations/001_initial.sql +6f7f2e86822d806640888da990716279659fe90e5a74b3b0d5454a5155d0334b internal/store/postgres/sessions.go +5f3e022a414103198a1ab8e62f337e67c22afd1afddda400884b79a5e51488a2 internal/store/postgres/store.go +538f1739eae4c276aa6b5df9aa8c4f4c3aca4a3043a71650256f257ffaaed029 internal/store/postgres/store_test.go +2721381975755efe2a4f14a8df3c1189d2dcc6c7933fc25292977014c26aa220 internal/store/postgres/users.go +ef9bfaf3bd684fded87c92a15b3e5c706a794caf04cc4ef711c4185e9c7fb12a internal/strictjson/decode.go +ea6273526572b4bfcf681ef2659ea2c1ec74bfedeb5e9bdbd83ebfabe0647bf9 internal/strictjson/decode_test.go +4baa4e399be201189371d1ace6169e56958251386624af4996fac04e0ab5d1f7 internal/valkey/admission.go +693b866a740b6d5f765221be4c6489391821d4b58942cf0ff36030163dbae6a9 internal/valkey/cache.go +86acf0827e1d29993eda7ee62a8fa42b02d707330a94a70f5a3933911407e882 internal/valkey/client.go +b39e08ecc720e1d4fc81d342fa15192c0a0a82e849231161c1e0d2da2d8f625d internal/valkey/client_test.go +5ea8c967f238b30a5f54ced22b0318832254ff99e5bcc4af145aee08d7f8c8da scripts/research.sh +f47019141be4ac06d912cbd4281d94d181625a08637801627e897633bb20a124 student-tests/plans.sql +f7ca02dfce0db42f72594d794eda5821a9125e7a2b6966df731f32869a5f0b43 student-tests/research.sql +Timing is on. +PostgreSQL 17.6 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 14.2.0) 14.2.0, 64-bit +Time: 0.459 ms +INSERT 0 1 +Time: 0.790 ms +INSERT 0 3 +Time: 1.172 ms +INSERT 0 3 +Time: 0.978 ms +INSERT 0 100000 +Time: 1729.487 ms (00:01.729) +DROP INDEX +Time: 1.273 ms +CREATE INDEX +Time: 13.915 ms +VARIANT: chat_only +ANALYZE +Time: 35.241 ms +[ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3686.59, + "Total Cost": 3686.72, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 4.354, + "Actual Total Time": 4.358, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1235, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3686.59, + "Total Cost": 3720.43, + "Plan Rows": 13536, + "Plan Width": 71, + "Actual Startup Time": 4.354, + "Actual Total Time": 4.355, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": ["created_at", "id"], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1235, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 3235.00, + "Plan Rows": 13536, + "Plan Width": 71, + "Actual Startup Time": 3.486, + "Actual Total Time": 4.129, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1235, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 33, + "Shared Read Blocks": 1, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.132, + "Triggers": [ + ], + "Execution Time": 4.380 + } +] +BEGIN +[ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.636, + "Actual Total Time": 3.636, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 6037, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 22, + "Shared Written Blocks": 19, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.034, + "Actual Total Time": 1.017, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.048, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_16431", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 5.081, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16436", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 4.982, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16441", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 5.075, + "Calls": 1000 + } + ], + "Execution Time": 18.904 + } +] +ROLLBACK +Time: 24.006 ms +[ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3725.42, + "Total Cost": 3725.55, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 4.327, + "Actual Total Time": 4.331, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1248, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3725.42, + "Total Cost": 3759.62, + "Plan Rows": 13679, + "Plan Width": 71, + "Actual Startup Time": 4.327, + "Actual Total Time": 4.328, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": ["created_at", "id"], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1248, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 3269.06, + "Plan Rows": 13679, + "Plan Width": 71, + "Actual Startup Time": 3.501, + "Actual Total Time": 4.113, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1248, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.080, + "Triggers": [ + ], + "Execution Time": 4.347 + } +] +BEGIN +[ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.093, + "Actual Total Time": 3.093, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 7044, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 15, + "Shared Written Blocks": 15, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.041, + "Actual Total Time": 0.944, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.035, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_16431", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 4.676, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16436", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 4.557, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16441", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 4.767, + "Calls": 1000 + } + ], + "Execution Time": 17.223 + } +] +ROLLBACK +Time: 21.961 ms +[ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3767.18, + "Total Cost": 3767.31, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 4.047, + "Actual Total Time": 4.051, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1262, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3767.18, + "Total Cost": 3801.76, + "Plan Rows": 13832, + "Plan Width": 71, + "Actual Startup Time": 4.047, + "Actual Total Time": 4.049, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": ["created_at", "id"], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1262, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 3305.72, + "Plan Rows": 13832, + "Plan Width": 71, + "Actual Startup Time": 3.225, + "Actual Total Time": 3.843, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1262, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.048, + "Triggers": [ + ], + "Execution Time": 4.062 + } +] +BEGIN +[ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 2.858, + "Actual Total Time": 2.859, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 7056, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 14, + "Shared Written Blocks": 14, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.028, + "Actual Total Time": 0.876, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.036, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_16431", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 4.890, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16436", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 4.752, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16441", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 5.050, + "Calls": 1000 + } + ], + "Execution Time": 17.684 + } +] +ROLLBACK +Time: 22.065 ms +Time: 0.119 ms +DROP INDEX +Time: 1.160 ms +CREATE INDEX +Time: 25.346 ms +VARIANT: history_keyset +ANALYZE +Time: 29.509 ms +[ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 11.77, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 0.019, + "Actual Total Time": 0.024, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 2986.47, + "Plan Rows": 13418, + "Plan Width": 71, + "Actual Startup Time": 0.019, + "Actual Total Time": 0.022, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 28, + "Shared Read Blocks": 1, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.145, + "Triggers": [ + ], + "Execution Time": 0.034 + } +] +BEGIN +[ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.555, + "Actual Total Time": 3.555, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 8094, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 29, + "Shared Written Blocks": 26, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.032, + "Actual Total Time": 0.919, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.028, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_16431", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 4.942, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16436", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 4.895, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16441", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 5.082, + "Calls": 1000 + } + ], + "Execution Time": 18.613 + } +] +ROLLBACK +Time: 19.066 ms +[ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 11.78, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 0.013, + "Actual Total Time": 0.020, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 3020.50, + "Plan Rows": 13554, + "Plan Width": 71, + "Actual Startup Time": 0.013, + "Actual Total Time": 0.017, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.054, + "Triggers": [ + ], + "Execution Time": 0.029 + } +] +BEGIN +[ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.419, + "Actual Total Time": 3.419, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 8061, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 15, + "Shared Written Blocks": 15, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.032, + "Actual Total Time": 0.918, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.022, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_16431", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 4.698, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16436", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 4.610, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16441", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 4.897, + "Calls": 1000 + } + ], + "Execution Time": 17.747 + } +] +ROLLBACK +Time: 18.036 ms +[ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 11.77, + "Plan Rows": 51, + "Plan Width": 71, + "Actual Startup Time": 0.011, + "Actual Total Time": 0.017, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 3049.09, + "Plan Rows": 13702, + "Plan Width": 71, + "Actual Startup Time": 0.010, + "Actual Total Time": 0.014, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'c4ca4238-a0b9-2382-0dcc-509a6f75849b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 'dedbbd60-c592-c7ad-b64f-8ef8f0a025dc'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.035, + "Triggers": [ + ], + "Execution Time": 0.024 + } +] +BEGIN +[ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.376, + "Actual Total Time": 3.377, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 8091, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 13, + "Shared Written Blocks": 13, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.00, + "Total Cost": 37.50, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.032, + "Actual Total Time": 0.926, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.021, + "Triggers": [ + { + "Trigger Name": "RI_ConstraintTrigger_c_16431", + "Constraint Name": "messages_chat_id_fkey", + "Relation": "messages", + "Time": 9.403, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16436", + "Constraint Name": "messages_sender_id_fkey", + "Relation": "messages", + "Time": 4.799, + "Calls": 1000 + }, + { + "Trigger Name": "RI_ConstraintTrigger_c_16441", + "Constraint Name": "messages_chat_id_sender_id_fkey", + "Relation": "messages", + "Time": 4.972, + "Calls": 1000 + } + ], + "Execution Time": 22.682 + } +] +ROLLBACK +Time: 22.961 ms +Time: 0.139 ms + +real 0m0.277s +user 0m0.020s +sys 0m0.047s + +real 0m0.469s +user 0m0.019s +sys 0m0.027s +PASS: restore row count and checksum match +100000|452ef7ddb29fb8f662613e2f14934870 + 15684027 + id | text +--------------------------------------+------------------ + 1017bfd4-6739-55ff-ee46-41ad3d481b1c | synthetic-50000 + 14ee22ea-ba29-7944-c96a-fdbe5b16c65b | synthetic-100000 + c4ca4238-a0b9-2382-0dcc-509a6f75849b | synthetic-1 +(3 rows) + diff --git a/evidence/sql-research.json b/evidence/sql-research.json new file mode 100644 index 00000000..93cec823 --- /dev/null +++ b/evidence/sql-research.json @@ -0,0 +1,1052 @@ +{ + "date_utc": "2026-10-07T11:54:15.607806+00:00", + "hypothesis": "A composite history index reduces late-page reads compared with a chat-only index, at an additional write cost.", + "method": "100000 synthetic messages: 90% in chat 1, 9% in chat 2, 1% in chat 3. Compare identical late-page SELECT and 1000-row INSERT EXPLAIN ANALYZE BUFFERS (rolled back), three repetitions after ANALYZE.", + "versions": { + "postgres": "PostgreSQL 17.6 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 14.2.0) 14.2.0, 64-bit" + }, + "limitations": "Single local Docker host; synthetic isolated schema; logical backup requires a quiescent comparison dataset; no WAL/PITR; restore shares the same PostgreSQL instance but uses a new database.", + "variants": [ + { + "name": "chat_only", + "columns": "chat_id", + "select_sql": "SELECT id,chat_id,sender_id,text,created_at FROM research_c99ee862.history WHERE chat_id=1 AND (created_at,id)>('2026-01-01Z'::timestamptz+85000*interval '1 microsecond',85000) ORDER BY created_at,id LIMIT 51", + "insert_sql": "INSERT INTO research_c99ee862.history SELECT n,1,'11111111-1111-4111-8111-111111111111','new-synthetic-'||n,'2026-01-01Z'::timestamptz+n*interval '1 microsecond' FROM generate_series(100001,101000) AS n", + "select_plans": [ + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3479.35, + "Total Cost": 3479.48, + "Plan Rows": 51, + "Plan Width": 51, + "Actual Startup Time": 7.137, + "Actual Total Time": 7.143, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1037, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3479.35, + "Total Cost": 3512.95, + "Plan Rows": 13439, + "Plan Width": 51, + "Actual Startup Time": 7.136, + "Actual Total Time": 7.138, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1037, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 3031.0, + "Plan Rows": 13439, + "Plan Width": 51, + "Actual Startup Time": 5.911, + "Actual Total Time": 6.801, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 1) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 85000)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1031, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "Shared Read Blocks": 1, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.412, + "Triggers": [], + "Execution Time": 7.2 + } + ], + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3519.84, + "Total Cost": 3519.97, + "Plan Rows": 51, + "Plan Width": 51, + "Actual Startup Time": 6.553, + "Actual Total Time": 6.56, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1049, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3519.84, + "Total Cost": 3553.83, + "Plan Rows": 13595, + "Plan Width": 51, + "Actual Startup Time": 6.55, + "Actual Total Time": 6.552, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1049, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 3066.28, + "Plan Rows": 13595, + "Plan Width": 51, + "Actual Startup Time": 5.289, + "Actual Total Time": 6.237, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 1) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 85000)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1043, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 114, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.421, + "Triggers": [], + "Execution Time": 6.619 + } + ], + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3556.98, + "Total Cost": 3557.11, + "Plan Rows": 51, + "Plan Width": 51, + "Actual Startup Time": 4.895, + "Actual Total Time": 4.899, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1060, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3556.98, + "Total Cost": 3591.33, + "Plan Rows": 13739, + "Plan Width": 51, + "Actual Startup Time": 4.894, + "Actual Total Time": 4.896, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 31, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1060, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 3098.62, + "Plan Rows": 13739, + "Plan Width": 51, + "Actual Startup Time": 4.022, + "Actual Total Time": 4.664, + "Actual Rows": 5000, + "Actual Loops": 1, + "Filter": "((chat_id = 1) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 85000)))", + "Rows Removed by Filter": 95000, + "Shared Hit Blocks": 1054, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 114, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.263, + "Triggers": [], + "Execution Time": 4.934 + } + ] + ], + "insert_plans": [ + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 2.492, + "Actual Total Time": 2.492, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 5077, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 20, + "Shared Written Blocks": 16, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 1000, + "Plan Width": 68, + "Actual Startup Time": 0.071, + "Actual Total Time": 0.287, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.141, + "Triggers": [], + "Execution Time": 2.546 + } + ], + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 2.231, + "Actual Total Time": 2.232, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 5684, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 12, + "Shared Written Blocks": 12, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 1000, + "Plan Width": 68, + "Actual Startup Time": 0.045, + "Actual Total Time": 0.195, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.11, + "Triggers": [], + "Execution Time": 2.274 + } + ], + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 2.158, + "Actual Total Time": 2.159, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 5642, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 13, + "Shared Written Blocks": 13, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 1000, + "Plan Width": 68, + "Actual Startup Time": 0.042, + "Actual Total Time": 0.199, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.073, + "Triggers": [], + "Execution Time": 2.186 + } + ] + ] + }, + { + "name": "history_keyset", + "columns": "chat_id,created_at,id", + "select_sql": "SELECT id,chat_id,sender_id,text,created_at FROM research_c99ee862.history WHERE chat_id=1 AND (created_at,id)>('2026-01-01Z'::timestamptz+85000*interval '1 microsecond',85000) ORDER BY created_at,id LIMIT 51", + "insert_sql": "INSERT INTO research_c99ee862.history SELECT n,1,'11111111-1111-4111-8111-111111111111','new-synthetic-'||n,'2026-01-01Z'::timestamptz+n*interval '1 microsecond' FROM generate_series(100001,101000) AS n", + "select_plans": [ + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 9.84, + "Plan Rows": 51, + "Plan Width": 51, + "Actual Startup Time": 0.065, + "Actual Total Time": 0.071, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.42, + "Total Cost": 2490.25, + "Plan Rows": 13482, + "Plan Width": 51, + "Actual Startup Time": 0.064, + "Actual Total Time": 0.067, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 1) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 85000)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 1, + "Shared Read Blocks": 3, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 124, + "Shared Read Blocks": 1, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.345, + "Triggers": [], + "Execution Time": 0.119 + } + ], + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 9.84, + "Plan Rows": 51, + "Plan Width": 51, + "Actual Startup Time": 0.029, + "Actual Total Time": 0.038, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.42, + "Total Cost": 2517.4, + "Plan Rows": 13621, + "Plan Width": 51, + "Actual Startup Time": 0.028, + "Actual Total Time": 0.033, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 1) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 85000)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 125, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.525, + "Triggers": [], + "Execution Time": 0.102 + } + ], + [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 9.83, + "Plan Rows": 51, + "Plan Width": 51, + "Actual Startup Time": 0.03, + "Actual Total Time": 0.038, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.42, + "Total Cost": 2539.99, + "Plan Rows": 13760, + "Plan Width": 51, + "Actual Startup Time": 0.029, + "Actual Total Time": 0.033, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 1) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.085'::interval), 85000)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 125, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.473, + "Triggers": [], + "Execution Time": 0.095 + } + ] + ], + "insert_plans": [ + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.504, + "Actual Total Time": 3.505, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 6592, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 23, + "Shared Written Blocks": 20, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 1000, + "Plan Width": 68, + "Actual Startup Time": 0.043, + "Actual Total Time": 0.259, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.093, + "Triggers": [], + "Execution Time": 3.552 + } + ], + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 4.028, + "Actual Total Time": 4.028, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 6657, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 12, + "Shared Written Blocks": 12, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 1000, + "Plan Width": 68, + "Actual Startup Time": 0.081, + "Actual Total Time": 0.324, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.169, + "Triggers": [], + "Execution Time": 4.084 + } + ], + [ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "history", + "Alias": "history", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.288, + "Actual Total Time": 3.288, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 6630, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 12, + "Shared Written Blocks": 12, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "n", + "Startup Cost": 0.0, + "Total Cost": 27.5, + "Plan Rows": 1000, + "Plan Width": 68, + "Actual Startup Time": 0.053, + "Actual Total Time": 0.241, + "Actual Rows": 1000, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.107, + "Triggers": [], + "Execution Time": 3.328 + } + ] + ] + } + ], + "source_snapshot_sha256": "df5a6a8d97058191dfc0a2f1378a09a0d1d43c918f268c0b79e00579b317aa80", + "backup_seconds": 0.2908229580207262, + "backup_bytes": 9068166, + "restore_seconds": 0.33597395799006335, + "verification": { + "before": "100000|f837d280b69f13bebe461b9e6f81bcac", + "after": "100000|f837d280b69f13bebe461b9e6f81bcac", + "equal": true + }, + "samples": [ + { + "id": 1, + "chat_id": 1, + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-1", + "created_at": "2026-01-01T00:00:00.000001+00:00" + }, + { + "id": 50000, + "chat_id": 1, + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-50000", + "created_at": "2026-01-01T00:00:00.05+00:00" + }, + { + "id": 90000, + "chat_id": 1, + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-90000", + "created_at": "2026-01-01T00:00:00.09+00:00" + }, + { + "id": 99000, + "chat_id": 2, + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-99000", + "created_at": "2026-01-01T00:00:00.099+00:00" + }, + { + "id": 100000, + "chat_id": 3, + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "synthetic-100000", + "created_at": "2026-01-01T00:00:00.1+00:00" + } + ] +} diff --git a/evidence/timeweb-chart-check.txt b/evidence/timeweb-chart-check.txt new file mode 100644 index 00000000..ddb771d3 --- /dev/null +++ b/evidence/timeweb-chart-check.txt @@ -0,0 +1,6 @@ +helm lint charts/messenger -f "charts/messenger/values.yaml" +==> Linting charts/messenger +[INFO] Chart.yaml: icon is recommended + +1 chart(s) linted, 0 chart(s) failed +helm template "lab2" charts/messenger -n "highload-applications" -f "charts/messenger/values.yaml" > /dev/null diff --git a/evidence/timeweb-counts-after.txt b/evidence/timeweb-counts-after.txt new file mode 100644 index 00000000..52529e30 --- /dev/null +++ b/evidence/timeweb-counts-after.txt @@ -0,0 +1 @@ +36|12|18 diff --git a/evidence/timeweb-counts-before.txt b/evidence/timeweb-counts-before.txt new file mode 100644 index 00000000..52529e30 --- /dev/null +++ b/evidence/timeweb-counts-before.txt @@ -0,0 +1 @@ +36|12|18 diff --git a/evidence/timeweb-image-build.json b/evidence/timeweb-image-build.json new file mode 100644 index 00000000..b7378483 --- /dev/null +++ b/evidence/timeweb-image-build.json @@ -0,0 +1,20 @@ +{ + "buildx.build.provenance": { + "buildType": "", + "invocation": { + "configSource": {}, + "parameters": {}, + "environment": { + "platform": "" + } + } + }, + "buildx.build.ref": "asisti-builder/asisti-builder0/sckql9y8ls7gr3q918peqrjkh", + "containerimage.descriptor": { + "mediaType": "application/vnd.oci.image.index.v1+json", + "digest": "sha256:3f19c9feb306a88044cc46b25d99592d48f04c21eba477d59676486277b2956c", + "size": 855 + }, + "containerimage.digest": "sha256:3f19c9feb306a88044cc46b25d99592d48f04c21eba477d59676486277b2956c", + "image.name": "asisti.registry.twcstorage.ru/mtusi2026lab2:87e1e5d" +} \ No newline at end of file diff --git a/evidence/timeweb-image-inspect.txt b/evidence/timeweb-image-inspect.txt new file mode 100644 index 00000000..c67d5024 --- /dev/null +++ b/evidence/timeweb-image-inspect.txt @@ -0,0 +1,15 @@ +Name: asisti.registry.twcstorage.ru/mtusi2026lab2@sha256:3f19c9feb306a88044cc46b25d99592d48f04c21eba477d59676486277b2956c +MediaType: application/vnd.oci.image.index.v1+json +Digest: sha256:3f19c9feb306a88044cc46b25d99592d48f04c21eba477d59676486277b2956c + +Manifests: + Name: asisti.registry.twcstorage.ru/mtusi2026lab2@sha256:db441136cf48247e64f65a64321dfcb17139501c549057c1c120a886e781d7ff + MediaType: application/vnd.oci.image.manifest.v1+json + Platform: linux/amd64 + + Name: asisti.registry.twcstorage.ru/mtusi2026lab2@sha256:c30bf44ec751d0d32f4827b52182288d11f6db43e035e18039e6984ca42df6cf + MediaType: application/vnd.oci.image.manifest.v1+json + Platform: unknown/unknown + Annotations: + vnd.docker.reference.digest: sha256:db441136cf48247e64f65a64321dfcb17139501c549057c1c120a886e781d7ff + vnd.docker.reference.type: attestation-manifest diff --git a/evidence/timeweb-persistence.txt b/evidence/timeweb-persistence.txt new file mode 100644 index 00000000..de07c0b2 --- /dev/null +++ b/evidence/timeweb-persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:18082" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/timeweb-pods.json b/evidence/timeweb-pods.json new file mode 100644 index 00000000..6c69b893 --- /dev/null +++ b/evidence/timeweb-pods.json @@ -0,0 +1,72 @@ +[ + { + "name": "api-7d8c9d6f-j5svn", + "uid": "62c2ffab-5098-48a1-9942-cbd960734e36", + "node": "dev.asisti.tech", + "containers": [ + { + "name": "api", + "ready": true, + "image": "sha256:700efb49a49e5a5084696a22eb7a15b1695ef693d61c8d5d6c2b397d3d3802b2", + "imageID": "asisti.registry.twcstorage.ru/mtusi2026lab2@sha256:3f19c9feb306a88044cc46b25d99592d48f04c21eba477d59676486277b2956c", + "restartCount": 0 + } + ] + }, + { + "name": "postgres-0", + "uid": "1f6ebfb6-7a2a-43b7-a61b-c887f5b2e235", + "node": "dev.asisti.tech", + "containers": [ + { + "name": "postgres", + "ready": true, + "image": "docker.io/library/postgres:17.6-alpine", + "imageID": "docker.io/library/postgres@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94", + "restartCount": 0 + } + ] + }, + { + "name": "valkey-0", + "uid": "d0d2a5ac-4fad-47e9-ab50-5169d09ecec5", + "node": "dev.asisti.tech", + "containers": [ + { + "name": "valkey", + "ready": true, + "image": "docker.io/valkey/valkey:8.1.3-alpine", + "imageID": "docker.io/valkey/valkey@sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "restartCount": 0 + } + ] + }, + { + "name": "valkey-1", + "uid": "fbd7523d-2088-4c52-b455-72b92910ef06", + "node": "marlosrv0", + "containers": [ + { + "name": "valkey", + "ready": true, + "image": "docker.io/valkey/valkey:8.1.3-alpine", + "imageID": "docker.io/valkey/valkey@sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "restartCount": 0 + } + ] + }, + { + "name": "valkey-2", + "uid": "a6681afc-3adb-4f40-8842-d32b5a7a583b", + "node": "srv0.agapov.space", + "containers": [ + { + "name": "valkey", + "ready": true, + "image": "docker.io/valkey/valkey:8.1.3-alpine", + "imageID": "docker.io/valkey/valkey@sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "restartCount": 0 + } + ] + } +] diff --git a/evidence/timeweb-pvc-after.txt b/evidence/timeweb-pvc-after.txt new file mode 100644 index 00000000..14cc910b --- /dev/null +++ b/evidence/timeweb-pvc-after.txt @@ -0,0 +1,5 @@ +NAME UID VOLUME +data-postgres-0 b592cc47-82be-4635-afa4-d65e3246e82a pvc-b592cc47-82be-4635-afa4-d65e3246e82a +data-valkey-0 fafeeae5-f6f6-487d-ba50-15d50f9678c7 pvc-fafeeae5-f6f6-487d-ba50-15d50f9678c7 +data-valkey-1 a39c3e41-fae2-4096-b83f-807aada803e9 pvc-a39c3e41-fae2-4096-b83f-807aada803e9 +data-valkey-2 ad5c9d15-ae01-409e-ad11-7f7f7b42e7fe pvc-ad5c9d15-ae01-409e-ad11-7f7f7b42e7fe diff --git a/evidence/timeweb-pvc-before.txt b/evidence/timeweb-pvc-before.txt new file mode 100644 index 00000000..14cc910b --- /dev/null +++ b/evidence/timeweb-pvc-before.txt @@ -0,0 +1,5 @@ +NAME UID VOLUME +data-postgres-0 b592cc47-82be-4635-afa4-d65e3246e82a pvc-b592cc47-82be-4635-afa4-d65e3246e82a +data-valkey-0 fafeeae5-f6f6-487d-ba50-15d50f9678c7 pvc-fafeeae5-f6f6-487d-ba50-15d50f9678c7 +data-valkey-1 a39c3e41-fae2-4096-b83f-807aada803e9 pvc-a39c3e41-fae2-4096-b83f-807aada803e9 +data-valkey-2 ad5c9d15-ae01-409e-ad11-7f7f7b42e7fe pvc-ad5c9d15-ae01-409e-ad11-7f7f7b42e7fe diff --git a/evidence/timeweb-reinstall.txt b/evidence/timeweb-reinstall.txt new file mode 100644 index 00000000..085b6f10 --- /dev/null +++ b/evidence/timeweb-reinstall.txt @@ -0,0 +1,8 @@ +release "lab2" uninstalled +NAME: lab2 +LAST DEPLOYED: Fri Oct 16 10:38:22 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +TEST SUITE: None diff --git a/evidence/timeweb-release.txt b/evidence/timeweb-release.txt new file mode 100644 index 00000000..fe7403f7 --- /dev/null +++ b/evidence/timeweb-release.txt @@ -0,0 +1,40 @@ +NAME: lab2 +LAST DEPLOYED: Fri Oct 16 10:38:22 2026 +NAMESPACE: highload-applications +STATUS: deployed +REVISION: 1 +DESCRIPTION: Install complete +RESOURCES: +==> v1/NetworkPolicy +NAME POD-SELECTOR AGE +private-databases app in (postgres,valkey) 3m51s + +==> v1/ConfigMap +NAME DATA AGE +messenger-config 9 3m51s + +==> v1/Service +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +api ClusterIP 10.152.183.248 8080/TCP 3m51s +postgres ClusterIP 10.152.183.190 5432/TCP 3m51s +valkey ClusterIP None 6379/TCP 3m52s + +==> v1/Deployment +NAME READY UP-TO-DATE AVAILABLE AGE +api 1/1 1 1 3m52s + +==> v1/Pod(related) +NAME READY STATUS RESTARTS AGE +api-7d8c9d6f-j5svn 1/1 Running 0 54s +postgres-0 1/1 Running 0 84s +valkey-0 1/1 Running 0 58s +valkey-1 1/1 Running 0 71s +valkey-2 1/1 Running 0 83s + +==> v1/StatefulSet +NAME READY AGE +postgres 1/1 3m52s +valkey 3/3 3m52s + + +TEST SUITE: None diff --git a/evidence/timeweb-smoke.txt b/evidence/timeweb-smoke.txt new file mode 100644 index 00000000..96b49787 --- /dev/null +++ b/evidence/timeweb-smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:18082" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..339ab019 --- /dev/null +++ b/go.mod @@ -0,0 +1,36 @@ +module gitea.privcloud.tech/vlad_marlo/mtusi2026lab2 + +go 1.26.1 + +require ( + github.com/gofiber/fiber/v2 v2.52.12 + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.9.1 + github.com/redis/go-redis/v9 v9.17.2 + github.com/valyala/fasthttp v1.51.0 + go.lab260.ru/fielderr v0.0.0-20260609150058-2f9540b99e41 + go.uber.org/fx v1.24.0 + go.uber.org/zap v1.27.1 + golang.org/x/crypto v0.49.0 +) + +require ( + github.com/andybalholm/brotli v1.1.0 // indirect + github.com/cespare/xxhash/v2 v2.3.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/klauspost/compress v1.17.9 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/rivo/uniseg v0.2.0 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/tcplisten v1.0.0 // indirect + go.uber.org/dig v1.19.0 // indirect + go.uber.org/multierr v1.10.0 // indirect + golang.org/x/sync v0.20.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/text v0.35.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..3bca56bd --- /dev/null +++ b/go.sum @@ -0,0 +1,77 @@ +github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= +github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= +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.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.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/gofiber/fiber/v2 v2.52.12 h1:0LdToKclcPOj8PktUdIKo9BUohjjwfnQl42Dhw8/WUw= +github.com/gofiber/fiber/v2 v2.52.12/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw= +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.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc= +github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +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/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= +github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +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.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI= +github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +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/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA= +github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g= +github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= +github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= +go.lab260.ru/fielderr v0.0.0-20260609150058-2f9540b99e41 h1:kHFUC/1OnQ05ShJW1wjCAbrSa/XxylAgEnZ75BholE4= +go.lab260.ru/fielderr v0.0.0-20260609150058-2f9540b99e41/go.mod h1:OQKs2tIkkTxUjzewIMsqChKuHPWDjIgUz+SYqdhR9rM= +go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4= +go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE= +go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg= +go.uber.org/fx v1.24.0/go.mod h1:AmDeGyS+ZARGKM4tlH4FY2Jr63VjbEDJHtqXTGP5hbo= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +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/internal/admission/distributed.go b/internal/admission/distributed.go new file mode 100644 index 00000000..c268f976 --- /dev/null +++ b/internal/admission/distributed.go @@ -0,0 +1,18 @@ +package admission + +import ( + "context" + "errors" +) + +// ErrRate means the request exhausted a shared rate budget. +var ErrRate = errors.New("shared request rate exceeded") + +// ErrSlots means the request exhausted a shared concurrency budget. +var ErrSlots = errors.New("shared execution slots exhausted") + +// Distributed defines request admission independently of the backing database. +type Distributed interface { + // Enter reserves global/group or user/group budgets and returns a release operation. + Enter(ctx context.Context, group, user string) (func(), error) +} diff --git a/internal/admission/limiter.go b/internal/admission/limiter.go new file mode 100644 index 00000000..97e7f2ac --- /dev/null +++ b/internal/admission/limiter.go @@ -0,0 +1,73 @@ +// Package admission bounds request rate and concurrent execution independently of transport. +package admission + +import ( + "fmt" + "sync" + "time" +) + +// Options defines the rate and execution bounds for one limiter. +type Options struct { + // MaxInFlight limits concurrent executions without an admission queue. + MaxInFlight int + // RequestsPerSecond is the token refill rate. + RequestsPerSecond int + // Burst is the maximum number of immediately available tokens. + Burst int +} + +// Limiter owns synchronization for the token bucket and execution slots. +// It knows neither HTTP response codes nor application shutdown state. +type Limiter struct { + mu sync.Mutex + rate float64 + burst float64 + tokens float64 + lastRefill time.Time + slots chan struct{} +} + +// New validates limits and creates a full token bucket with bounded execution slots. +func New(cfg Options) (*Limiter, error) { + if cfg.MaxInFlight <= 0 || cfg.RequestsPerSecond <= 0 || cfg.Burst <= 0 { + return nil, fmt.Errorf("admission limits must be positive") + } + return &Limiter{ + rate: float64(cfg.RequestsPerSecond), + burst: float64(cfg.Burst), + tokens: float64(cfg.Burst), + lastRefill: time.Now(), + slots: make(chan struct{}, cfg.MaxInFlight), + }, nil +} + +// Allow refills the token bucket and consumes a token when one is available. +func (limiter *Limiter) Allow(now time.Time) bool { + limiter.mu.Lock() + defer limiter.mu.Unlock() + elapsed := max(0, now.Sub(limiter.lastRefill).Seconds()) + limiter.tokens = min(limiter.burst, limiter.tokens+elapsed*limiter.rate) + limiter.lastRefill = now + if limiter.tokens < 1 { + return false + } + limiter.tokens-- + return true +} + +// Acquire reserves an execution slot without waiting. +func (limiter *Limiter) Acquire() bool { + select { + case limiter.slots <- struct{}{}: + return true + default: + return false + } +} + +// Release returns an execution slot previously reserved by Acquire. +// Each successful Acquire must be paired with exactly one Release. +func (limiter *Limiter) Release() { + <-limiter.slots +} diff --git a/internal/admission/limiter_test.go b/internal/admission/limiter_test.go new file mode 100644 index 00000000..9fcb7e47 --- /dev/null +++ b/internal/admission/limiter_test.go @@ -0,0 +1,148 @@ +package admission + +import ( + "testing" + "testing/synctest" + "time" +) + +// TestLimiter_Allow checks token exhaustion and refill with deterministic time. +func TestLimiter_Allow(t *testing.T) { + cases := []struct { + name string + elapsed time.Duration + want bool + }{ + {"Negative: exhausted bucket", 0, false}, + {"Negative: partial token", time.Millisecond * 500, false}, + {"Positive: refilled token", time.Second, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + // Arrange. + limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1}) + if !limiter.Allow(time.Now()) { + t.Fatal("fixture token missing") + } + time.Sleep(tc.elapsed) + + // Act. + got := limiter.Allow(time.Now()) + + // Assert. + if got != tc.want { + t.Fatalf("Allow after %s=%v, want=%v", tc.elapsed, got, tc.want) + } + }) + }) + } +} + +// TestLimiter_Acquire checks available, occupied and released execution slots independently. +func TestLimiter_Acquire(t *testing.T) { + t.Run("Positive: free slot", func(t *testing.T) { + // Arrange. + limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1}) + + want := true + + // Act. + got := limiter.Acquire() + if got { + t.Cleanup(limiter.Release) + } + + // Assert. + if got != want { + t.Fatalf("Acquire=%v, want=%v", got, want) + } + }) + + t.Run("Negative: occupied slot", func(t *testing.T) { + // Arrange. + limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1}) + + if !limiter.Acquire() { + t.Fatal("fixture slot unavailable") + } + + t.Cleanup(limiter.Release) + + want := false + + // Act. + got := limiter.Acquire() + if got { + t.Cleanup(limiter.Release) + } + + // Assert. + if got != want { + t.Fatalf("Acquire=%v, want=%v", got, want) + } + }) + + t.Run("Positive: released slot", func(t *testing.T) { + // Arrange. + limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1}) + + if !limiter.Acquire() { + t.Fatal("fixture slot unavailable") + } + + limiter.Release() + + want := true + + // Act. + got := limiter.Acquire() + if got { + t.Cleanup(limiter.Release) + } + + // Assert. + if got != want { + t.Fatalf("Acquire=%v, want=%v", got, want) + } + }) +} + +// newTestLimiter creates a limiter or fails the test on invalid settings. +func newTestLimiter(t *testing.T, options Options) *Limiter { + t.Helper() + limiter, err := New(options) + if err != nil { + t.Fatal(err) + } + return limiter +} + +// TestLimiter_New rejects each nonpositive limit independently. +func TestLimiter_New(t *testing.T) { + cases := []struct { + name string + options Options + }{ + {"Negative: zero concurrency", Options{MaxInFlight: 0, RequestsPerSecond: 1, Burst: 1}}, + {"Negative: negative concurrency", Options{MaxInFlight: -1, RequestsPerSecond: 1, Burst: 1}}, + {"Negative: zero refill rate", Options{MaxInFlight: 1, RequestsPerSecond: 0, Burst: 1}}, + {"Negative: negative refill rate", Options{MaxInFlight: 1, RequestsPerSecond: -1, Burst: 1}}, + {"Negative: zero burst", Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 0}}, + {"Negative: negative burst", Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: -1}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + options := tc.options + + // Act. + limiter, err := New(options) + + // Assert. + if err == nil || limiter != nil { + t.Fatalf("invalid options accepted: %v, %v", limiter, err) + } + }) + } +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 00000000..339faacc --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,53 @@ +// Package config loads and validates the environment configuration of the application. +package config + +import "fmt" + +// Config groups settings by the component that consumes them. +type Config struct { + // HTTP configures the listener, request limits and shutdown deadline. + HTTP *Controller + // Memory configures the capacity of the process-local store. + Memory *Memory + // Logger configures structured process logging. + Logger *Logger +} + +// Default returns independent configuration sections with the documented defaults. +func Default() *Config { + return &Config{ + HTTP: defaultController(), + Memory: defaultMemory(), + Logger: &Logger{Level: "info"}, + } +} + +// New loads environment overrides and rejects invalid settings before startup. +func New() (*Config, error) { + cfg := Default() + if err := cfg.HTTP.loadEnvironment(); err != nil { + return nil, err + } + if err := cfg.Memory.loadEnvironment(); err != nil { + return nil, err + } + cfg.Logger.loadEnvironment() + if err := cfg.Validate(); err != nil { + return nil, err + } + return cfg, nil +} + +// Validate verifies the presence and invariants of each configuration section. +func (cfg *Config) Validate() error { + if cfg == nil || cfg.HTTP == nil || cfg.Memory == nil || cfg.Logger == nil { + return fmt.Errorf("HTTP, Memory and Logger configuration sections are required") + } + if err := cfg.HTTP.Validate(); err != nil { + return err + } + if err := cfg.Memory.Validate(); err != nil { + return err + } + return cfg.Logger.Validate() +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 00000000..83969917 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,241 @@ +package config + +import "testing" + +// TestConfig_New checks individual environment overrides and invalid settings. +func TestConfig_New(t *testing.T) { + t.Run("Positive: APP_PORT override", func(t *testing.T) { + // Arrange. + t.Setenv("APP_PORT", "18080") + + // Act. + cfg, err := New() + + // Assert. + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.Port != 18080 { + t.Fatalf("APP_PORT=%v, want=%v", cfg.HTTP.Port, 18080) + } + }) + t.Run("Positive: REQUEST_TIMEOUT_SECONDS override", func(t *testing.T) { + // Arrange. + t.Setenv("REQUEST_TIMEOUT_SECONDS", "4") + + // Act. + cfg, err := New() + + // Assert. + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.TimeoutSeconds != 4 { + t.Fatalf("REQUEST_TIMEOUT_SECONDS=%v, want=%v", cfg.HTTP.TimeoutSeconds, 4) + } + }) + t.Run("Positive: MAX_MESSAGES override", func(t *testing.T) { + // Arrange. + t.Setenv("MAX_MESSAGES", "25") + + // Act. + cfg, err := New() + + // Assert. + if err != nil { + t.Fatal(err) + } + if cfg.Memory.MaxMessages != 25 { + t.Fatalf("MAX_MESSAGES=%v, want=%v", cfg.Memory.MaxMessages, 25) + } + }) + t.Run("Positive: REQUESTS_PER_SECOND override", func(t *testing.T) { + // Arrange. + t.Setenv("REQUESTS_PER_SECOND", "12") + + // Act. + cfg, err := New() + + // Assert. + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.Admission.RequestsPerSecond != 12 { + t.Fatalf("REQUESTS_PER_SECOND=%v, want=%v", cfg.HTTP.Admission.RequestsPerSecond, 12) + } + }) + t.Run("Positive: LOG_LEVEL override", func(t *testing.T) { + // Arrange. + t.Setenv("LOG_LEVEL", "debug") + + // Act. + cfg, err := New() + + // Assert. + if err != nil { + t.Fatal(err) + } + if cfg.Logger.Level != "debug" { + t.Fatalf("LOG_LEVEL=%v, want=%v", cfg.Logger.Level, "debug") + } + }) + cases := []struct { + name string + key string + value string + }{ + {"port exceeds TCP range", "APP_PORT", "65536"}, + {"zero message capacity", "MAX_MESSAGES", "0"}, + {"nonnumeric body limit", "MAX_BODY_BYTES", "bad"}, + {"shutdown deadline exceeds bound", "SHUTDOWN_TIMEOUT_SECONDS", "10"}, + {"hostname instead of bind IP", "APP_HOST", "hostname"}, + } + for _, tc := range cases { + t.Run("Negative: "+tc.name, func(t *testing.T) { + // Arrange. + t.Setenv(tc.key, tc.value) + + // Act. + cfg, err := New() + + // Assert. + if err == nil || cfg != nil { + t.Fatalf("invalid %s=%q returned config=%+v, error=%v", tc.key, tc.value, cfg, err) + } + }) + } +} + +// TestConfig_Validate rejects one missing section or invalid component per scenario. +func TestConfig_Validate(t *testing.T) { + t.Run("Negative: nil config", func(t *testing.T) { + // Arrange. + var cfg *Config + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatalf("accepted %s", "nil config") + } + }) + + t.Run("Negative: missing HTTP", func(t *testing.T) { + // Arrange. + cfg := Default() + + cfg.HTTP = nil + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatalf("accepted %s", "missing HTTP") + } + }) + + t.Run("Negative: missing Memory", func(t *testing.T) { + // Arrange. + cfg := Default() + + cfg.Memory = nil + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatalf("accepted %s", "missing Memory") + } + }) + + t.Run("Negative: missing Logger", func(t *testing.T) { + // Arrange. + cfg := Default() + + cfg.Logger = nil + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatalf("accepted %s", "missing Logger") + } + }) + + t.Run("Negative: unknown log level", func(t *testing.T) { + // Arrange. + cfg := Default() + + cfg.Logger.Level = "unknown" + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatalf("accepted %s", "unknown log level") + } + }) + + t.Run("Negative: zero storage capacity", func(t *testing.T) { + // Arrange. + cfg := Default() + + cfg.Memory.MaxUsers = 0 + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatalf("accepted %s", "zero storage capacity") + } + }) + + t.Run("Negative: zero concurrency", func(t *testing.T) { + // Arrange. + cfg := Default() + + cfg.HTTP.Admission.MaxInFlight = 0 + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatalf("accepted %s", "zero concurrency") + } + }) +} + +// TestLogger_Validate rejects an absent logging section without panicking. +func TestLogger_Validate(t *testing.T) { + // Arrange. + var cfg *Logger + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatal("nil logger accepted") + } +} + +// TestMemory_Validate rejects absent storage settings without panicking. +func TestMemory_Validate(t *testing.T) { + // Arrange. + var cfg *Memory + + // Act. + err := cfg.Validate() + + // Assert. + if err == nil { + t.Fatal("nil memory configuration accepted") + } +} diff --git a/internal/config/controller.go b/internal/config/controller.go new file mode 100644 index 00000000..5fe1f9ca --- /dev/null +++ b/internal/config/controller.go @@ -0,0 +1,157 @@ +package config + +import ( + "fmt" + "net" + "os" + "strconv" + "time" +) + +const ( + maxTCPPort = 65535 + maxShutdownTimeoutSeconds = 9 + maxRequestTimeoutSeconds = 15 +) + +// Controller contains settings owned exclusively by the HTTP transport. +type Controller struct { + // Host is the IP address on which the listener binds. + Host string + // Port is the TCP port, in the range 1..65535. + Port int + // TimeoutSeconds limits request reads, response writes and idle connections. + TimeoutSeconds int + // ShutdownTimeoutSeconds bounds draining of active requests; it must not exceed nine seconds. + ShutdownTimeoutSeconds int + // MaxBodyBytes is the maximum accepted request body size before decoding. + MaxBodyBytes int + // MaxConnections bounds simultaneous connections handled by fasthttp. + MaxConnections int + // Admission controls business request throughput and execution concurrency. + Admission Admission +} + +// Admission defines shared request policies; health endpoints bypass them. +type Admission struct { + // MaxInFlight is the maximum number of executing requests, with no waiting queue. + MaxInFlight int + // RequestsPerSecond is the token refill rate for the global admission bucket. + RequestsPerSecond int + // Burst is the bucket capacity and maximum immediate request burst. + Burst int + // AuthRate limits public registration/login attempts per second. + AuthRate int + // AuthSlots bounds concurrent password KDF work globally. + AuthSlots int + // UserRate limits each authenticated account across all groups. + UserRate int + // UserSlots bounds concurrency across one account's groups. + UserSlots int + // UserWriteRate limits one account's write attempts per second. + UserWriteRate int + // UserWriteSlots bounds one account's concurrent writes. + UserWriteSlots int + // UserAuthRate limits session-management operations per account. + UserAuthRate int + // UserAuthSlots bounds one account's session-management concurrency. + UserAuthSlots int +} + +// defaultController returns the default listener, timeout and admission settings. +func defaultController() *Controller { + return &Controller{ + Host: "0.0.0.0", + Port: 8080, + TimeoutSeconds: 3, + ShutdownTimeoutSeconds: 5, + MaxBodyBytes: 64 << 10, + MaxConnections: 256, + Admission: Admission{ + MaxInFlight: 32, + RequestsPerSecond: 1000, + Burst: 100, + AuthRate: 100, + AuthSlots: 4, + UserRate: 100, + UserSlots: 8, + UserWriteRate: 50, + UserWriteSlots: 4, + UserAuthRate: 20, + UserAuthSlots: 2, + }, + } +} + +// loadEnvironment applies environment overrides to this configuration section. +func (cfg *Controller) loadEnvironment() error { + if host, exists := os.LookupEnv("APP_HOST"); exists { + cfg.Host = host + } + return loadIntegers( + integerSetting{"APP_PORT", &cfg.Port}, + integerSetting{"REQUEST_TIMEOUT_SECONDS", &cfg.TimeoutSeconds}, + integerSetting{"SHUTDOWN_TIMEOUT_SECONDS", &cfg.ShutdownTimeoutSeconds}, + integerSetting{"MAX_BODY_BYTES", &cfg.MaxBodyBytes}, + integerSetting{"MAX_CONNECTIONS", &cfg.MaxConnections}, + integerSetting{"MAX_IN_FLIGHT", &cfg.Admission.MaxInFlight}, + integerSetting{"REQUESTS_PER_SECOND", &cfg.Admission.RequestsPerSecond}, + integerSetting{"REQUEST_BURST", &cfg.Admission.Burst}, + integerSetting{"AUTH_RATE", &cfg.Admission.AuthRate}, + integerSetting{"AUTH_SLOTS", &cfg.Admission.AuthSlots}, + integerSetting{"USER_RATE", &cfg.Admission.UserRate}, + integerSetting{"USER_SLOTS", &cfg.Admission.UserSlots}, + integerSetting{"USER_WRITE_RATE", &cfg.Admission.UserWriteRate}, + integerSetting{"USER_WRITE_SLOTS", &cfg.Admission.UserWriteSlots}, + integerSetting{"USER_AUTH_RATE", &cfg.Admission.UserAuthRate}, + integerSetting{"USER_AUTH_SLOTS", &cfg.Admission.UserAuthSlots}, + ) +} + +// Validate checks listener addresses, timeouts and admission bounds. +func (cfg *Controller) Validate() error { + if cfg == nil { + return fmt.Errorf("HTTP configuration is required") + } + if cfg.TimeoutSeconds > maxRequestTimeoutSeconds { + return fmt.Errorf("REQUEST_TIMEOUT_SECONDS must not exceed %d", maxRequestTimeoutSeconds) + } + if net.ParseIP(cfg.Host) == nil { + return fmt.Errorf("APP_HOST must be an IP address") + } + if cfg.Port < 1 || cfg.Port > maxTCPPort { + return fmt.Errorf("APP_PORT must be 1..%d", maxTCPPort) + } + if cfg.ShutdownTimeoutSeconds < 1 || cfg.ShutdownTimeoutSeconds > maxShutdownTimeoutSeconds { + return fmt.Errorf("SHUTDOWN_TIMEOUT_SECONDS must be 1..%d", maxShutdownTimeoutSeconds) + } + settings := []integerSetting{ + {"REQUEST_TIMEOUT_SECONDS", &cfg.TimeoutSeconds}, + {"MAX_BODY_BYTES", &cfg.MaxBodyBytes}, + {"MAX_CONNECTIONS", &cfg.MaxConnections}, + {"MAX_IN_FLIGHT", &cfg.Admission.MaxInFlight}, + {"REQUESTS_PER_SECOND", &cfg.Admission.RequestsPerSecond}, + {"REQUEST_BURST", &cfg.Admission.Burst}, + } + for _, setting := range settings { + if err := validatePositive(setting.name, *setting.target); err != nil { + return err + } + } + return nil +} + +// Bind returns the listener address, including brackets for IPv6 hosts. +func (cfg *Controller) Bind() string { + return net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)) +} + +// Timeout returns the configured read, write and idle timeout. +func (cfg *Controller) Timeout() time.Duration { + return time.Duration(cfg.TimeoutSeconds) * time.Second +} + +// ShutdownTimeout returns the maximum time allowed to drain active requests. +func (cfg *Controller) ShutdownTimeout() time.Duration { + return time.Duration(cfg.ShutdownTimeoutSeconds) * time.Second +} diff --git a/internal/config/environment.go b/internal/config/environment.go new file mode 100644 index 00000000..db5dfd83 --- /dev/null +++ b/internal/config/environment.go @@ -0,0 +1,41 @@ +package config + +import ( + "fmt" + "os" + "strconv" +) + +const maxConfiguredInteger = 1 << 30 + +type integerSetting struct { + name string + target *int +} + +// loadIntegers parses configured integer overrides and reports invalid values. +func loadIntegers(settings ...integerSetting) error { + for _, setting := range settings { + raw, exists := os.LookupEnv(setting.name) + if !exists { + continue + } + value, err := strconv.Atoi(raw) + if err != nil { + return fmt.Errorf("%s must be an integer", setting.name) + } + if err := validatePositive(setting.name, value); err != nil { + return err + } + *setting.target = value + } + return nil +} + +// validatePositive checks that a setting is positive and within the supported range. +func validatePositive(name string, value int) error { + if value < 1 || value > maxConfiguredInteger { + return fmt.Errorf("%s must be between 1 and %d", name, maxConfiguredInteger) + } + return nil +} diff --git a/internal/config/logger.go b/internal/config/logger.go new file mode 100644 index 00000000..58f2450b --- /dev/null +++ b/internal/config/logger.go @@ -0,0 +1,32 @@ +package config + +import ( + "fmt" + "os" +) + +// Logger configures the minimum severity written as structured JSON to stderr. +type Logger struct { + // Level is one of debug, info, warn or error; the default is info. + Level string +} + +// loadEnvironment applies environment overrides to this configuration section. +func (cfg *Logger) loadEnvironment() { + if level, exists := os.LookupEnv("LOG_LEVEL"); exists { + cfg.Level = level + } +} + +// Validate rejects unsupported levels rather than silently changing verbosity. +func (cfg *Logger) Validate() error { + if cfg == nil { + return fmt.Errorf("Logger configuration is required") + } + switch cfg.Level { + case "debug", "info", "warn", "error": + return nil + default: + return fmt.Errorf("LOG_LEVEL must be debug, info, warn or error") + } +} diff --git a/internal/config/memory.go b/internal/config/memory.go new file mode 100644 index 00000000..401e67d1 --- /dev/null +++ b/internal/config/memory.go @@ -0,0 +1,54 @@ +package config + +import "fmt" + +// Memory defines logical capacity limits; MaxStateBytes is not a measurement of RSS. +type Memory struct { + // MaxUsers limits the number of registered users. + MaxUsers int + // MaxChats limits the number of immutable chats. + MaxChats int + // MaxMessages limits the total number of messages across all chats. + MaxMessages int + // MaxStateBytes limits the logical storage budget, including estimated record overhead. + MaxStateBytes int +} + +// defaultMemory returns the default storage capacity limits. +func defaultMemory() *Memory { + return &Memory{ + MaxUsers: 10000, + MaxChats: 10000, + MaxMessages: 100000, + MaxStateBytes: 32 << 20, + } +} + +// loadEnvironment applies environment overrides to this configuration section. +func (cfg *Memory) loadEnvironment() error { + return loadIntegers( + integerSetting{"MAX_USERS", &cfg.MaxUsers}, + integerSetting{"MAX_CHATS", &cfg.MaxChats}, + integerSetting{"MAX_MESSAGES", &cfg.MaxMessages}, + integerSetting{"MAX_STATE_BYTES", &cfg.MaxStateBytes}, + ) +} + +// Validate rejects disabled, negative and excessively large storage limits. +func (cfg *Memory) Validate() error { + if cfg == nil { + return fmt.Errorf("Memory configuration is required") + } + settings := []integerSetting{ + {"MAX_USERS", &cfg.MaxUsers}, + {"MAX_CHATS", &cfg.MaxChats}, + {"MAX_MESSAGES", &cfg.MaxMessages}, + {"MAX_STATE_BYTES", &cfg.MaxStateBytes}, + } + for _, setting := range settings { + if err := validatePositive(setting.name, *setting.target); err != nil { + return err + } + } + return nil +} diff --git a/internal/config/persistence.go b/internal/config/persistence.go new file mode 100644 index 00000000..97142002 --- /dev/null +++ b/internal/config/persistence.go @@ -0,0 +1,52 @@ +package config + +import ( + "fmt" + "os" + "strings" +) + +// Persistence contains database, cache and session settings. +type Persistence struct { + // DatabaseURL identifies the PostgreSQL database. + DatabaseURL string + // Shards maps stable identities to Valkey addresses. + Shards map[string]string + // Coordinator names the stable global admission shard. + Coordinator string + // PoolSize bounds connections per dependency. + PoolSize int + // TimeoutMilliseconds bounds each dependency operation. + TimeoutMilliseconds int + // SessionTTLSeconds sets the absolute session lifetime. + SessionTTLSeconds int +} + +// NewPersistence loads dependency settings separately from HTTP configuration. +func NewPersistence() (*Persistence, error) { + cfg := &Persistence{ + DatabaseURL: os.Getenv("DATABASE_URL"), + Coordinator: os.Getenv("VALKEY_COORDINATOR"), + Shards: make(map[string]string), + PoolSize: 8, + TimeoutMilliseconds: 1000, + SessionTTLSeconds: 3600, + } + if cfg.Coordinator == "" { + cfg.Coordinator = "shard0" + } + for _, entry := range strings.Split(os.Getenv("VALKEY_SHARDS"), ",") { + id, address, ok := strings.Cut(entry, "=") + if !ok || id == "" || address == "" || cfg.Shards[id] != "" { + return nil, fmt.Errorf("VALKEY_SHARDS requires unique id=address entries") + } + cfg.Shards[id] = address + } + if cfg.DatabaseURL == "" || cfg.Shards[cfg.Coordinator] == "" { + return nil, fmt.Errorf("DATABASE_URL and a configured VALKEY_COORDINATOR are required") + } + if err := loadIntegers(integerSetting{"DEPENDENCY_POOL_SIZE", &cfg.PoolSize}, integerSetting{"DEPENDENCY_TIMEOUT_MS", &cfg.TimeoutMilliseconds}, integerSetting{"SESSION_TTL_SECONDS", &cfg.SessionTTLSeconds}); err != nil { + return nil, err + } + return cfg, nil +} diff --git a/internal/config/persistence_test.go b/internal/config/persistence_test.go new file mode 100644 index 00000000..6f9b63f4 --- /dev/null +++ b/internal/config/persistence_test.go @@ -0,0 +1,34 @@ +package config + +import "testing" + +// TestPersistenceConfiguration validates independent environment configurations. +func TestPersistenceConfiguration(t *testing.T) { + cases := []struct { + name string + database string + shards string + coordinator string + ttl string + valid bool + }{ + {"defaults", "postgres://localhost/test", "shard0=localhost:6379", "", "3600", true}, + {"missing database", "", "shard0=localhost:6379", "", "3600", false}, + {"missing coordinator", "postgres://localhost/test", "shard1=localhost:6379", "shard0", "3600", false}, + {"duplicate shard", "postgres://localhost/test", "shard0=a,shard0=b", "", "3600", false}, + {"invalid topology", "postgres://localhost/test", "wrong", "", "3600", false}, + {"invalid ttl", "postgres://localhost/test", "shard0=a", "", "no", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("DATABASE_URL", tc.database) + t.Setenv("VALKEY_SHARDS", tc.shards) + t.Setenv("VALKEY_COORDINATOR", tc.coordinator) + t.Setenv("SESSION_TTL_SECONDS", tc.ttl) + _, err := NewPersistence() + if (err == nil) != tc.valid { + t.Fatalf("unexpected validation result: %v", err) + } + }) + } +} diff --git a/internal/controller/fx.go b/internal/controller/fx.go new file mode 100644 index 00000000..e99b2264 --- /dev/null +++ b/internal/controller/fx.go @@ -0,0 +1,8 @@ +package controller + +import "go.uber.org/fx" + +// RunControllerFx lets Fx own startup, signal handling and graceful shutdown. +func RunControllerFx(lc fx.Lifecycle, ctrl Controller) { + lc.Append(fx.Hook{OnStart: ctrl.Start, OnStop: ctrl.Stop}) +} diff --git a/internal/controller/http/fiber/auth.go b/internal/controller/http/fiber/auth.go new file mode 100644 index 00000000..10c9e0ca --- /dev/null +++ b/internal/controller/http/fiber/auth.go @@ -0,0 +1,76 @@ +package fiber + +import ( + "encoding/base64" + "net/http" + "strings" + + "github.com/gofiber/fiber/v2" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +const identityKey = "authenticated-user" + +// HandleLogin structurally decodes Basic credentials and delegates authentication. +func (ctrl *Controller) HandleLogin(ctx *fiber.Ctx) error { + scheme, encoded, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ") + if !ok || !strings.EqualFold(scheme, "Basic") { + return service.ErrUnauthorized + } + decoded, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return service.ErrUnauthorized + } + username, password, ok := strings.Cut(string(decoded), ":") + if !ok { + return service.ErrUnauthorized + } + if len(ctx.Body()) != 0 { + return service.ErrInvalid + } + session, err := ctrl.auth.Login(ctx.UserContext(), username, password) + if err != nil { + return err + } + return ctx.Status(http.StatusCreated).JSON(fiber.Map{ + "token": session.Token, + "token_type": "Bearer", + "expires_at": session.ExpiresAt, + "user": userResponse(session.User), + }) +} + +// HandleLogout revokes the current authenticated token before returning no content. +func (ctrl *Controller) HandleLogout(ctx *fiber.Ctx) error { + if err := ctrl.auth.Logout(ctx.UserContext(), bearer(ctx)); err != nil { + return err + } + return ctx.SendStatus(http.StatusNoContent) +} + +// bearer extracts a Bearer token without interpreting its identity or validity. +func bearer(ctx *fiber.Ctx) string { + scheme, token, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ") + if !ok || !strings.EqualFold(scheme, "Bearer") { + return "" + } + return token +} + +// identity reads only the identity produced by successful session authentication. +func identity(ctx *fiber.Ctx) string { + value, _ := ctx.Locals(identityKey).(string) + return value +} + +// requestGroup selects a bounded policy group from the HTTP operation. +func requestGroup(ctx *fiber.Ctx) string { + if ctx.Path() == "/api/v1/users" || strings.HasPrefix(ctx.Path(), "/api/v1/auth/") { + return "auth" + } + if ctx.Method() == http.MethodGet { + return "read" + } + return "write" +} diff --git a/internal/controller/http/fiber/auth_test.go b/internal/controller/http/fiber/auth_test.go new file mode 100644 index 00000000..8d30d0a1 --- /dev/null +++ b/internal/controller/http/fiber/auth_test.go @@ -0,0 +1,161 @@ +package fiber + +import ( + "context" + "encoding/base64" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +type sessionFixture struct { + fixtureAuthentication + login func(string, string) (dto.SessionDTO, error) + logoutError error +} + +// Login delegates the credentials decoded by the controller to the arranged scenario. +func (f sessionFixture) Login(_ context.Context, username, password string) (dto.SessionDTO, error) { + return f.login(username, password) +} + +// Logout returns the prescribed revocation outcome. +func (f sessionFixture) Logout(context.Context, string) error { + return f.logoutError +} + +// TestLoginHTTPChecksBasicEncoding verifies independent wire-level login scenarios. +func TestLoginHTTPChecksBasicEncoding(t *testing.T) { + cases := []struct { + name string + header string + body string + status int + }{ + {"missing header", "", "", http.StatusUnauthorized}, + {"wrong scheme", "Bearer abc", "", http.StatusUnauthorized}, + {"bad base64", "Basic %%%", "", http.StatusUnauthorized}, + {"no delimiter", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice")), "", http.StatusUnauthorized}, + {"unexpected body", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "{}", http.StatusBadRequest}, + {"valid colon in password", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "", http.StatusCreated}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctrl := testController(t, nil) + ctrl.auth = sessionFixture{login: func(username, password string) (dto.SessionDTO, error) { + if username != "alice" || password != "long-password:ok" { + t.Fatal("credentials altered") + } + return dto.SessionDTO{Token: "opaque", ExpiresAt: time.Now().UTC().Add(time.Hour), User: dto.UserDTO{ID: uuid.New(), Username: "alice"}}, nil + }} + req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader(tc.body)) + req.Header.Set("Authorization", tc.header) + response, err := ctrl.server.Test(req) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = response.Body.Close() + }() + if response.StatusCode != tc.status { + t.Fatalf("got %d want %d", response.StatusCode, tc.status) + } + if tc.status == http.StatusUnauthorized && response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` { + t.Fatal("missing Basic challenge") + } + }) + } +} + +// TestLoginInvalidCredentialsUsesBasicChallenge checks the service rejection mapping. +func TestLoginInvalidCredentialsUsesBasicChallenge(t *testing.T) { + ctrl := testController(t, nil) + ctrl.auth = sessionFixture{login: func(string, string) (dto.SessionDTO, error) { + return dto.SessionDTO{}, service.ErrUnauthorized + }} + req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil) + req.SetBasicAuth("alice", "invalid-password") + response, err := ctrl.server.Test(req) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = response.Body.Close() + }() + if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` { + t.Fatal("incorrect login rejection") + } +} + +// TestLogoutHTTPReturnsNoContent checks the authenticated revocation response. +func TestLogoutHTTPReturnsNoContent(t *testing.T) { + ctrl := testController(t, nil) + actor := user(t, ctrl) + req := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil) + req.Header.Set("Authorization", "Bearer "+actor) + response, err := ctrl.server.Test(req) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = response.Body.Close() + }() + body, err := io.ReadAll(response.Body) + if err != nil || response.StatusCode != http.StatusNoContent || len(body) != 0 { + t.Fatalf("invalid logout response: %v", err) + } +} + +// TestLogoutHTTPPreservesFailure ensures an unsuccessful revoke does not claim success. +func TestLogoutHTTPPreservesFailure(t *testing.T) { + ctrl := testController(t, nil) + actor := user(t, ctrl) + ctrl.auth = sessionFixture{fixtureAuthentication: fixtureAuthentication{ctrl.service}, logoutError: context.DeadlineExceeded} + status, _, err := request(ctrl, http.MethodDelete, "/api/v1/auth/sessions/current", actor, nil) + if err != nil || status != http.StatusInternalServerError { + t.Fatalf("revocation failure hidden: %d %v", status, err) + } +} + +// TestLegacyIdentityDoesNotAuthenticate verifies the lab1 header cannot grant access. +func TestLegacyIdentityDoesNotAuthenticate(t *testing.T) { + ctrl := testController(t, nil) + actor := user(t, ctrl) + req := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil) + req.Header.Set("X-User-Id", actor) + response, err := ctrl.server.Test(req) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = response.Body.Close() + }() + if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Bearer realm="messenger"` { + t.Fatal("legacy identity granted access or missing challenge") + } +} + +type unavailableReadiness struct{} + +// Ping simulates an unavailable mandatory dependency for readiness mapping. +func (unavailableReadiness) Ping(context.Context) error { + return context.DeadlineExceeded +} + +// TestReadinessRejectsDependencyFailure verifies readiness reflects mandatory infrastructure. +func TestReadinessRejectsDependencyFailure(t *testing.T) { + ctrl := testController(t, nil) + ctrl.readiness = unavailableReadiness{} + status, _, err := request(ctrl, http.MethodGet, "/health/ready", "", nil) + if err != nil || status != http.StatusServiceUnavailable { + t.Fatalf("incorrect readiness: %d %v", status, err) + } +} diff --git a/internal/controller/http/fiber/chats_test.go b/internal/controller/http/fiber/chats_test.go new file mode 100644 index 00000000..d1660ba1 --- /dev/null +++ b/internal/controller/http/fiber/chats_test.go @@ -0,0 +1,312 @@ +package fiber + +import ( + "net/http" + "net/url" + "reflect" + "testing" + + "github.com/google/uuid" +) + +// TestController_ChatsCreate checks membership and request validation in isolated chats. +func TestController_ChatsCreate(t *testing.T) { + t.Run("Positive: caller included", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor}}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusCreated, body) + if body["title"] != "Team" || !reflect.DeepEqual(body["member_ids"], []any{actor}) { + t.Fatalf("chat fields changed: %v", body) + } + }) + + t.Run("Negative: empty members", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{}}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: duplicate members", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, actor}}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: caller omitted", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + outsider := user(t, ctrl) + payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{outsider}}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: unknown member", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, uuid.NewString()}}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: malformed member ID", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, "invalid"}}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: blank title", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + payload := mustJSON(t, map[string]any{"title": " ", "member_ids": []string{actor}}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: malformed JSON", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + payload := []byte(`{`) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) +} + +// TestController_ChatsGetByID checks access and the returned chat identity. +func TestController_ChatsGetByID(t *testing.T) { + t.Run("Positive: member reads chat", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor, target := owner, id + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusOK, body) + if body["id"] != id || body["title"] != "Чат" { + t.Fatalf("wrong chat: %v", body) + } + }) + + t.Run("Negative: outsider", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor, target := user(t, ctrl), id + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusNotFound, body) + assertErrorCode(t, body, "not_found") + }) + + t.Run("Negative: unknown chat", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + actor, target := owner, uuid.NewString() + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusNotFound, body) + assertErrorCode(t, body, "not_found") + }) + + t.Run("Negative: malformed chat ID", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + actor, target := owner, "invalid" + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: authentication precedes ID parsing", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor, target := "", "invalid" + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusUnauthorized, body) + assertErrorCode(t, body, "unauthorized") + }) +} + +// TestController_ChatsGetPage checks that foreign memberships remain absent from lists. +func TestController_ChatsGetPage(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + chat(t, ctrl, owner) + outsider := user(t, ctrl) + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats", outsider, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusOK, body) + if len(body["items"].([]any)) != 0 || body["next_cursor"] != nil { + t.Fatalf("foreign chat leaked: %v", body) + } +} + +// TestController_ChatPagination recovers every chat exactly once across page boundaries. +func TestController_ChatPagination(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + expected := make(map[string]bool) + for range 15 { + expected[chat(t, ctrl, actor)] = true + } + + // Act. + items := history(t, ctrl, actor, "/api/v1/chats") + + // Assert. + if len(items) != len(expected) { + t.Fatalf("got %d chats, want %d", len(items), len(expected)) + } + for _, item := range items { + id := item.(map[string]any)["id"].(string) + if !expected[id] { + t.Fatalf("duplicate or unexpected chat %s", id) + } + delete(expected, id) + } +} + +// TestController_ChatCursorScope rejects a continuation issued for another user's list. +func TestController_ChatCursorScope(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + outsider := user(t, ctrl) + chat(t, ctrl, owner) + chat(t, ctrl, owner) + page := call(t, ctrl, http.MethodGet, "/api/v1/chats?limit=1", owner, nil, http.StatusOK) + token := page["next_cursor"].(string) + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats?cursor="+url.QueryEscape(token), outsider, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") +} diff --git a/internal/controller/http/fiber/configure.go b/internal/controller/http/fiber/configure.go new file mode 100644 index 00000000..1f3da39a --- /dev/null +++ b/internal/controller/http/fiber/configure.go @@ -0,0 +1,37 @@ +package fiber + +import ( + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/recover" +) + +// configure initializes the HTTP server, middleware and routes. +func (ctrl *Controller) configure() { + ctrl.createServer() + ctrl.initMiddlewares() + ctrl.initRoutes() +} + +// createServer creates Fiber with the configured transport limits and error handler. +func (ctrl *Controller) createServer() { + timeout := ctrl.cfg.Timeout() + ctrl.server = fiber.New(fiber.Config{ + AppName: "messenger-lab1", + DisableStartupMessage: true, + Immutable: true, + CaseSensitive: true, + StrictRouting: true, + BodyLimit: ctrl.cfg.MaxBodyBytes, + Concurrency: ctrl.cfg.MaxConnections, + ReadTimeout: timeout, + WriteTimeout: timeout, + IdleTimeout: timeout, + ErrorHandler: ctrl.handleErr, + }) +} + +// initMiddlewares registers request logging and panic recovery middleware. +func (ctrl *Controller) initMiddlewares() { + ctrl.server.Use(ctrl.request) + ctrl.server.Use(recover.New()) +} diff --git a/internal/controller/http/fiber/controller.go b/internal/controller/http/fiber/controller.go new file mode 100644 index 00000000..bf07f4ad --- /dev/null +++ b/internal/controller/http/fiber/controller.go @@ -0,0 +1,57 @@ +// Package fiber implements the messenger HTTP transport using Fiber. +package fiber + +import ( + "fmt" + "sync/atomic" + + "github.com/gofiber/fiber/v2" + "go.lab260.ru/fielderr" + "go.uber.org/zap" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/controller" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// Controller owns the HTTP server and delegates business operations to Service. +// Its configuration is copied at construction and must not change during serving. +// Fx manages its listener through Start and Stop. +type Controller struct { + log *zap.Logger + cfg config.Controller + service service.Service + server *fiber.App + errorRegistry *fielderr.Registry + admission admission.Distributed + auth service.Authentication + readiness Readiness + stopping atomic.Bool + serveDone chan error +} + +var _ controller.Controller = (*Controller)(nil) + +// New validates dependencies and prepares the server without opening a listener. +// Routing, middleware and Fiber configuration are installed by configure. +func New(log *zap.Logger, cfg *config.Controller, svc service.Service, registry *fielderr.Registry, limiter admission.Distributed, auth service.Authentication, readiness Readiness) (*Controller, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + if log == nil || svc == nil || registry == nil || limiter == nil || auth == nil || readiness == nil { + return nil, fmt.Errorf("HTTP logger, service, error registry and admission limiter are required") + } + ctrl := &Controller{ + log: log.Named("controller.http.fiber"), + cfg: *cfg, + service: svc, + errorRegistry: registry, + admission: limiter, + auth: auth, + readiness: readiness, + serveDone: make(chan error, 1), + } + ctrl.configure() + return ctrl, nil +} diff --git a/internal/controller/http/fiber/controller_test.go b/internal/controller/http/fiber/controller_test.go new file mode 100644 index 00000000..bb625822 --- /dev/null +++ b/internal/controller/http/fiber/controller_test.go @@ -0,0 +1,319 @@ +package fiber + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "sync" + "testing" + + "github.com/google/uuid" + "go.uber.org/zap" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service/production" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store/memory" +) + +// testController creates an integration fixture with the real controller, service and store. +func testController(t *testing.T, change func(*config.Config)) *Controller { + t.Helper() + cfg := config.Default() + cfg.HTTP.Admission.RequestsPerSecond = 100000 + cfg.HTTP.Admission.Burst = 100000 + if change != nil { + change(cfg) + } + repo, err := memory.New(cfg.Memory) + if err != nil { + t.Fatal(err) + } + codec, err := cursor.New() + if err != nil { + t.Fatal(err) + } + svc, err := production.New(repo, codec) + if err != nil { + t.Fatal(err) + } + registry, err := NewErrorRegistry() + if err != nil { + t.Fatal(err) + } + limiter, err := admission.New(admission.Options{ + MaxInFlight: cfg.HTTP.Admission.MaxInFlight, + RequestsPerSecond: cfg.HTTP.Admission.RequestsPerSecond, + Burst: cfg.HTTP.Admission.Burst, + }) + if err != nil { + t.Fatal(err) + } + ctrl, err := New(zap.NewNop(), cfg.HTTP, svc, registry, &fixtureAdmission{limiter}, fixtureAuthentication{svc}, fixtureReadiness{}) + if err != nil { + t.Fatal(err) + } + return ctrl +} + +// request sends a raw test request and decodes its response. +func request(ctrl *Controller, method, path, actor string, body []byte) (int, map[string]any, error) { + req := httptest.NewRequest(method, path, bytes.NewReader(body)) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if actor != "" { + req.Header.Set("Authorization", "Bearer "+actor) + } + resp, err := ctrl.server.Test(req, 10000) + if err != nil { + return 0, nil, err + } + defer func() { + _ = resp.Body.Close() + }() + b, err := io.ReadAll(resp.Body) + if err != nil { + return 0, nil, err + } + var data map[string]any + if err = json.Unmarshal(b, &data); err != nil { + return resp.StatusCode, nil, fmt.Errorf("invalid JSON response: %w", err) + } + if resp.Header.Get("X-Request-Id") == "" { + return resp.StatusCode, data, fmt.Errorf("missing request ID") + } + if resp.StatusCode >= http.StatusBadRequest { + envelope, ok := data["error"].(map[string]any) + if !ok || envelope["request_id"] != resp.Header.Get("X-Request-Id") { + return resp.StatusCode, data, fmt.Errorf("invalid error envelope") + } + } + return resp.StatusCode, data, nil +} + +// call sends a JSON test request and checks its expected HTTP status. +func call(t *testing.T, ctrl *Controller, method, path, actor string, body any, want int) map[string]any { + t.Helper() + var b []byte + var err error + if raw, ok := body.([]byte); ok { + b = raw + } else if body != nil { + b, err = json.Marshal(body) + if err != nil { + t.Fatal(err) + } + } + status, data, err := request(ctrl, method, path, actor, b) + if err != nil { + t.Fatal(err) + } + if status != want { + t.Fatalf("%s %s: got %d want %d: %v", method, path, status, want, data) + } + return data +} + +// user creates a test user and returns its identifier. +func user(t *testing.T, c *Controller) string { + t.Helper() + r := call(t, c, http.MethodPost, "/api/v1/users", "", map[string]any{"username": "u_" + uuid.New().String()[:8], "display_name": "Алиса 👋", "password": "fixture-password-123"}, http.StatusCreated) + return r["id"].(string) +} + +// chat creates a test chat containing the supplied user. +func chat(t *testing.T, c *Controller, u string) string { + t.Helper() + r := call(t, c, http.MethodPost, "/api/v1/chats", u, map[string]any{"title": "Чат", "member_ids": []string{u}}, http.StatusCreated) + return r["id"].(string) +} + +// TestDuplicateUsernameRace checks username uniqueness under concurrent requests. +func TestDuplicateUsernameRace(t *testing.T) { + // Arrange. + c := testController(t, nil) + results := make(chan int, 10) + failures := make(chan error, 10) + var wg sync.WaitGroup + // Act. + for range 10 { + wg.Go(func() { + status, _, err := request(c, http.MethodPost, "/api/v1/users", "", []byte(`{"username":"same","display_name":"User","password":"fixture-password-123"}`)) + if err != nil { + failures <- err + } + results <- status + }) + } + wg.Wait() + close(results) + close(failures) + // Assert. + for err := range failures { + t.Error(err) + } + created, conflicts := 0, 0 + for s := range results { + switch s { + case http.StatusCreated: + created++ + case http.StatusConflict: + conflicts++ + default: + t.Errorf("unexpected %d", s) + } + } + if created != 1 || conflicts != 9 { + t.Fatalf("created=%d conflicts=%d", created, conflicts) + } +} + +// history collects all test messages by following pagination cursors. +func history(t *testing.T, c *Controller, u, path string) []any { + t.Helper() + var items []any + next := path + "?limit=7" + for range 100 { + r := call(t, c, http.MethodGet, next, u, nil, http.StatusOK) + items = append(items, r["items"].([]any)...) + if r["next_cursor"] == nil { + return items + } + next = path + "?limit=7&cursor=" + url.QueryEscape(r["next_cursor"].(string)) + } + t.Fatal("pagination never finished") + return nil +} + +// TestConcurrent100Messages10Clients recovers the exact acknowledged records after concurrent writes. +func TestConcurrent100Messages10Clients(t *testing.T) { + // Arrange. + const clients = 10 + const messagesPerClient = 10 + const total = clients * messagesPerClient + ctrl := testController(t, nil) + actor := user(t, ctrl) + chatID := chat(t, ctrl, actor) + path := "/api/v1/chats/" + chatID + "/messages" + acknowledgements := make(chan map[string]any, total) + failures := make(chan error, total) + var writers sync.WaitGroup + + // Act. + for client := range clients { + writers.Go(func() { + for index := range messagesPerClient { + text := fmt.Sprintf("client %d message %d", client, index) + payload, err := json.Marshal(map[string]string{"text": text}) + if err != nil { + failures <- err + continue + } + status, body, err := request(ctrl, http.MethodPost, path, actor, payload) + if err != nil { + failures <- err + continue + } + if status != http.StatusCreated || body["text"] != text || body["sender_id"] != actor || body["chat_id"] != chatID { + failures <- fmt.Errorf("incorrect acknowledgement: status=%d, body=%v", status, body) + continue + } + acknowledgements <- body + } + }) + } + writers.Wait() + close(failures) + close(acknowledgements) + + // Assert. + for err := range failures { + t.Error(err) + } + if t.Failed() { + t.FailNow() + } + expected := make(map[string]map[string]any, total) + for message := range acknowledgements { + id, ok := message["id"].(string) + if !ok || id == "" { + t.Fatalf("invalid message ID: %v", message) + } + if _, duplicate := expected[id]; duplicate { + t.Fatalf("duplicate acknowledgement ID %s", id) + } + expected[id] = message + } + if len(expected) != total { + t.Fatalf("acknowledged=%d, want=%d", len(expected), total) + } + items := history(t, ctrl, actor, path) + if len(items) != total { + t.Fatalf("recovered=%d, want=%d", len(items), total) + } + for _, item := range items { + message := item.(map[string]any) + id := message["id"].(string) + if !reflect.DeepEqual(message, expected[id]) { + t.Fatalf("stored record differs from acknowledgement: got=%v, want=%v", message, expected[id]) + } + delete(expected, id) + } +} + +// TestUnsupportedMediaType checks rejection of unsupported request content types. +func TestUnsupportedMediaType(t *testing.T) { + // Arrange. + c := testController(t, nil) + req := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{}`)) + req.Header.Set("Content-Type", "text/plain") + // Act. + r, e := c.server.Test(req) + + // Assert. + if e != nil { + t.Fatal(e) + } + defer func() { + _ = r.Body.Close() + }() + if r.StatusCode != http.StatusUnsupportedMediaType { + t.Fatalf("status %d", r.StatusCode) + } +} + +// TestConfigIndependentState prevents one application instance from accepting another's identity. +func TestConfigIndependentState(t *testing.T) { + // Arrange. + first := testController(t, nil) + actor := user(t, first) + second := testController(t, nil) + + // Act. + status, body, err := request(second, http.MethodGet, "/api/v1/users/me", actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusUnauthorized, body) + assertErrorCode(t, body, "unauthorized") +} + +// mustJSON encodes fixture payloads and reports preparation failures at the caller. +func mustJSON(t *testing.T, value any) []byte { + t.Helper() + payload, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return payload +} diff --git a/internal/controller/http/fiber/decode.go b/internal/controller/http/fiber/decode.go new file mode 100644 index 00000000..7ba482ae --- /dev/null +++ b/internal/controller/http/fiber/decode.go @@ -0,0 +1,22 @@ +package fiber + +import ( + "mime" + + "github.com/gofiber/fiber/v2" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/strictjson" +) + +// decode checks HTTP media type and maps strict JSON decoding errors to API input errors. +func decode(ctx *fiber.Ctx, target any, requiredFields ...string) error { + mediaType, _, err := mime.ParseMediaType(ctx.Get(fiber.HeaderContentType)) + if err != nil || mediaType != fiber.MIMEApplicationJSON { + return errMedia + } + if err := strictjson.DecodeObject(ctx.Body(), target, requiredFields...); err != nil { + return service.ErrInvalid + } + return nil +} diff --git a/internal/controller/http/fiber/dependencies.go b/internal/controller/http/fiber/dependencies.go new file mode 100644 index 00000000..58a3a74d --- /dev/null +++ b/internal/controller/http/fiber/dependencies.go @@ -0,0 +1,9 @@ +package fiber + +import "context" + +// Readiness checks the dependencies required by the synchronous request path. +type Readiness interface { + // Ping reports whether requests can be safely served. + Ping(context.Context) error +} diff --git a/internal/controller/http/fiber/error_codes.go b/internal/controller/http/fiber/error_codes.go new file mode 100644 index 00000000..64decfa0 --- /dev/null +++ b/internal/controller/http/fiber/error_codes.go @@ -0,0 +1,22 @@ +package fiber + +const ( + // codeInvalid identifies malformed or invalid request input. + codeInvalid = "invalid_request" + // codeUnauthorized identifies an unresolved user identity. + codeUnauthorized = "unauthorized" + // codeNotFound deliberately covers both absent and inaccessible resources. + codeNotFound = "not_found" + // codeConflict identifies a violated uniqueness constraint. + codeConflict = "conflict" + // codeUnavailable identifies temporary admission or persistent capacity exhaustion. + codeUnavailable = "unavailable" + // codeRateLimited identifies exhaustion of the request token bucket. + codeRateLimited = "rate_limited" + // codeTooLarge identifies a request exceeding the transport byte budget. + codeTooLarge = "payload_too_large" + // codeMedia identifies an unsupported request media type. + codeMedia = "unsupported_media_type" + // codeInternal identifies a hidden unexpected failure. + codeInternal = "internal_error" +) diff --git a/internal/controller/http/fiber/error_registry.go b/internal/controller/http/fiber/error_registry.go new file mode 100644 index 00000000..d5e10075 --- /dev/null +++ b/internal/controller/http/fiber/error_registry.go @@ -0,0 +1,33 @@ +package fiber + +import ( + "net/http" + + "go.lab260.ru/fielderr" +) + +// NewErrorRegistry returns an immutable mapping of application statuses to HTTP codes. +// The registry is injected rather than installed in process-global state, allowing +// independent application instances in integration tests. +func NewErrorRegistry() (*fielderr.Registry, error) { + return fielderr.NewRegistry( + statusDefinition(codeInvalid, http.StatusBadRequest), + statusDefinition(codeUnauthorized, http.StatusUnauthorized), + statusDefinition(codeNotFound, http.StatusNotFound), + statusDefinition(codeConflict, http.StatusConflict), + statusDefinition(codeTooLarge, http.StatusRequestEntityTooLarge), + statusDefinition(codeMedia, http.StatusUnsupportedMediaType), + statusDefinition(codeRateLimited, http.StatusTooManyRequests), + statusDefinition(codeUnavailable, http.StatusServiceUnavailable), + statusDefinition(codeInternal, http.StatusInternalServerError), + ) +} + +// statusDefinition associates an application error code with its HTTP status. +func statusDefinition(name string, httpStatus int) fielderr.StatusDefinition { + return fielderr.StatusDefinition{ + Code: fielderr.NewStatusCode(name), + Name: name, + HTTPStatus: httpStatus, + } +} diff --git a/internal/controller/http/fiber/errors.go b/internal/controller/http/fiber/errors.go new file mode 100644 index 00000000..954c7550 --- /dev/null +++ b/internal/controller/http/fiber/errors.go @@ -0,0 +1,71 @@ +package fiber + +import ( + "errors" + "net/http" + + "github.com/gofiber/fiber/v2" + "github.com/google/uuid" + "go.lab260.ru/fielderr" + "go.uber.org/zap" + + httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/http" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// handleErr normalizes a failure and writes the public error envelope. +func (ctrl *Controller) handleErr(ctx *fiber.Ctx, err error) error { + requestID := ctx.GetRespHeader(headerRequestID) + if requestID == "" { + requestID = uuid.NewString() + ctx.Set(headerRequestID, requestID) + } + err = publicError(normalizeTransportError(err)) + status, ok := fielderr.HTTPStatusFrom(ctrl.errorRegistry, err) + if !ok { + err = errInternal + status = http.StatusInternalServerError + } + if status == http.StatusUnauthorized { + challenge := `Bearer realm="messenger"` + if ctx.Path() == "/api/v1/auth/sessions" && ctx.Method() == http.MethodPost { + challenge = `Basic realm="messenger", charset="UTF-8"` + } + ctx.Set(fiber.HeaderWWWAuthenticate, challenge) + } + if status == http.StatusInternalServerError { + ctrl.log.Error("unexpected request failure", zap.String("request_id", requestID)) + } + return ctx.Status(status).JSON(errorResponse(err, requestID)) +} + +// normalizeTransportError maps Fiber failures to transport-independent application errors. +func normalizeTransportError(err error) error { + transportError, ok := errors.AsType[*fiber.Error](err) + if !ok { + return err + } + switch transportError.Code { + case http.StatusRequestEntityTooLarge: + return errTooLarge + case http.StatusNotFound, http.StatusMethodNotAllowed: + return service.ErrNotFound + case http.StatusBadRequest, http.StatusRequestTimeout, http.StatusRequestHeaderFieldsTooLarge: + return service.ErrInvalid + default: + return errInternal + } +} + +// errorResponse builds the public error envelope with its request identifier. +func errorResponse(err error, requestID string) httpmodel.ErrorResponse { + status, _ := fielderr.Status(err) + message, _ := fielderr.PublicMessage(err) + return httpmodel.ErrorResponse{ + Error: httpmodel.ErrorDetail{ + Code: status.String(), + Message: message, + RequestID: requestID, + }, + } +} diff --git a/internal/controller/http/fiber/errors_test.go b/internal/controller/http/fiber/errors_test.go new file mode 100644 index 00000000..126a1185 --- /dev/null +++ b/internal/controller/http/fiber/errors_test.go @@ -0,0 +1,107 @@ +package fiber + +import ( + "encoding/json" + "errors" + "net/http" + "testing" + + "github.com/gofiber/fiber/v2" + "github.com/valyala/fasthttp" + "go.lab260.ru/fielderr" + + httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/http" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// TestTransportErrorMapping checks safe API errors for framework-generated failures. +func TestTransportErrorMapping(t *testing.T) { + t.Run("large body", func(t *testing.T) { + if normalizeTransportError(fiber.ErrRequestEntityTooLarge) != errTooLarge { + t.Fatal("incorrect body-limit error") + } + }) + t.Run("method not allowed", func(t *testing.T) { + if normalizeTransportError(fiber.ErrMethodNotAllowed) != service.ErrNotFound { + t.Fatal("unexpected method error") + } + }) + t.Run("invalid request", func(t *testing.T) { + if normalizeTransportError(fiber.ErrBadRequest) != service.ErrInvalid { + t.Fatal("unexpected input error") + } + }) + t.Run("unexpected framework failure", func(t *testing.T) { + if normalizeTransportError(fiber.ErrInternalServerError) != errInternal { + t.Fatal("unexpected failure escaped normalization") + } + }) +} + +// TestController_handleErr writes a safe, correlated fallback response. +func TestController_handleErr(t *testing.T) { + t.Run("Negative: unknown internal error", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + raw := &fasthttp.RequestCtx{} + ctx := ctrl.server.AcquireCtx(raw) + defer ctrl.server.ReleaseCtx(ctx) + + // Act. + err := ctrl.handleErr(ctx, errors.New("private storage secret")) + + // Assert. + if err != nil { + t.Fatal(err) + } + if raw.Response.StatusCode() != http.StatusInternalServerError { + t.Fatalf("status=%d", raw.Response.StatusCode()) + } + var body httpmodel.ErrorResponse + if err := json.Unmarshal(raw.Response.Body(), &body); err != nil { + t.Fatal(err) + } + requestID := string(raw.Response.Header.Peek(headerRequestID)) + if requestID == "" || body.Error.RequestID != requestID { + t.Fatalf("uncorrelated error: %+v, header=%q", body, requestID) + } + if body.Error.Code != "internal_error" || body.Error.Message != "internal server error" { + t.Fatalf("unsafe fallback: %+v", body) + } + }) + + t.Run("Negative: missing status mapping", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + registry, err := fielderr.NewRegistry() + if err != nil { + t.Fatal(err) + } + ctrl.errorRegistry = registry + raw := &fasthttp.RequestCtx{} + ctx := ctrl.server.AcquireCtx(raw) + defer ctrl.server.ReleaseCtx(ctx) + + // Act. + err = ctrl.handleErr(ctx, service.ErrInvalid) + + // Assert. + if err != nil { + t.Fatal(err) + } + if raw.Response.StatusCode() != http.StatusInternalServerError { + t.Fatalf("status=%d", raw.Response.StatusCode()) + } + var body httpmodel.ErrorResponse + if err := json.Unmarshal(raw.Response.Body(), &body); err != nil { + t.Fatal(err) + } + requestID := string(raw.Response.Header.Peek(headerRequestID)) + if requestID == "" || body.Error.RequestID != requestID { + t.Fatalf("uncorrelated error: %+v, header=%q", body, requestID) + } + if body.Error.Code != "internal_error" || body.Error.Message != "internal server error" { + t.Fatalf("unsafe fallback: %+v", body) + } + }) +} diff --git a/internal/controller/http/fiber/fixtures_auth_test.go b/internal/controller/http/fiber/fixtures_auth_test.go new file mode 100644 index 00000000..deecc6ab --- /dev/null +++ b/internal/controller/http/fiber/fixtures_auth_test.go @@ -0,0 +1,61 @@ +package fiber + +import ( + "context" + "time" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// fixtureAuthentication isolates HTTP decoding and business authorization from session persistence. +type fixtureAuthentication struct { + service service.Service +} + +// Register delegates profile validation to the real business service. +func (f fixtureAuthentication) Register(ctx context.Context, request dto.UsersCreateRequestDTO, _ string) (dto.UserDTO, error) { + return f.service.UsersCreate(ctx, request) +} + +// Authenticate uses fixture tokens equal to user IDs exclusively in controller tests. +func (f fixtureAuthentication) Authenticate(ctx context.Context, token string) (string, error) { + return token, f.service.UsersCheckIdentity(ctx, token) +} + +// Login is deliberately unsupported by this fixture; real login has separate integration coverage. +func (f fixtureAuthentication) Login(context.Context, string, string) (dto.SessionDTO, error) { + return dto.SessionDTO{}, service.ErrUnauthorized +} + +// Logout accepts the fixture session without persistent side effects. +func (f fixtureAuthentication) Logout(context.Context, string) error { + return nil +} + +type fixtureReadiness struct{} + +// Ping marks isolated controller fixtures ready without external resources. +func (fixtureReadiness) Ping(context.Context) error { + return nil +} + +type fixtureAdmission struct { + *admission.Limiter +} + +// Enter adapts the deterministic local policy fixture to the distributed boundary. +func (f *fixtureAdmission) Enter(_ context.Context, _, user string) (func(), error) { + if user != "" { + return func() { + }, nil + } + if !f.Allow(time.Now()) { + return nil, admission.ErrRate + } + if !f.Acquire() { + return nil, admission.ErrSlots + } + return f.Release, nil +} diff --git a/internal/controller/http/fiber/handlers.go b/internal/controller/http/fiber/handlers.go new file mode 100644 index 00000000..c1ab1a09 --- /dev/null +++ b/internal/controller/http/fiber/handlers.go @@ -0,0 +1,96 @@ +package fiber + +import ( + "net/http" + + "github.com/gofiber/fiber/v2" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/http" +) + +// HandleUsersCreate decodes registration input and returns the created user. +func (ctrl *Controller) HandleUsersCreate(ctx *fiber.Ctx) error { + var request httpmodel.UsersCreateRequest + if err := decode(ctx, &request, "username", "display_name", "password"); err != nil { + return err + } + user, err := ctrl.auth.Register(ctx.UserContext(), dto.UsersCreateRequestDTO{ + Username: request.Username, + DisplayName: request.DisplayName, + }, request.Password) + if err != nil { + return err + } + return ctx.Status(http.StatusCreated).JSON(userResponse(user)) +} + +// HandleUsersGetMe returns the account selected by the validated session. +func (ctrl *Controller) HandleUsersGetMe(ctx *fiber.Ctx) error { + user, err := ctrl.service.UsersGetMe(ctx.UserContext(), identity(ctx)) + if err != nil { + return err + } + return ctx.Status(http.StatusOK).JSON(userResponse(user)) +} + +// HandleChatsCreate decodes the chat payload and returns the new chat. +func (ctrl *Controller) HandleChatsCreate(ctx *fiber.Ctx) error { + var request httpmodel.ChatsCreateRequest + if err := decode(ctx, &request, "title", "member_ids"); err != nil { + return err + } + chat, err := ctrl.service.ChatsCreate(ctx.UserContext(), dto.ChatsCreateRequestDTO{ + UserID: identity(ctx), + Title: request.Title, + MemberIDs: request.MemberIDs, + }) + if err != nil { + return err + } + return ctx.Status(http.StatusCreated).JSON(chatResponse(chat)) +} + +// HandleChatsGetByID delegates chat authorization and maps the accessible chat. +func (ctrl *Controller) HandleChatsGetByID(ctx *fiber.Ctx) error { + chat, err := ctrl.service.ChatsGetByID(ctx.UserContext(), identity(ctx), ctx.Params("chat_id")) + if err != nil { + return err + } + return ctx.Status(http.StatusOK).JSON(chatResponse(chat)) +} + +// HandleChatsGetPage returns the service's page of visible chats. +func (ctrl *Controller) HandleChatsGetPage(ctx *fiber.Ctx) error { + page, err := ctrl.service.ChatsGetPage(ctx.UserContext(), pageRequest(ctx)) + if err != nil { + return err + } + return ctx.Status(http.StatusOK).JSON(chatPageResponse(page)) +} + +// HandleMessagesCreate decodes text; the service derives and authorizes the sender. +func (ctrl *Controller) HandleMessagesCreate(ctx *fiber.Ctx) error { + var request httpmodel.MessagesCreateRequest + if err := decode(ctx, &request, "text"); err != nil { + return err + } + message, err := ctrl.service.MessagesCreate(ctx.UserContext(), dto.MessagesCreateRequestDTO{ + UserID: identity(ctx), + ChatID: ctx.Params("chat_id"), + Text: request.Text, + }) + if err != nil { + return err + } + return ctx.Status(http.StatusCreated).JSON(messageResponse(message)) +} + +// HandleMessagesGetPage returns the service's ordered history page. +func (ctrl *Controller) HandleMessagesGetPage(ctx *fiber.Ctx) error { + page, err := ctrl.service.MessagesGetPage(ctx.UserContext(), pageRequest(ctx)) + if err != nil { + return err + } + return ctx.Status(http.StatusOK).JSON(messagePageResponse(page)) +} diff --git a/internal/controller/http/fiber/headers.go b/internal/controller/http/fiber/headers.go new file mode 100644 index 00000000..d6991683 --- /dev/null +++ b/internal/controller/http/fiber/headers.go @@ -0,0 +1,7 @@ +package fiber + +const ( + headerUserID = "X-User-Id" + headerRequestID = "X-Request-Id" + retryAfterSeconds = 1 +) diff --git a/internal/controller/http/fiber/health.go b/internal/controller/http/fiber/health.go new file mode 100644 index 00000000..b6ada696 --- /dev/null +++ b/internal/controller/http/fiber/health.go @@ -0,0 +1,28 @@ +package fiber + +import ( + "github.com/gofiber/fiber/v2" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// handleLive reports that the server process is running. +func (ctrl *Controller) handleLive(ctx *fiber.Ctx) error { + return ctx.JSON(fiber.Map{"status": "ok"}) +} + +// handleReady reports readiness unless shutdown has started. +func (ctrl *Controller) handleReady(ctx *fiber.Ctx) error { + if ctrl.stopping.Load() { + return errBusy + } + if err := ctrl.readiness.Ping(ctx.UserContext()); err != nil { + return errBusy + } + return ctrl.handleLive(ctx) +} + +// handleNotFound returns the application error for an unmatched route. +func (ctrl *Controller) handleNotFound(_ *fiber.Ctx) error { + return service.ErrNotFound +} diff --git a/internal/controller/http/fiber/lifecycle.go b/internal/controller/http/fiber/lifecycle.go new file mode 100644 index 00000000..455e213f --- /dev/null +++ b/internal/controller/http/fiber/lifecycle.go @@ -0,0 +1,70 @@ +package fiber + +import ( + "context" + "net" + "sync" + + "go.uber.org/zap" +) + +// Start opens the listener synchronously so Fx observes bind errors immediately. +// It must be called once per Controller; Stop terminates the serving goroutine. +func (ctrl *Controller) Start(ctx context.Context) error { + listener, err := net.Listen("tcp", ctrl.cfg.Bind()) + if err != nil { + return err + } + ready := make(chan struct{}) + go ctrl.serve(&acceptingListener{Listener: listener, ready: ready}) + select { + case <-ready: + ctrl.log.Info("http listener started", zap.String("address", listener.Addr().String())) + return nil + case err := <-ctrl.serveDone: + return err + case <-ctx.Done(): + _ = listener.Close() + return ctx.Err() + } +} + +// acceptingListener signals after fasthttp registers the listener and enters its +// accept loop. An OnListen hook runs earlier and cannot guarantee safe immediate Stop. +type acceptingListener struct { + // Listener is the bound socket owned by the HTTP lifecycle. + net.Listener + ready chan struct{} + once sync.Once +} + +// Accept marks the server as started before waiting for the next connection. +func (listener *acceptingListener) Accept() (net.Conn, error) { + listener.once.Do(func() { + close(listener.ready) + }) + return listener.Listener.Accept() +} + +// serve serves the listener and publishes its terminal result to the lifecycle. +func (ctrl *Controller) serve(listener net.Listener) { + ctrl.serveDone <- ctrl.server.Listener(listener) +} + +// Stop disables admission, closes the listener and drains active requests. +// The configured timeout is bounded by the caller's Fx shutdown context. +func (ctrl *Controller) Stop(ctx context.Context) error { + ctrl.stopping.Store(true) + ctx, cancel := context.WithTimeout(ctx, ctrl.cfg.ShutdownTimeout()) + defer cancel() + if err := ctrl.server.ShutdownWithContext(ctx); err != nil { + return err + } + select { + case err := <-ctrl.serveDone: + ctrl.log.Info("http listener stopped") + return err + case <-ctx.Done(): + return ctx.Err() + } +} diff --git a/internal/controller/http/fiber/lifecycle_test.go b/internal/controller/http/fiber/lifecycle_test.go new file mode 100644 index 00000000..ed9e1b47 --- /dev/null +++ b/internal/controller/http/fiber/lifecycle_test.go @@ -0,0 +1,132 @@ +package fiber + +import ( + "context" + "errors" + "net" + "net/http" + "testing" + "time" + + "github.com/gofiber/fiber/v2" +) + +// TestImmediateShutdown checks the startup/stop race without waiting for a first request. +func TestImmediateShutdown(t *testing.T) { + const repetitions = 10 + const stopDeadline = time.Second + for range repetitions { + // Arrange. + ctrl := testController(t, nil) + // Select an ephemeral test port after validating the normal application config. + ctrl.cfg.Host = "127.0.0.1" + ctrl.cfg.Port = 0 + if err := ctrl.Start(t.Context()); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), stopDeadline) + // Act. + err := ctrl.Stop(ctx) + cancel() + // Assert. + if err != nil { + t.Fatalf("immediate shutdown leaked the listener or serve goroutine: %v", err) + } + } +} + +// TestController_Stop_ActiveRequestDeadline bounds draining while a real handler is still running. +func TestController_Stop_ActiveRequestDeadline(t *testing.T) { + // Arrange. + const deadline = 3 * time.Second + ctrl := testController(t, nil) + ctrl.cfg.Host = "127.0.0.1" + ctrl.cfg.Port = 0 + // Install one controlled handler to test lifecycle independently of business routes. + ctrl.createServer() + entered := make(chan struct{}) + release := make(chan struct{}) + address := make(chan string, 1) + ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error { + address <- net.JoinHostPort(data.Host, data.Port) + return nil + }) + ctrl.server.Get("/blocked", func(ctx *fiber.Ctx) error { + close(entered) + <-release + return ctx.SendStatus(http.StatusOK) + }) + if err := ctrl.Start(t.Context()); err != nil { + t.Fatal(err) + } + client := &http.Client{Timeout: deadline} + completed := make(chan error, 1) + go func() { + response, err := client.Get("http://" + <-address + "/blocked") + if err == nil { + err = response.Body.Close() + } + completed <- err + }() + t.Cleanup(func() { + close(release) + select { + case err := <-completed: + if err != nil { + t.Error(err) + } + case <-time.After(deadline): + t.Error("blocked request did not terminate after release") + } + stopCtx, cancel := context.WithTimeout(context.Background(), deadline) + defer cancel() + if err := ctrl.Stop(stopCtx); err != nil { + t.Error(err) + } + }) + select { + case <-entered: + case <-time.After(deadline): + t.Fatal("request did not reach handler") + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + + // Act. + err := ctrl.Stop(ctx) + + // Assert. + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected canceled drain, got %v", err) + } + if !ctrl.stopping.Load() { + t.Fatal("shutdown did not disable admission") + } +} + +// TestCanceledStartup closes its socket while server initialization is still blocked. +func TestCanceledStartup(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + ctrl.cfg.Host = "127.0.0.1" + ctrl.cfg.Port = 0 + release := make(chan struct{}) + ctrl.server.Hooks().OnListen(func(_ fiber.ListenData) error { + <-release + return nil + }) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + // Act. + err := ctrl.Start(ctx) + close(release) + // Assert. + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected canceled startup, got %v", err) + } + select { + case <-ctrl.serveDone: + case <-time.After(time.Second): + t.Fatal("serving goroutine leaked after canceled startup") + } +} diff --git a/internal/controller/http/fiber/mapping.go b/internal/controller/http/fiber/mapping.go new file mode 100644 index 00000000..04876e62 --- /dev/null +++ b/internal/controller/http/fiber/mapping.go @@ -0,0 +1,77 @@ +package fiber + +import ( + "github.com/gofiber/fiber/v2" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/http" +) + +// userResponse converts a user DTO into its HTTP representation. +func userResponse(user dto.UserDTO) httpmodel.UserResponse { + return httpmodel.UserResponse{ + ID: user.ID.String(), + Username: user.Username, + DisplayName: user.DisplayName, + CreatedAt: user.CreatedAt, + } +} + +// chatResponse converts a chat DTO and its member identifiers into an HTTP response. +func chatResponse(chat dto.ChatDTO) httpmodel.ChatResponse { + members := make([]string, len(chat.MemberIDs)) + for index, id := range chat.MemberIDs { + members[index] = id.String() + } + return httpmodel.ChatResponse{ + ID: chat.ID.String(), + Title: chat.Title, + MemberIDs: members, + CreatedAt: chat.CreatedAt, + } +} + +// messageResponse converts a message DTO into its HTTP representation. +func messageResponse(message dto.MessageDTO) httpmodel.MessageResponse { + return httpmodel.MessageResponse{ + ID: message.ID.String(), + ChatID: message.ChatID.String(), + SenderID: message.SenderID.String(), + Text: message.Text, + CreatedAt: message.CreatedAt, + } +} + +// pageRequest extracts identity, resource and pagination parameters from the request. +func pageRequest(ctx *fiber.Ctx) dto.PageRequestDTO { + return dto.PageRequestDTO{ + UserID: identity(ctx), + ChatID: ctx.Params("chat_id"), + Limit: ctx.Query("limit"), + Cursor: ctx.Query("cursor"), + } +} + +// chatPageResponse converts a page of chat DTOs into an HTTP response. +func chatPageResponse(page dto.ChatPageDTO) httpmodel.ChatPageResponse { + response := httpmodel.ChatPageResponse{ + Items: make([]httpmodel.ChatResponse, len(page.Items)), + NextCursor: page.NextCursor, + } + for index, chat := range page.Items { + response.Items[index] = chatResponse(chat) + } + return response +} + +// messagePageResponse converts a page of message DTOs into an HTTP response. +func messagePageResponse(page dto.MessagePageDTO) httpmodel.MessagePageResponse { + response := httpmodel.MessagePageResponse{ + Items: make([]httpmodel.MessageResponse, len(page.Items)), + NextCursor: page.NextCursor, + } + for index, message := range page.Items { + response.Items[index] = messageResponse(message) + } + return response +} diff --git a/internal/controller/http/fiber/messages_test.go b/internal/controller/http/fiber/messages_test.go new file mode 100644 index 00000000..35aa94e4 --- /dev/null +++ b/internal/controller/http/fiber/messages_test.go @@ -0,0 +1,270 @@ +package fiber + +import ( + "net/http" + "net/url" + "strings" + "testing" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" +) + +// TestController_MessagesCreate checks message validation and identity-derived sender fields. +func TestController_MessagesCreate(t *testing.T) { + t.Run("Positive: Unicode at rune limit", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor := owner + text := strings.Repeat("界", 4000) + payload := mustJSON(t, map[string]string{"text": text}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusCreated, body) + if body["sender_id"] != owner || body["chat_id"] != id || body["text"] != text { + t.Fatalf("message fields changed: %v", body) + } + }) + + t.Run("Negative: empty text", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor := owner + payload := mustJSON(t, map[string]string{"text": ""}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: whitespace text", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor := owner + payload := mustJSON(t, map[string]string{"text": " \n\t"}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: text exceeds rune limit", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor := owner + payload := mustJSON(t, map[string]string{"text": strings.Repeat("界", 4001)}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: sender spoof", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor := owner + outsider := user(t, ctrl) + payload := mustJSON(t, map[string]string{"text": "hello", "sender_id": outsider}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") + }) + + t.Run("Negative: outsider", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor := user(t, ctrl) + payload := mustJSON(t, map[string]string{"text": "hello"}) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusNotFound, body) + assertErrorCode(t, body, "not_found") + }) + + t.Run("Negative: authentication precedes JSON decoding", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + owner := user(t, ctrl) + id := chat(t, ctrl, owner) + actor := "" + payload := []byte(`{`) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusUnauthorized, body) + assertErrorCode(t, body, "unauthorized") + }) +} + +// TestController_MessagesGetPage rejects invalid pagination separately from access failures. +func TestController_MessagesGetPage(t *testing.T) { + cases := []struct { + name string + query string + outsider bool + status int + code string + }{ + {"Negative: zero limit", "limit=0", false, http.StatusBadRequest, "invalid_request"}, + {"Negative: limit above maximum", "limit=101", false, http.StatusBadRequest, "invalid_request"}, + {"Negative: negative limit", "limit=-1", false, http.StatusBadRequest, "invalid_request"}, + {"Negative: nonnumeric limit", "limit=x", false, http.StatusBadRequest, "invalid_request"}, + {"Negative: fractional limit", "limit=1.0", false, http.StatusBadRequest, "invalid_request"}, + {"Negative: malformed cursor", "cursor=invalid", false, http.StatusBadRequest, "invalid_request"}, + {"Negative: outsider", "", true, http.StatusNotFound, "not_found"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + id := chat(t, ctrl, actor) + if tc.outsider { + actor = user(t, ctrl) + } + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+id+"/messages?"+tc.query, actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, tc.status, body) + assertErrorCode(t, body, tc.code) + }) + } +} + +// TestController_MessageCursorScope rejects a continuation from another chat's history. +func TestController_MessageCursorScope(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + first := chat(t, ctrl, actor) + second := chat(t, ctrl, actor) + path := "/api/v1/chats/" + first + "/messages" + for _, text := range []string{"first", "second"} { + call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": text}, http.StatusCreated) + } + page := call(t, ctrl, http.MethodGet, path+"?limit=1", actor, nil, http.StatusOK) + token := page["next_cursor"].(string) + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+second+"/messages?cursor="+url.QueryEscape(token), actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusBadRequest, body) + assertErrorCode(t, body, "invalid_request") +} + +// TestController_MessagePageLimitChange preserves continuation when the client changes page size. +func TestController_MessagePageLimitChange(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + path := "/api/v1/chats/" + chat(t, ctrl, actor) + "/messages" + for _, text := range []string{"first", "second", "third"} { + call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": text}, http.StatusCreated) + } + first := call(t, ctrl, http.MethodGet, path+"?limit=1", actor, nil, http.StatusOK) + token := first["next_cursor"].(string) + + // Act. + status, body, err := request(ctrl, http.MethodGet, path+"?limit=100&cursor="+url.QueryEscape(token), actor, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusOK, body) + items := body["items"].([]any) + if len(items) != 2 || body["next_cursor"] != nil { + t.Fatalf("unexpected final page: %v", body) + } + if items[0].(map[string]any)["text"] != "second" || items[1].(map[string]any)["text"] != "third" { + t.Fatalf("lost order or skipped messages: %v", items) + } +} + +// TestController_MessageCapacity preserves acknowledged data after rejecting an overflow write. +func TestController_MessageCapacity(t *testing.T) { + // Arrange. + ctrl := testController(t, func(cfg *config.Config) { + cfg.Memory.MaxMessages = 2 + }) + actor := user(t, ctrl) + path := "/api/v1/chats/" + chat(t, ctrl, actor) + "/messages" + first := call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": "first"}, http.StatusCreated) + second := call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": "second"}, http.StatusCreated) + + // Act. + status, body, err := request(ctrl, http.MethodPost, path, actor, []byte(`{"text":"rejected"}`)) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusServiceUnavailable, body) + assertErrorCode(t, body, "unavailable") + items := history(t, ctrl, actor, path) + if len(items) != 2 || items[0].(map[string]any)["id"] != first["id"] || items[1].(map[string]any)["id"] != second["id"] { + t.Fatalf("overflow changed acknowledged messages: %v", items) + } +} diff --git a/internal/controller/http/fiber/middleware.go b/internal/controller/http/fiber/middleware.go new file mode 100644 index 00000000..8a48fa44 --- /dev/null +++ b/internal/controller/http/fiber/middleware.go @@ -0,0 +1,81 @@ +package fiber + +import ( + "context" + "errors" + "strconv" + "time" + + "github.com/gofiber/fiber/v2" + "github.com/google/uuid" + "go.uber.org/zap" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission" +) + +// request assigns a request identifier, handles errors and logs the completed request. +func (ctrl *Controller) request(ctx *fiber.Ctx) error { + ctx.Set(headerRequestID, uuid.NewString()) + started := time.Now() + err := ctx.Next() + if err != nil { + err = ctrl.handleErr(ctx, err) + } + ctrl.logRequest(ctx, time.Since(started)) + return err +} + +// logRequest logs request metadata without including message contents. +func (ctrl *Controller) logRequest(ctx *fiber.Ctx, elapsed time.Duration) { + route := "unmatched" + if ctx.Route() != nil { + route = ctx.Route().Path + } + ctrl.log.Info("http request", + zap.String("method", ctx.Method()), + zap.String("route", route), + zap.Int("status", ctx.Response().StatusCode()), + zap.String("request_id", ctx.GetRespHeader(headerRequestID)), + zap.Duration("duration", elapsed), + ) +} + +// admit reserves global budgets and bounds downstream request work. +func (ctrl *Controller) admit(ctx *fiber.Ctx) error { + if ctrl.stopping.Load() { + return errBusy + } + requestCtx, cancel := context.WithTimeout(ctx.UserContext(), ctrl.cfg.Timeout()) + defer cancel() + ctx.SetUserContext(requestCtx) + release, err := ctrl.admission.Enter(requestCtx, requestGroup(ctx), "") + if err != nil { + return admissionError(ctx, err) + } + defer release() + return ctx.Next() +} + +// requireIdentity resolves the session before reserving per-user budgets. +func (ctrl *Controller) requireIdentity(ctx *fiber.Ctx) error { + user, err := ctrl.auth.Authenticate(ctx.UserContext(), bearer(ctx)) + if err != nil { + return err + } + ctx.Locals(identityKey, user) + release, err := ctrl.admission.Enter(ctx.UserContext(), requestGroup(ctx), user) + if err != nil { + return admissionError(ctx, err) + } + defer release() + return ctx.Next() +} + +// admissionError maps policy rejection and backend failure into HTTP-owned errors. +func admissionError(ctx *fiber.Ctx, err error) error { + ctx.Set(fiber.HeaderRetryAfter, strconv.Itoa(retryAfterSeconds)) + if errors.Is(err, admission.ErrRate) { + return errRateLimited + } + return errBusy +} diff --git a/internal/controller/http/fiber/middleware_test.go b/internal/controller/http/fiber/middleware_test.go new file mode 100644 index 00000000..fd9906ed --- /dev/null +++ b/internal/controller/http/fiber/middleware_test.go @@ -0,0 +1,211 @@ +package fiber + +import ( + "net/http" + "testing" + "testing/synctest" + "time" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" +) + +// TestController_InFlightAdmission checks rejection, recovery and health exemption independently. +func TestController_InFlightAdmission(t *testing.T) { + cases := []struct { + name string + release bool + path string + status int + }{ + {"Negative: occupied execution slot", false, "/api/v1/users/me", http.StatusServiceUnavailable}, + {"Positive: released execution slot", true, "/api/v1/users/me", http.StatusUnauthorized}, + {"Positive: health bypasses occupied slot", false, "/health/live", http.StatusOK}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + ctrl := testController(t, func(cfg *config.Config) { + cfg.HTTP.Admission.MaxInFlight = 1 + }) + if !ctrl.admission.(*fixtureAdmission).Acquire() { + t.Fatal("fixture could not reserve slot") + } + if tc.release { + ctrl.admission.(*fixtureAdmission).Release() + } else { + t.Cleanup(ctrl.admission.(*fixtureAdmission).Release) + } + + // Act. + status, body, err := request(ctrl, http.MethodGet, tc.path, "", nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, tc.status, body) + }) + } +} + +// TestController_RateAdmission checks exhausted tokens without timing-dependent HTTP setup. +func TestController_RateAdmission(t *testing.T) { + t.Run("/api/v1/users/me", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + // Arrange. + ctrl := testController(t, func(cfg *config.Config) { + cfg.HTTP.Admission.RequestsPerSecond = 1 + cfg.HTTP.Admission.Burst = 1 + }) + if !ctrl.admission.(*fixtureAdmission).Allow(time.Now()) { + t.Fatal("fixture token missing") + } + expected := http.StatusTooManyRequests + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", "", nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, expected, body) + }) + }) + + t.Run("/health/ready", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + // Arrange. + ctrl := testController(t, func(cfg *config.Config) { + cfg.HTTP.Admission.RequestsPerSecond = 1 + cfg.HTTP.Admission.Burst = 1 + }) + if !ctrl.admission.(*fixtureAdmission).Allow(time.Now()) { + t.Fatal("fixture token missing") + } + expected := http.StatusOK + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/health/ready", "", nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, expected, body) + }) + }) +} + +// TestController_Draining checks each endpoint's admission policy during shutdown. +func TestController_Draining(t *testing.T) { + cases := []struct { + name string + path string + status int + }{ + {"Negative: readiness disabled", "/health/ready", http.StatusServiceUnavailable}, + {"Positive: liveness remains available", "/health/live", http.StatusOK}, + {"Negative: business requests rejected", "/api/v1/users/me", http.StatusServiceUnavailable}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + ctrl.stopping.Store(true) + + // Act. + status, body, err := request(ctrl, http.MethodGet, tc.path, "", nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, tc.status, body) + }) + } +} + +// TestController_UnknownRoute checks the public fallback for an unmatched path. +func TestController_UnknownRoute(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/missing", "", nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusNotFound, body) + assertErrorCode(t, body, "not_found") +} + +// TestController_New rejects each missing dependency independently. +func TestController_New(t *testing.T) { + t.Run("Negative: missing configuration", func(t *testing.T) { + // Arrange. + fixture := testController(t, nil) + + // Act. + ctrl, err := New(fixture.log, nil, fixture.service, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness) + + // Assert. + if err == nil || ctrl != nil { + t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err) + } + }) + + t.Run("Negative: missing logger", func(t *testing.T) { + // Arrange. + fixture := testController(t, nil) + + // Act. + ctrl, err := New(nil, &fixture.cfg, fixture.service, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness) + + // Assert. + if err == nil || ctrl != nil { + t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err) + } + }) + + t.Run("Negative: missing service", func(t *testing.T) { + // Arrange. + fixture := testController(t, nil) + + // Act. + ctrl, err := New(fixture.log, &fixture.cfg, nil, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness) + + // Assert. + if err == nil || ctrl != nil { + t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err) + } + }) + + t.Run("Negative: missing registry", func(t *testing.T) { + // Arrange. + fixture := testController(t, nil) + + // Act. + ctrl, err := New(fixture.log, &fixture.cfg, fixture.service, nil, fixture.admission, fixture.auth, fixture.readiness) + + // Assert. + if err == nil || ctrl != nil { + t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err) + } + }) + + t.Run("Negative: missing limiter", func(t *testing.T) { + // Arrange. + fixture := testController(t, nil) + + // Act. + ctrl, err := New(fixture.log, &fixture.cfg, fixture.service, fixture.errorRegistry, nil, fixture.auth, fixture.readiness) + + // Assert. + if err == nil || ctrl != nil { + t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err) + } + }) +} diff --git a/internal/controller/http/fiber/public_errors.go b/internal/controller/http/fiber/public_errors.go new file mode 100644 index 00000000..f69b7c12 --- /dev/null +++ b/internal/controller/http/fiber/public_errors.go @@ -0,0 +1,51 @@ +package fiber + +import ( + "errors" + + "go.lab260.ru/fielderr" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +var ( + errBusy = publicFailure(codeUnavailable, "server is busy") + errRateLimited = publicFailure(codeRateLimited, "request rate exceeded") + errTooLarge = publicFailure(codeTooLarge, "request body is too large") + errMedia = publicFailure(codeMedia, "expected application/json") + errInternal = publicFailure(codeInternal, "internal server error") +) + +// publicFailure creates a transport-owned error with a safe API message. +func publicFailure(code, message string) error { + return fielderr.WithStatus(errors.New(message), fielderr.NewStatusCode(code), message) +} + +// publicError maps application failures into the public API envelope. +// Unknown errors receive a fixed response without exposing their details. +func publicError(err error) error { + switch { + case errors.Is(err, service.ErrUnavailable): + return publicFailure(codeUnavailable, "dependency unavailable") + case errors.Is(err, service.ErrInvalid): + return fielderr.WithStatus(err, fielderr.NewStatusCode(codeInvalid), "invalid request") + case errors.Is(err, service.ErrUnauthorized): + return fielderr.WithStatus(err, fielderr.NewStatusCode(codeUnauthorized), "unknown user identity") + case errors.Is(err, service.ErrNotFound): + return fielderr.WithStatus(err, fielderr.NewStatusCode(codeNotFound), "resource not found") + case errors.Is(err, service.ErrConflict): + return fielderr.WithStatus(err, fielderr.NewStatusCode(codeConflict), "username already exists") + case errors.Is(err, service.ErrCapacity): + return fielderr.WithStatus(err, fielderr.NewStatusCode(codeUnavailable), "in-memory storage capacity reached") + case errors.Is(err, errBusy): + return errBusy + case errors.Is(err, errRateLimited): + return errRateLimited + case errors.Is(err, errTooLarge): + return errTooLarge + case errors.Is(err, errMedia): + return errMedia + default: + return errInternal + } +} diff --git a/internal/controller/http/fiber/public_errors_test.go b/internal/controller/http/fiber/public_errors_test.go new file mode 100644 index 00000000..801337ce --- /dev/null +++ b/internal/controller/http/fiber/public_errors_test.go @@ -0,0 +1,43 @@ +package fiber + +import ( + "errors" + "fmt" + "testing" + + "go.lab260.ru/fielderr" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// TestPublicErrorSafety maps wrapped application failures without exposing internal details. +func TestPublicErrorSafety(t *testing.T) { + t.Run("wrapped application error", func(t *testing.T) { + err := publicError(fmt.Errorf("private database detail: %w", service.ErrConflict)) + response := errorResponse(err, "request") + if response.Error.Code != codeConflict || response.Error.Message != "username already exists" { + t.Fatalf("unexpected response: %+v", response) + } + }) + t.Run("unknown error", func(t *testing.T) { + err := publicError(errors.New("private database detail")) + if err != errInternal { + t.Fatalf("unexpected public error: %v", err) + } + }) + t.Run("foreign public status", func(t *testing.T) { + err := fielderr.WithStatus(errors.New("private detail"), fielderr.NewStatusCode(codeInvalid), "private detail") + if publicError(err) != errInternal { + t.Fatal("untrusted error metadata reached the public response") + } + }) +} + +// TestPublicErrorUnavailable keeps dependency details out of the public envelope. +func TestPublicErrorUnavailable(t *testing.T) { + err := publicError(fmt.Errorf("private database detail: %w", service.ErrUnavailable)) + response := errorResponse(err, "request") + if response.Error.Code != codeUnavailable || response.Error.Message != "dependency unavailable" { + t.Fatalf("unexpected response: %+v", response) + } +} diff --git a/internal/controller/http/fiber/routes.go b/internal/controller/http/fiber/routes.go new file mode 100644 index 00000000..1438d60c --- /dev/null +++ b/internal/controller/http/fiber/routes.go @@ -0,0 +1,22 @@ +package fiber + +// initRoutes registers health endpoints and authenticated application routes. +func (ctrl *Controller) initRoutes() { + ctrl.server.Get("/health/live", ctrl.handleLive) + ctrl.server.Get("/health/ready", ctrl.handleReady) + ctrl.server.Use(ctrl.admit) + ctrl.server.Post("/api/v1/users", ctrl.HandleUsersCreate) + + ctrl.server.Post("/api/v1/auth/sessions", ctrl.HandleLogin) + + api := ctrl.server.Group("/api/v1", ctrl.requireIdentity) + api.Delete("/auth/sessions/current", ctrl.HandleLogout) + api.Get("/users/me", ctrl.HandleUsersGetMe) + api.Post("/chats", ctrl.HandleChatsCreate) + api.Get("/chats", ctrl.HandleChatsGetPage) + api.Get("/chats/:chat_id", ctrl.HandleChatsGetByID) + api.Post("/chats/:chat_id/messages", ctrl.HandleMessagesCreate) + api.Get("/chats/:chat_id/messages", ctrl.HandleMessagesGetPage) + + ctrl.server.Use(ctrl.handleNotFound) +} diff --git a/internal/controller/http/fiber/users_test.go b/internal/controller/http/fiber/users_test.go new file mode 100644 index 00000000..61d7e35d --- /dev/null +++ b/internal/controller/http/fiber/users_test.go @@ -0,0 +1,130 @@ +package fiber + +import ( + "net/http" + "strings" + "testing" + + "github.com/google/uuid" +) + +// TestController_UsersCreate checks one registration contract scenario per subtest. +func TestController_UsersCreate(t *testing.T) { + cases := []struct { + name string + body string + status int + }{ + {"Positive: valid Unicode display name", `{"password":"fixture-password-123","username":"alice","display_name":"Алиса 👋"}`, http.StatusCreated}, + {"Positive: display name at rune limit", `{"password":"fixture-password-123","username":"alice","display_name":"` + strings.Repeat("👋", 100) + `"}`, http.StatusCreated}, + {"Negative: display name exceeds rune limit", `{"password":"fixture-password-123","username":"alice","display_name":"` + strings.Repeat("👋", 101) + `"}`, http.StatusBadRequest}, + {"Negative: uppercase username", `{"password":"fixture-password-123","username":"Alice","display_name":"Alice"}`, http.StatusBadRequest}, + {"Negative: malformed JSON", `{`, http.StatusBadRequest}, + {"Negative: null root", `null`, http.StatusBadRequest}, + {"Negative: array root", `[]`, http.StatusBadRequest}, + {"Negative: missing fields", `{}`, http.StatusBadRequest}, + {"Negative: null field", `{"password":"fixture-password-123","username":"alice","display_name":null}`, http.StatusBadRequest}, + {"Negative: wrong field type", `{"password":"fixture-password-123","username":5,"display_name":"Alice"}`, http.StatusBadRequest}, + {"Negative: unknown field", `{"password":"fixture-password-123","username":"alice","display_name":"Alice","unknown":"secret"}`, http.StatusBadRequest}, + {"Negative: field name case", `{"password":"fixture-password-123","Username":"alice","display_name":"Alice"}`, http.StatusBadRequest}, + {"Negative: duplicate field", `{"password":"fixture-password-123","username":"alice","username":"bob","display_name":"Alice"}`, http.StatusBadRequest}, + {"Negative: trailing object", `{"password":"fixture-password-123","username":"alice","display_name":"Alice"} {}`, http.StatusBadRequest}, + {"Negative: invalid UTF-8", "{\"username\":\"alice\",\"display_name\":\"\xff\"}", http.StatusBadRequest}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + + // Act. + status, body, err := request(ctrl, http.MethodPost, "/api/v1/users", "", []byte(tc.body)) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, tc.status, body) + if tc.status == http.StatusBadRequest { + assertErrorCode(t, body, "invalid_request") + return + } + if body["username"] != "alice" || body["display_name"] == "" { + t.Fatalf("registration fields changed: %v", body) + } + if _, err := uuid.Parse(body["id"].(string)); err != nil { + t.Fatalf("invalid assigned ID: %v", err) + } + }) + } +} + +// TestController_UsersGetMe verifies profile selection and authentication failures. +func TestController_UsersGetMe(t *testing.T) { + t.Run("Positive: own profile", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + actor := user(t, ctrl) + identity := actor + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusOK, body) + if body["id"] != actor || body["display_name"] != "Алиса 👋" { + t.Fatalf("wrong profile: %v", body) + } + }) + + t.Run("Negative: missing identity", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + identity := "" + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusUnauthorized, body) + assertErrorCode(t, body, "unauthorized") + }) + + t.Run("Negative: unknown identity", func(t *testing.T) { + // Arrange. + ctrl := testController(t, nil) + identity := uuid.NewString() + + // Act. + status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil) + + // Assert. + if err != nil { + t.Fatal(err) + } + assertHTTPStatus(t, status, http.StatusUnauthorized, body) + assertErrorCode(t, body, "unauthorized") + }) +} + +// assertHTTPStatus reports the response body alongside a mismatched status. +func assertHTTPStatus(t *testing.T, got, want int, body map[string]any) { + t.Helper() + if got != want { + t.Fatalf("status=%d, want=%d, body=%v", got, want, body) + } +} + +// assertErrorCode checks the documented error classification independently of status. +func assertErrorCode(t *testing.T, body map[string]any, want string) { + t.Helper() + envelope, ok := body["error"].(map[string]any) + if !ok || envelope["code"] != want { + t.Fatalf("error=%v, want code %q", body, want) + } +} diff --git a/internal/controller/interface.go b/internal/controller/interface.go new file mode 100644 index 00000000..46e9af5f --- /dev/null +++ b/internal/controller/interface.go @@ -0,0 +1,12 @@ +// Package controller connects transport lifecycles to Fx. +package controller + +import "context" + +// Controller is a process-owned transport server. +type Controller interface { + // Start acquires the listener and reports startup errors to the lifecycle owner. + Start(context.Context) error + // Stop stops accepting work and drains active requests within the supplied deadline. + Stop(context.Context) error +} diff --git a/internal/cursor/codec.go b/internal/cursor/codec.go new file mode 100644 index 00000000..92789f50 --- /dev/null +++ b/internal/cursor/codec.go @@ -0,0 +1,108 @@ +// Package cursor signs and verifies resource-bound keyset positions. +package cursor + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +const ( + cursorSigningKeyBytes = 32 + maxEncodedCursorBytes = 1024 +) + +// ErrInvalid means a cursor is malformed, tampered with or bound to another resource. +var ErrInvalid = errors.New("invalid cursor") + +// Position identifies the last record already returned by keyset pagination. +type Position struct { + // CreatedAt is the creation timestamp of the last returned record. + CreatedAt time.Time + // ID breaks ties between records sharing a timestamp. + ID uuid.UUID +} + +// Codec authenticates pagination positions with an immutable process-local key. +type Codec struct { + key [cursorSigningKeyBytes]byte +} + +type cursorPayload struct { + // Resource binds the position to a chat history or one user's chat list. + Resource string `json:"r"` + // Time is the creation timestamp of the last record in the previous page. + Time time.Time `json:"t"` + // ID breaks ties between records with the same creation timestamp. + ID uuid.UUID `json:"i"` +} + +// New creates a cursor codec with a random process-local signing key. +func New() (*Codec, error) { + codec := &Codec{} + if _, err := rand.Read(codec.key[:]); err != nil { + return nil, err + } + return codec, nil +} + +// Encode serializes and signs a pagination position bound to a resource. +func (codec *Codec) Encode(resource string, position Position) (string, error) { + payload, err := json.Marshal(cursorPayload{ + Resource: resource, + Time: position.CreatedAt, + ID: position.ID, + }) + if err != nil { + return "", fmt.Errorf("encode cursor: %w", err) + } + payload = append(payload, codec.signature(payload)...) + return base64.RawURLEncoding.EncodeToString(payload), nil +} + +// Decode verifies the cursor signature and extracts its resource-bound position. +func (codec *Codec) Decode(encoded, resource string) (Position, error) { + if encoded == "" { + return Position{}, nil + } + if len(encoded) > maxEncodedCursorBytes { + return Position{}, ErrInvalid + } + signed, err := base64.RawURLEncoding.DecodeString(encoded) + if err != nil || len(signed) <= sha256.Size { + return Position{}, ErrInvalid + } + boundary := len(signed) - sha256.Size + payload, signature := signed[:boundary], signed[boundary:] + if !hmac.Equal(signature, codec.signature(payload)) { + return Position{}, ErrInvalid + } + return decodeCursorPosition(payload, resource) +} + +// signature computes the HMAC-SHA256 authentication tag for a cursor payload. +func (codec *Codec) signature(payload []byte) []byte { + mac := hmac.New(sha256.New, codec.key[:]) + // hash.Hash.Write is documented to always return a nil error. + _, _ = mac.Write(payload) + return mac.Sum(nil) +} + +// decodeCursorPosition validates the decoded cursor resource and timestamp. +func decodeCursorPosition(payload []byte, resource string) (Position, error) { + var cursor cursorPayload + if err := json.Unmarshal(payload, &cursor); err != nil { + return Position{}, ErrInvalid + } + if cursor.Resource != resource || cursor.Time.IsZero() { + return Position{}, ErrInvalid + } + return Position{CreatedAt: cursor.Time, ID: cursor.ID}, nil +} diff --git a/internal/cursor/codec_test.go b/internal/cursor/codec_test.go new file mode 100644 index 00000000..56832367 --- /dev/null +++ b/internal/cursor/codec_test.go @@ -0,0 +1,179 @@ +package cursor + +import ( + "encoding/base64" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +// TestCodec_EncodeDecode preserves the complete position through an authenticated round trip. +func TestCodec_EncodeDecode(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + position := Position{CreatedAt: time.Unix(1700000000, 123456789).UTC(), ID: uuid.New()} + + // Act. + encoded, err := codec.Encode("chats:alice", position) + + // Assert. + if err != nil { + t.Fatal(err) + } + if encoded == "" { + t.Fatal("encoded position is empty") + } + decoded, err := codec.Decode(encoded, "chats:alice") + if err != nil || decoded != position { + t.Fatalf("decoded=%v, want=%v, error=%v", decoded, position, err) + } +} + +// TestCodec_Decode checks first-page behavior and independent rejection conditions. +func TestCodec_Decode(t *testing.T) { + t.Run("Positive: empty token starts first page", func(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + + // Act. + got, err := codec.Decode("", "chats:alice") + + // Assert. + if err != nil || got != (Position{}) { + t.Fatalf("first-page position=%v, error=%v", got, err) + } + }) + + t.Run("Negative: another resource", func(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + encoded := encodeFixture(t, codec, "chats:alice") + + // Act. + got, err := codec.Decode(encoded, "chats:bob") + + // Assert. + if !errors.Is(err, ErrInvalid) || got != (Position{}) { + t.Fatalf("position=%v, error=%v", got, err) + } + }) + + t.Run("Negative: another process key", func(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + encoded := encodeFixture(t, codec, "chats:alice") + codec = newTestCodec(t) + + // Act. + got, err := codec.Decode(encoded, "chats:alice") + + // Assert. + if !errors.Is(err, ErrInvalid) || got != (Position{}) { + t.Fatalf("position=%v, error=%v", got, err) + } + }) + + t.Run("Negative: tampered payload", func(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + encoded := encodeFixture(t, codec, "chats:alice") + signed, err := base64.RawURLEncoding.DecodeString(encoded) + if err != nil { + t.Fatal(err) + } + signed[0] ^= 1 + encoded = base64.RawURLEncoding.EncodeToString(signed) + + // Act. + got, err := codec.Decode(encoded, "chats:alice") + + // Assert. + if !errors.Is(err, ErrInvalid) || got != (Position{}) { + t.Fatalf("position=%v, error=%v", got, err) + } + }) + + t.Run("Negative: oversized token", func(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + encoded := strings.Repeat("a", 1025) + + // Act. + got, err := codec.Decode(encoded, "chats:alice") + + // Assert. + if !errors.Is(err, ErrInvalid) || got != (Position{}) { + t.Fatalf("position=%v, error=%v", got, err) + } + }) + + t.Run("Negative: malformed base64", func(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + encoded := "!invalid!" + + // Act. + got, err := codec.Decode(encoded, "chats:alice") + + // Assert. + if !errors.Is(err, ErrInvalid) || got != (Position{}) { + t.Fatalf("position=%v, error=%v", got, err) + } + }) + + t.Run("Negative: signed malformed JSON", func(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + encoded := signedPayload(codec, []byte("not JSON")) + + // Act. + got, err := codec.Decode(encoded, "chats:alice") + + // Assert. + if !errors.Is(err, ErrInvalid) || got != (Position{}) { + t.Fatalf("position=%v, error=%v", got, err) + } + }) + + t.Run("Negative: signed zero timestamp", func(t *testing.T) { + // Arrange. + codec := newTestCodec(t) + encoded := signedPayload(codec, []byte(`{"r":"chats:alice","t":"0001-01-01T00:00:00Z","i":"11111111-1111-1111-1111-111111111111"}`)) + + // Act. + got, err := codec.Decode(encoded, "chats:alice") + + // Assert. + if !errors.Is(err, ErrInvalid) || got != (Position{}) { + t.Fatalf("position=%v, error=%v", got, err) + } + }) +} + +// signedPayload creates authenticated malformed fixtures to isolate payload validation. +func signedPayload(codec *Codec, payload []byte) string { + return base64.RawURLEncoding.EncodeToString(append(payload, codec.signature(payload)...)) +} + +// newTestCodec creates an independent signing key for one scenario. +func newTestCodec(t *testing.T) *Codec { + t.Helper() + codec, err := New() + if err != nil { + t.Fatal(err) + } + return codec +} + +// encodeFixture prepares a valid token before testing a separate decoding condition. +func encodeFixture(t *testing.T, codec *Codec, resource string) string { + t.Helper() + token, err := codec.Encode(resource, Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}) + if err != nil { + t.Fatal(err) + } + return token +} diff --git a/internal/hashring/ring.go b/internal/hashring/ring.go new file mode 100644 index 00000000..f8c03623 --- /dev/null +++ b/internal/hashring/ring.go @@ -0,0 +1,62 @@ +// Package hashring implements immutable consistent hashing with virtual nodes. +package hashring + +import ( + "cmp" + "crypto/sha256" + "encoding/binary" + "fmt" + "slices" + "sort" + "strconv" +) + +type point struct { + hash uint64 + node string +} + +// Ring maps arbitrary keys to stable node identifiers. +type Ring struct { + points []point +} + +// New creates an order-independent ring and rejects ambiguous node identities. +func New(nodes []string, replicas int) (*Ring, error) { + if len(nodes) == 0 || replicas < 1 { + return nil, fmt.Errorf("nodes and positive virtual node count are required") + } + ring := &Ring{} + seen := make(map[string]bool) + for _, node := range nodes { + if node == "" || seen[node] { + return nil, fmt.Errorf("node identifiers must be unique and nonempty") + } + seen[node] = true + for index := range replicas { + ring.points = append(ring.points, point{hash: hash(node + ":" + strconv.Itoa(index)), node: node}) + } + } + slices.SortFunc(ring.points, func(a, b point) int { + if order := cmp.Compare(a.hash, b.hash); order != 0 { + return order + } + return cmp.Compare(a.node, b.node) + }) + return ring, nil +} + +// Owner selects the first virtual node clockwise from the key hash. +func (r *Ring) Owner(key string) string { + value := hash(key) + index := sort.Search(len(r.points), func(index int) bool { + return r.points[index].hash >= value + }) + return r.points[index%len(r.points)].node +} + +// hash maps a stable string into the ring's 64-bit coordinate space. +func hash(value string) uint64 { + sum := sha256.Sum256([]byte(value)) + return binary.BigEndian.Uint64(sum[:8]) +} diff --git a/internal/hashring/ring_test.go b/internal/hashring/ring_test.go new file mode 100644 index 00000000..56bd7625 --- /dev/null +++ b/internal/hashring/ring_test.go @@ -0,0 +1,73 @@ +package hashring + +import ( + "fmt" + "testing" +) + +// TestExpansionMovesOnlyKeysOwnedByNewNode verifies the consistent hashing invariant. +func TestExpansionMovesOnlyKeysOwnedByNewNode(t *testing.T) { + before, err := New([]string{"a", "b"}, 256) + if err != nil { + t.Fatal(err) + } + after, err := New([]string{"c", "b", "a"}, 256) + if err != nil { + t.Fatal(err) + } + moved := 0 + for index := range 100000 { + key := fmt.Sprint(index) + oldOwner, newOwner := before.Owner(key), after.Owner(key) + if oldOwner != newOwner { + moved++ + if newOwner != "c" { + t.Fatalf("existing nodes exchanged key %s", key) + } + } + } + fraction := float64(moved) / 100000 + if fraction < 0.2 || fraction > 0.45 { + t.Fatalf("unexpected moved fraction: %f", fraction) + } + t.Logf("100000 keys: moved=%d fraction=%.5f", moved, fraction) +} + +// TestRingRejectsAmbiguousConfiguration checks independent malformed rings. +func TestRingRejectsAmbiguousConfiguration(t *testing.T) { + cases := []struct { + name string + nodes []string + replicas int + }{ + {"empty", nil, 1}, + {"zero replicas", []string{"a"}, 0}, + {"empty node", []string{""}, 1}, + {"duplicate", []string{"a", "a"}, 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if _, err := New(tc.nodes, tc.replicas); err == nil { + t.Fatal("invalid ring accepted") + } + }) + } +} + +// TestRingIgnoresInputOrder verifies that replicas agree despite configuration ordering. +func TestRingIgnoresInputOrder(t *testing.T) { + a, err := New([]string{"a", "b"}, 64) + if err != nil { + t.Fatal(err) + } + b, err := New([]string{"b", "a"}, 64) + if err != nil { + t.Fatal(err) + } + for index := range 1000 { + key := fmt.Sprint(index) + if a.Owner(key) != b.Owner(key) { + t.Fatal("node order changes ownership") + } + } +} diff --git a/internal/model/dto/models.go b/internal/model/dto/models.go new file mode 100644 index 00000000..78aea0b1 --- /dev/null +++ b/internal/model/dto/models.go @@ -0,0 +1,110 @@ +// Package dto defines the transport-independent data shared by service and store. +package dto + +import ( + "time" + + "github.com/google/uuid" +) + +// UserDTO is the public account profile without credentials. +type UserDTO struct { + // ID is the server-generated user identifier. + ID uuid.UUID + // Username is the unique lowercase ASCII account name. + Username string + // DisplayName is the display label, limited to 100 Unicode code points. + DisplayName string + // CreatedAt is the server-assigned UTC creation time. + CreatedAt time.Time +} + +// ChatDTO is a chat with immutable membership. +type ChatDTO struct { + // ID is the server-generated chat identifier. + ID uuid.UUID + // Title is the nonblank title, limited to 100 Unicode code points. + Title string + // MemberIDs contains the fixed set of users allowed to read and write the chat. + MemberIDs []uuid.UUID + // CreatedAt is the server-assigned UTC creation time. + CreatedAt time.Time +} + +// MessageDTO is an immutable message stored in a chat. +type MessageDTO struct { + // ID is the server-generated message identifier. + ID uuid.UUID + // ChatID identifies the owning chat. + ChatID uuid.UUID + // SenderID identifies the user resolved from the request identity. + SenderID uuid.UUID + // Text contains the original text, limited to 4000 Unicode code points. + Text string + // CreatedAt is the server-assigned UTC ordering timestamp. + CreatedAt time.Time +} + +// UsersCreateRequestDTO carries untrusted registration values into the service. +type UsersCreateRequestDTO struct { + // Username is the raw requested account name. + Username string + // DisplayName is the raw requested display label. + DisplayName string +} + +// ChatsCreateRequestDTO carries untrusted chat creation input. +type ChatsCreateRequestDTO struct { + // UserID is the caller identifier resolved from a validated session. + UserID string + // Title is the raw requested chat title. + Title string + // MemberIDs contains raw user UUIDs; the service checks uniqueness and membership. + MemberIDs []string +} + +// MessagesCreateRequestDTO carries untrusted message creation input. +type MessagesCreateRequestDTO struct { + // UserID is the authenticated caller identifier, never a supplied sender field. + UserID string + // ChatID is the raw chat UUID from the route. + ChatID string + // Text is the unmodified message text to validate. + Text string +} + +// PageRequestDTO carries raw pagination values for service-level validation. +type PageRequestDTO struct { + // UserID is the caller identifier resolved from a validated session. + UserID string + // ChatID is the requested chat UUID; it is unused when listing chats. + ChatID string + // Limit is the raw page size; empty selects the contract default. + Limit string + // Cursor is the opaque continuation token; empty starts at the beginning. + Cursor string +} + +// PositionDTO is a validated keyset boundary; its zero value starts a history. +type PositionDTO struct { + // CreatedAt is the timestamp of the last record already returned. + CreatedAt time.Time + // ID is the tie-breaking identifier of the last record already returned. + ID uuid.UUID +} + +// ChatPageDTO contains an ordered page of accessible chats. +type ChatPageDTO struct { + // Items contains at most the requested number of chats. + Items []ChatDTO + // NextCursor continues the same user-specific list; nil marks its current end. + NextCursor *string +} + +// MessagePageDTO contains an ordered page of chat history. +type MessagePageDTO struct { + // Items contains at most the requested number of messages. + Items []MessageDTO + // NextCursor continues the same chat history; nil marks its current end. + NextCursor *string +} diff --git a/internal/model/dto/session.go b/internal/model/dto/session.go new file mode 100644 index 00000000..9d1193cd --- /dev/null +++ b/internal/model/dto/session.go @@ -0,0 +1,13 @@ +package dto + +import "time" + +// SessionDTO is an issued session, exposing the raw token only at creation. +type SessionDTO struct { + // Token contains 256 random bits encoded for a Bearer header. + Token string + // ExpiresAt is an absolute UTC deadline which is not extended by reads. + ExpiresAt time.Time + // User is the authenticated account without credentials. + User UserDTO +} diff --git a/internal/model/http/models.go b/internal/model/http/models.go new file mode 100644 index 00000000..4ad10c8a --- /dev/null +++ b/internal/model/http/models.go @@ -0,0 +1,98 @@ +// Package http defines the public JSON boundary, separate from DTOs. +package http + +import "time" + +// UsersCreateRequest is the registration payload. +type UsersCreateRequest struct { + // Password is the unmodified Unicode registration secret. + Password string `json:"password"` + // Username is the unique lowercase ASCII username. + Username string `json:"username"` + // DisplayName is the user-visible name, limited to 100 Unicode code points. + DisplayName string `json:"display_name"` +} + +// ChatsCreateRequest is the chat payload. +type ChatsCreateRequest struct { + // Title is the nonblank chat title, limited to 100 Unicode code points. + Title string `json:"title"` + // MemberIDs contains unique user UUIDs, including the caller when creating a chat. + MemberIDs []string `json:"member_ids"` +} + +// MessagesCreateRequest is the message payload. +type MessagesCreateRequest struct { + // Text contains nonblank text, limited to 4000 Unicode code points. + Text string `json:"text"` +} + +// UserResponse is the public user model. +type UserResponse struct { + // ID is the canonical server-generated UUID. + ID string `json:"id"` + // Username is the unique lowercase ASCII username. + Username string `json:"username"` + // DisplayName is the user-visible name, limited to 100 Unicode code points. + DisplayName string `json:"display_name"` + // CreatedAt is the UTC creation time serialized as RFC 3339. + CreatedAt time.Time `json:"created_at"` +} + +// ChatResponse is the public chat model. +type ChatResponse struct { + // ID is the canonical server-generated UUID. + ID string `json:"id"` + // Title is the nonblank chat title, limited to 100 Unicode code points. + Title string `json:"title"` + // MemberIDs contains unique user UUIDs, including the caller when creating a chat. + MemberIDs []string `json:"member_ids"` + // CreatedAt is the UTC creation time serialized as RFC 3339. + CreatedAt time.Time `json:"created_at"` +} + +// MessageResponse is the public message model. +type MessageResponse struct { + // ID is the canonical server-generated UUID. + ID string `json:"id"` + // ChatID is the canonical UUID of the chat containing the message. + ChatID string `json:"chat_id"` + // SenderID is derived from the request identity, never from a client-supplied sender. + SenderID string `json:"sender_id"` + // Text contains nonblank text, limited to 4000 Unicode code points. + Text string `json:"text"` + // CreatedAt is the UTC creation time serialized as RFC 3339. + CreatedAt time.Time `json:"created_at"` +} + +// ChatPageResponse contains visible chats. +type ChatPageResponse struct { + // Items contains the ordered page records; an empty page is serialized as an empty array. + Items []ChatResponse `json:"items"` + // NextCursor is the opaque continuation token or null when the current page is last. + NextCursor *string `json:"next_cursor"` +} + +// MessagePageResponse contains the requested history page. +type MessagePageResponse struct { + // Items contains the ordered page records; an empty page is serialized as an empty array. + Items []MessageResponse `json:"items"` + // NextCursor is the opaque continuation token or null when the current page is last. + NextCursor *string `json:"next_cursor"` +} + +// ErrorResponse is the mandatory error envelope. +type ErrorResponse struct { + // Error contains the safe public error details. + Error ErrorDetail `json:"error"` +} + +// ErrorDetail never exposes internal errors or input contents. +type ErrorDetail struct { + // Code is one of the machine-readable error codes declared by the API contract. + Code string `json:"code"` + // Message is a safe public explanation without internal errors or input contents. + Message string `json:"message"` + // RequestID matches the X-Request-Id response header for log correlation. + RequestID string `json:"request_id"` +} diff --git a/internal/password/password.go b/internal/password/password.go new file mode 100644 index 00000000..630e1608 --- /dev/null +++ b/internal/password/password.go @@ -0,0 +1,54 @@ +// Package password implements a bounded Argon2id password KDF. +package password + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "strings" + + "golang.org/x/crypto/argon2" +) + +const ( + memoryKiB = 19 * 1024 + iterations = 2 + parallelism = 1 + saltBytes = 16 + hashBytes = 32 + prefix = "$argon2id$v=19$m=19456,t=2,p=1$" +) + +// Hasher implements password hashing without transport or storage dependencies. +type Hasher struct{} + +// Hash generates a salted Argon2id encoding using fixed resource bounds. +func (Hasher) Hash(password string) (string, error) { + salt := make([]byte, saltBytes) + if _, err := rand.Read(salt); err != nil { + return "", err + } + hash := argon2.IDKey([]byte(password), salt, iterations, memoryKiB, parallelism, hashBytes) + return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash), nil +} + +// Verify accepts only this application's bounded KDF encoding and compares in constant time. +func (Hasher) Verify(encoded, password string) bool { + if !strings.HasPrefix(encoded, prefix) { + return false + } + parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$") + if len(parts) != 2 { + return false + } + salt, err := base64.RawStdEncoding.DecodeString(parts[0]) + if err != nil || len(salt) != saltBytes { + return false + } + expected, err := base64.RawStdEncoding.DecodeString(parts[1]) + if err != nil || len(expected) != hashBytes { + return false + } + actual := argon2.IDKey([]byte(password), salt, iterations, memoryKiB, parallelism, hashBytes) + return subtle.ConstantTimeCompare(actual, expected) == 1 +} diff --git a/internal/password/password_test.go b/internal/password/password_test.go new file mode 100644 index 00000000..565df62b --- /dev/null +++ b/internal/password/password_test.go @@ -0,0 +1,37 @@ +package password + +import ( + "strings" + "testing" +) + +// TestPasswordRoundTrip verifies long Unicode input without bcrypt-style truncation. +func TestPasswordRoundTrip(t *testing.T) { + password := strings.Repeat("🔐", 128) + hasher := Hasher{} + encoded, err := hasher.Hash(password) + if err != nil { + t.Fatal(err) + } + if !hasher.Verify(encoded, password) || hasher.Verify(encoded, password+"x") { + t.Fatal("password verification mismatch") + } + second, err := hasher.Hash(password) + if err != nil { + t.Fatal(err) + } + if encoded == second { + t.Fatal("salt reused") + } +} + +// TestPasswordRejectsInvalidEncoding checks corrupt or unbounded KDF descriptions. +func TestPasswordRejectsInvalidEncoding(t *testing.T) { + for _, encoded := range []string{"", "$argon2id$v=19$m=999999999,t=2,p=1$a$b", prefix + "x", prefix + "%%%$abc", prefix + "YWJj$abc", prefix + "AAAAAAAAAAAAAAAAAAAAAA$%%%", prefix + "AAAAAAAAAAAAAAAAAAAAAA$YWJj"} { + t.Run(encoded, func(t *testing.T) { + if (Hasher{}).Verify(encoded, "password") { + t.Fatal("invalid encoding accepted") + } + }) + } +} diff --git a/internal/service/auth.go b/internal/service/auth.go new file mode 100644 index 00000000..19d5d928 --- /dev/null +++ b/internal/service/auth.go @@ -0,0 +1,44 @@ +package service + +import ( + "context" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// Passwords is the password KDF boundary used by authentication. +type Passwords interface { + // Hash creates a salted password encoding. + Hash(password string) (string, error) + // Verify checks the supplied password against its encoding. + Verify(encoded, password string) bool +} + +// Accounts persists credentials and session validity independently of HTTP. +type Accounts interface { + // Register atomically stores a profile with credentials. + Register(context.Context, dto.UserDTO, string) (dto.UserDTO, error) + // Credentials looks up the password encoding and account profile. + Credentials(context.Context, string) (dto.UserDTO, string, error) + // SaveSession persists an opaque token digest and absolute expiry. + SaveSession(context.Context, string, uuid.UUID, time.Time) error + // SessionUser resolves an unexpired token digest. + SessionUser(context.Context, string) (uuid.UUID, error) + // RevokeSession invalidates a token digest. + RevokeSession(context.Context, string) error +} + +// Authentication defines registration and opaque session operations. +type Authentication interface { + // Register validates registration and persists a password-protected account. + Register(context.Context, dto.UsersCreateRequestDTO, string) (dto.UserDTO, error) + // Login verifies credentials and issues an opaque session. + Login(context.Context, string, string) (dto.SessionDTO, error) + // Authenticate resolves a valid token to its immutable owner. + Authenticate(context.Context, string) (string, error) + // Logout revokes the current token. + Logout(context.Context, string) error +} diff --git a/internal/service/authentication/service.go b/internal/service/authentication/service.go new file mode 100644 index 00000000..1b6d87e3 --- /dev/null +++ b/internal/service/authentication/service.go @@ -0,0 +1,123 @@ +// Package authentication validates credentials and owns the session lifecycle. +package authentication + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "time" + "unicode/utf8" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service/production" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +const ( + minimumPasswordRunes = 12 + maximumPasswordRunes = 128 + tokenBytes = 32 +) + +// Service performs password and session operations through explicit boundaries. +type Service struct { + accounts service.Accounts + passwords service.Passwords + ttl time.Duration + dummyHash string +} + +// New validates dependencies and prepares the unknown-account verification hash. +func New(accounts service.Accounts, passwords service.Passwords, ttl time.Duration) (*Service, error) { + if accounts == nil || passwords == nil || ttl <= 0 { + return nil, fmt.Errorf("accounts, passwords and positive session TTL are required") + } + dummyHash, err := passwords.Hash("unknown-account-dummy-password") + if err != nil { + return nil, err + } + return &Service{accounts: accounts, passwords: passwords, ttl: ttl, dummyHash: dummyHash}, nil +} + +// Register checks profile and Unicode password bounds before hashing and persistence. +func (s *Service) Register(ctx context.Context, request dto.UsersCreateRequestDTO, password string) (dto.UserDTO, error) { + user, err := production.PrepareUser(request) + if err != nil || !validPassword(password) { + return dto.UserDTO{}, service.ErrInvalid + } + hash, err := s.passwords.Hash(password) + if err != nil { + return dto.UserDTO{}, err + } + user, err = s.accounts.Register(ctx, user, hash) + if errors.Is(err, store.ErrConflict) { + return dto.UserDTO{}, service.ErrConflict + } + return user, err +} + +// Login verifies credentials uniformly and persists a new session before returning its token. +func (s *Service) Login(ctx context.Context, username, password string) (dto.SessionDTO, error) { + if !validPassword(password) { + return dto.SessionDTO{}, service.ErrUnauthorized + } + user, hash, err := s.accounts.Credentials(ctx, username) + if err != nil && !errors.Is(err, store.ErrNotFound) { + return dto.SessionDTO{}, err + } + missing := errors.Is(err, store.ErrNotFound) + if missing { + hash = s.dummyHash + } + if !s.passwords.Verify(hash, password) || missing { + return dto.SessionDTO{}, service.ErrUnauthorized + } + random := make([]byte, tokenBytes) + if _, err := rand.Read(random); err != nil { + return dto.SessionDTO{}, err + } + token := base64.RawURLEncoding.EncodeToString(random) + expiry := time.Now().UTC().Add(s.ttl) + if err := s.accounts.SaveSession(ctx, digest(token), user.ID, expiry); err != nil { + return dto.SessionDTO{}, err + } + return dto.SessionDTO{Token: token, ExpiresAt: expiry, User: user}, nil +} + +// Authenticate checks absolute expiry in the source of truth on every request. +func (s *Service) Authenticate(ctx context.Context, token string) (string, error) { + decoded, err := base64.RawURLEncoding.DecodeString(token) + if err != nil || len(decoded) != tokenBytes { + return "", service.ErrUnauthorized + } + id, err := s.accounts.SessionUser(ctx, digest(token)) + if errors.Is(err, store.ErrNotFound) { + return "", service.ErrUnauthorized + } + if err != nil { + return "", err + } + return id.String(), nil +} + +// Logout removes the current session from the authoritative store. +func (s *Service) Logout(ctx context.Context, token string) error { + return s.accounts.RevokeSession(ctx, digest(token)) +} + +// digest produces the storage key without persisting the bearer secret. +func digest(token string) string { + hash := sha256.Sum256([]byte(token)) + return hex.EncodeToString(hash[:]) +} + +// validPassword enforces the contract in Unicode code points without truncation. +func validPassword(password string) bool { + count := utf8.RuneCountInString(password) + return utf8.ValidString(password) && count >= minimumPasswordRunes && count <= maximumPasswordRunes +} diff --git a/internal/service/authentication/service_test.go b/internal/service/authentication/service_test.go new file mode 100644 index 00000000..f7994a97 --- /dev/null +++ b/internal/service/authentication/service_test.go @@ -0,0 +1,232 @@ +package authentication + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +type accountFixture struct { + user dto.UserDTO + hash string + tokenHash string + expiry time.Time + failure error + registerFailure error + saveFailure error +} + +// Register captures one synthetic account or a prescribed persistence failure. +func (f *accountFixture) Register(_ context.Context, user dto.UserDTO, hash string) (dto.UserDTO, error) { + f.user = user + f.hash = hash + return user, f.registerFailure +} + +// Credentials returns the fixture account and its password encoding. +func (f *accountFixture) Credentials(context.Context, string) (dto.UserDTO, string, error) { + return f.user, f.hash, f.failure +} + +// SaveSession captures the digest and absolute expiry without storing the raw token. +func (f *accountFixture) SaveSession(_ context.Context, hash string, _ uuid.UUID, expiry time.Time) error { + f.tokenHash = hash + f.expiry = expiry + return f.saveFailure +} + +// SessionUser implements expiry and revocation for the service unit fixture. +func (f *accountFixture) SessionUser(_ context.Context, hash string) (uuid.UUID, error) { + if f.failure != nil { + return uuid.Nil, f.failure + } + if hash != f.tokenHash || !f.expiry.After(time.Now()) { + return uuid.Nil, store.ErrNotFound + } + return f.user.ID, nil +} + +// RevokeSession invalidates the fixture digest. +func (f *accountFixture) RevokeSession(context.Context, string) error { + f.tokenHash = "" + return f.failure +} + +type passwordFixture struct { + failure error +} + +// Hash creates an intentionally noncryptographic encoding for service-only unit tests. +func (f passwordFixture) Hash(password string) (string, error) { + return "fixture:" + password, f.failure +} + +// Verify compares only test fixture encodings; production uses Argon2id. +func (passwordFixture) Verify(encoded, password string) bool { + return encoded == "fixture:"+password +} + +// authFixture assembles deterministic service boundaries. +func authFixture(t *testing.T) (*Service, *accountFixture) { + t.Helper() + accounts := &accountFixture{user: dto.UserDTO{ID: uuid.New(), Username: "alice"}, hash: "fixture:synthetic-password"} + s, err := New(accounts, passwordFixture{}, time.Hour) + if err != nil { + t.Fatal(err) + } + return s, accounts +} + +// TestRegisterValidatesPassword checks contract boundaries without truncation. +func TestRegisterValidatesPassword(t *testing.T) { + cases := []struct { + name string + password string + valid bool + }{ + {"short", "short", false}, + {"minimum", strings.Repeat("a", 12), true}, + {"unicode maximum", strings.Repeat("🔐", 128), true}, + {"too long", strings.Repeat("a", 129), false}, + {"invalid UTF8", strings.Repeat("a", 12) + "\xff", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s, _ := authFixture(t) + _, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, tc.password) + if (err == nil) != tc.valid { + t.Fatalf("unexpected registration result: %v", err) + } + }) + } +} + +// TestRegisterConflictMapsToApplicationError verifies uniqueness error translation. +func TestRegisterConflictMapsToApplicationError(t *testing.T) { + s, accounts := authFixture(t) + accounts.registerFailure = store.ErrConflict + _, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password") + if !errors.Is(err, service.ErrConflict) { + t.Fatal(err) + } +} + +// TestRegisterHashFailurePreservesCause checks KDF failures before persistence. +func TestRegisterHashFailurePreservesCause(t *testing.T) { + s, _ := authFixture(t) + failure := errors.New("KDF unavailable") + s.passwords = passwordFixture{failure: failure} + _, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password") + if !errors.Is(err, failure) { + t.Fatal(err) + } +} + +// TestLoginPersistsOnlyTokenDigest checks issued entropy, owner and deadline together. +func TestLoginPersistsOnlyTokenDigest(t *testing.T) { + s, accounts := authFixture(t) + session, err := s.Login(t.Context(), "alice", "synthetic-password") + if err != nil { + t.Fatal(err) + } + if session.Token == accounts.tokenHash || len(accounts.tokenHash) != 64 || session.User.ID != accounts.user.ID || !session.ExpiresAt.Equal(accounts.expiry) { + t.Fatal("invalid issued session") + } + id, err := s.Authenticate(t.Context(), session.Token) + if err != nil || id != accounts.user.ID.String() { + t.Fatalf("session does not authenticate its owner: %v", err) + } +} + +// TestLoginRejectsCredentials checks independent authentication rejection scenarios. +func TestLoginRejectsCredentials(t *testing.T) { + cases := []struct { + name string + password string + failure error + expected error + }{ + {"short password", "short", nil, service.ErrUnauthorized}, + {"wrong password", "incorrect-password", nil, service.ErrUnauthorized}, + {"missing account", "synthetic-password", store.ErrNotFound, service.ErrUnauthorized}, + {"database unavailable", "synthetic-password", context.DeadlineExceeded, context.DeadlineExceeded}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s, accounts := authFixture(t) + accounts.failure = tc.failure + _, err := s.Login(t.Context(), "alice", tc.password) + if !errors.Is(err, tc.expected) { + t.Fatalf("expected %v, got %v", tc.expected, err) + } + }) + } +} + +// TestLoginDoesNotReturnUnpersistedSession checks failure after successful password verification. +func TestLoginDoesNotReturnUnpersistedSession(t *testing.T) { + s, accounts := authFixture(t) + accounts.saveFailure = context.DeadlineExceeded + session, err := s.Login(t.Context(), "alice", "synthetic-password") + if !errors.Is(err, context.DeadlineExceeded) || session.Token != "" { + t.Fatal("unpersisted session escaped") + } +} + +// TestAuthenticateRejectsUnknownToken checks malformed and correctly encoded unknown tokens. +func TestAuthenticateRejectsUnknownToken(t *testing.T) { + for _, token := range []string{"", "%%%", strings.Repeat("A", 43)} { + t.Run(token, func(t *testing.T) { + s, _ := authFixture(t) + if _, err := s.Authenticate(t.Context(), token); !errors.Is(err, service.ErrUnauthorized) { + t.Fatal(err) + } + }) + } +} + +// TestAuthenticatePropagatesDatabaseFailure prevents trusting a token during an outage. +func TestAuthenticatePropagatesDatabaseFailure(t *testing.T) { + s, accounts := authFixture(t) + accounts.failure = context.DeadlineExceeded + if _, err := s.Authenticate(t.Context(), strings.Repeat("A", 43)); !errors.Is(err, context.DeadlineExceeded) { + t.Fatal(err) + } +} + +// TestLogoutRevokesIssuedToken checks that the same token cannot be reused. +func TestLogoutRevokesIssuedToken(t *testing.T) { + s, _ := authFixture(t) + session, err := s.Login(t.Context(), "alice", "synthetic-password") + if err != nil { + t.Fatal(err) + } + if err := s.Logout(t.Context(), session.Token); err != nil { + t.Fatal(err) + } + if _, err := s.Authenticate(t.Context(), session.Token); !errors.Is(err, service.ErrUnauthorized) { + t.Fatal("revoked token authenticated") + } +} + +// TestNewRejectsIncompleteDependencies checks constructor validation and KDF startup failure. +func TestNewRejectsIncompleteDependencies(t *testing.T) { + t.Run("missing accounts", func(t *testing.T) { + if _, err := New(nil, passwordFixture{}, time.Hour); err == nil { + t.Fatal("missing accounts accepted") + } + }) + t.Run("hash failure", func(t *testing.T) { + if _, err := New(&accountFixture{}, passwordFixture{failure: context.Canceled}, time.Hour); !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + }) +} diff --git a/internal/service/cache.go b/internal/service/cache.go new file mode 100644 index 00000000..c8dc1328 --- /dev/null +++ b/internal/service/cache.go @@ -0,0 +1,17 @@ +package service + +import ( + "context" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// ProfileCache stores immutable public account profiles; misses fall back to PostgreSQL. +type ProfileCache interface { + // GetProfile returns a cached profile or a miss, including on backend failure. + GetProfile(context.Context, uuid.UUID) (dto.UserDTO, bool) + // PutProfile stores a bounded-lifetime profile on a best-effort basis. + PutProfile(context.Context, dto.UserDTO) +} diff --git a/internal/service/cursor.go b/internal/service/cursor.go new file mode 100644 index 00000000..60c634a7 --- /dev/null +++ b/internal/service/cursor.go @@ -0,0 +1,12 @@ +package service + +import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + +// CursorCodec defines the pagination operations required by application services. +type CursorCodec interface { + // Encode signs a position for the specified resource. + Encode(resource string, position cursor.Position) (string, error) + + // Decode verifies a token and returns its position; empty tokens start a page sequence. + Decode(encoded, resource string) (cursor.Position, error) +} diff --git a/internal/service/errors.go b/internal/service/errors.go new file mode 100644 index 00000000..738fdd90 --- /dev/null +++ b/internal/service/errors.go @@ -0,0 +1,23 @@ +package service + +import ( + "errors" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +var ( + // ErrUnavailable preserves the dependency failure category across service boundaries. + ErrUnavailable = store.ErrUnavailable + + // ErrInvalid indicates invalid operation input. + ErrInvalid = errors.New("invalid request") + // ErrUnauthorized indicates an unresolved current user. + ErrUnauthorized = errors.New("unknown user identity") + // ErrNotFound hides both absent and inaccessible resources. + ErrNotFound = errors.New("resource not found") + // ErrConflict indicates a duplicate username. + ErrConflict = errors.New("username already exists") + // ErrCapacity indicates exhausted storage capacity without eviction. + ErrCapacity = errors.New("in-memory storage capacity reached") +) diff --git a/internal/service/interface.go b/internal/service/interface.go new file mode 100644 index 00000000..6a1c7a0f --- /dev/null +++ b/internal/service/interface.go @@ -0,0 +1,36 @@ +// Package service defines the application operations consumed by HTTP controllers. +package service + +import ( + "context" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// Service validates raw input and enforces identity and membership requirements. +// Implementations must not expose transport-specific types or storage internals. +type Service interface { + // UsersCreate registers a user or reports invalid input, conflict or capacity exhaustion. + UsersCreate(ctx context.Context, request dto.UsersCreateRequestDTO) (dto.UserDTO, error) + + // UsersCheckIdentity verifies that an identity belongs to an existing user. + UsersCheckIdentity(ctx context.Context, userID string) error + + // UsersGetMe resolves the authenticated caller, rejecting malformed or unknown identifiers. + UsersGetMe(ctx context.Context, userID string) (dto.UserDTO, error) + + // ChatsCreate validates all members and creates one chat atomically. + ChatsCreate(ctx context.Context, request dto.ChatsCreateRequestDTO) (dto.ChatDTO, error) + + // ChatsGetByID hides missing and inaccessible chats behind the same not-found result. + ChatsGetByID(ctx context.Context, userID, chatID string) (dto.ChatDTO, error) + + // ChatsGetPage lists only chats visible to the caller, using resource-bound cursors. + ChatsGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.ChatPageDTO, error) + + // MessagesCreate derives the sender from the identity and appends validated text. + MessagesCreate(ctx context.Context, request dto.MessagesCreateRequestDTO) (dto.MessageDTO, error) + + // MessagesGetPage authorizes the caller and returns history after a verified cursor. + MessagesGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.MessagePageDTO, error) +} diff --git a/internal/service/production/access.go b/internal/service/production/access.go new file mode 100644 index 00000000..b89cd37f --- /dev/null +++ b/internal/service/production/access.go @@ -0,0 +1,62 @@ +package production + +import ( + "context" + "slices" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// parseIdentity maps malformed identity values to the authentication error. +func parseIdentity(rawID string) (uuid.UUID, error) { + id, err := parseID(rawID) + if err != nil { + return uuid.Nil, service.ErrUnauthorized + } + return id, nil +} + +// requireUserID resolves an existing identity without loading a user profile. +func (s *Service) requireUserID(ctx context.Context, rawID string) (uuid.UUID, error) { + id, err := parseIdentity(rawID) + if err != nil { + return uuid.Nil, err + } + exists, err := s.repo.UsersExist(ctx, []uuid.UUID{id}) + if err != nil { + return uuid.Nil, normalizeStoreError(err) + } + if !exists { + return uuid.Nil, service.ErrUnauthorized + } + return id, nil +} + +// requireChatMember resolves an existing caller and a chat available to that caller. +func (s *Service) requireChatMember(ctx context.Context, userID, chatID string) (uuid.UUID, dto.ChatDTO, error) { + caller, err := s.requireUserID(ctx, userID) + if err != nil { + return uuid.Nil, dto.ChatDTO{}, err + } + chat, err := s.findChat(ctx, chatID) + if err != nil { + return uuid.Nil, dto.ChatDTO{}, err + } + if !slices.Contains(chat.MemberIDs, caller) { + return uuid.Nil, dto.ChatDTO{}, service.ErrNotFound + } + return caller, chat, nil +} + +// findChat parses a chat identifier and translates storage lookup errors. +func (s *Service) findChat(ctx context.Context, rawID string) (dto.ChatDTO, error) { + id, err := parseID(rawID) + if err != nil { + return dto.ChatDTO{}, err + } + chat, err := s.repo.Chat(ctx, id) + return chat, normalizeStoreError(err) +} diff --git a/internal/service/production/cache_test.go b/internal/service/production/cache_test.go new file mode 100644 index 00000000..6733e56b --- /dev/null +++ b/internal/service/production/cache_test.go @@ -0,0 +1,84 @@ +package production + +import ( + "context" + "testing" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +type cacheFixture struct { + profile dto.UserDTO + hit bool + writes int +} + +// GetProfile returns the arranged optional-cache lookup outcome. +func (f *cacheFixture) GetProfile(context.Context, uuid.UUID) (dto.UserDTO, bool) { + return f.profile, f.hit +} + +// PutProfile records successful cache population from authoritative data. +func (f *cacheFixture) PutProfile(_ context.Context, user dto.UserDTO) { + f.profile = user + f.writes++ +} + +// TestProfileCacheHitAvoidsProfileQuery verifies that the cache has a concrete role. +func TestProfileCacheHitAvoidsProfileQuery(t *testing.T) { + codec, err := cursor.New() + if err != nil { + t.Fatal(err) + } + cache := &cacheFixture{profile: dto.UserDTO{ID: uuid.New()}, hit: true} + svc, err := NewCached(&storeStub{t: t}, codec, cache) + if err != nil { + t.Fatal(err) + } + got, err := svc.UsersGetMe(t.Context(), cache.profile.ID.String()) + if err != nil || got.ID != cache.profile.ID { + t.Fatalf("cache hit ignored: %v", err) + } +} + +// TestProfileCacheMissPopulatesAfterDatabaseRead checks the authoritative fallback. +func TestProfileCacheMissPopulatesAfterDatabaseRead(t *testing.T) { + codec, err := cursor.New() + if err != nil { + t.Fatal(err) + } + id := uuid.New() + repo := &storeStub{t: t, user: func(context.Context, uuid.UUID) (dto.UserDTO, error) { + return dto.UserDTO{ID: id}, nil + }} + cache := &cacheFixture{} + svc, err := NewCached(repo, codec, cache) + if err != nil { + t.Fatal(err) + } + got, err := svc.UsersGetMe(t.Context(), id.String()) + if err != nil || got.ID != id || cache.writes != 1 { + t.Fatalf("fallback failed: %v", err) + } +} + +// TestCachedServiceRejectsMissingDependencies checks explicit service boundaries. +func TestCachedServiceRejectsMissingDependencies(t *testing.T) { + t.Run("store", func(t *testing.T) { + if _, err := NewCached(nil, nil, &cacheFixture{}); err == nil { + t.Fatal("missing store accepted") + } + }) + t.Run("cache", func(t *testing.T) { + codec, err := cursor.New() + if err != nil { + t.Fatal(err) + } + if _, err := NewCached(&storeStub{t: t}, codec, nil); err == nil { + t.Fatal("missing cache accepted") + } + }) +} diff --git a/internal/service/production/chats.go b/internal/service/production/chats.go new file mode 100644 index 00000000..1dc601c4 --- /dev/null +++ b/internal/service/production/chats.go @@ -0,0 +1,47 @@ +package production + +import ( + "context" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// ChatsCreate resolves the caller, validates the proposed chat and persists it atomically. +func (s *Service) ChatsCreate(ctx context.Context, request dto.ChatsCreateRequestDTO) (dto.ChatDTO, error) { + caller, err := s.requireUserID(ctx, request.UserID) + if err != nil { + return dto.ChatDTO{}, err + } + chat, err := prepareChat(request, caller) + if err != nil { + return dto.ChatDTO{}, err + } + if err := s.requireExistingMembers(ctx, chat.MemberIDs); err != nil { + return dto.ChatDTO{}, err + } + created, err := s.repo.CreateChat(ctx, chat) + return created, normalizeStoreError(err) +} + +// ChatsGetByID returns a chat only to a current member, hiding its existence otherwise. +func (s *Service) ChatsGetByID(ctx context.Context, userID, chatID string) (dto.ChatDTO, error) { + _, chat, err := s.requireChatMember(ctx, userID, chatID) + return chat, err +} + +// ChatsGetPage authorizes the caller, loads a page and prepares its continuation. +func (s *Service) ChatsGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.ChatPageDTO, error) { + caller, err := s.requireUserID(ctx, request.UserID) + if err != nil { + return dto.ChatPageDTO{}, err + } + page, err := s.parsePage(request, chatListResource(caller)) + if err != nil { + return dto.ChatPageDTO{}, err + } + items, err := s.repo.Chats(ctx, caller, page.position, page.fetchLimit()) + if err != nil { + return dto.ChatPageDTO{}, normalizeStoreError(err) + } + return s.chatPage(items, page) +} diff --git a/internal/service/production/chats_page_test.go b/internal/service/production/chats_page_test.go new file mode 100644 index 00000000..06dec4c8 --- /dev/null +++ b/internal/service/production/chats_page_test.go @@ -0,0 +1,207 @@ +package production + +import ( + "context" + "errors" + "reflect" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// TestService_ChatsGetPage validates access and pagination before issuing a typed store query. +func TestService_ChatsGetPage(t *testing.T) { + t.Run("Positive: continuation uses scope, position and lookahead", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + allowIdentity(repo, actor) + + previous := cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()} + records := []dto.ChatDTO{ + {ID: uuid.New(), CreatedAt: time.Unix(1700000001, 0).UTC()}, + {ID: uuid.New(), CreatedAt: time.Unix(1700000002, 0).UTC()}, + {ID: uuid.New(), CreatedAt: time.Unix(1700000003, 0).UTC()}, + } + calls := 0 + repo.chats = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) { + calls++ + expected := dto.PositionDTO{ID: previous.ID, CreatedAt: previous.CreatedAt} + if id != actor || position != expected || limit != 3 { + t.Fatalf("wrong page query: id=%s, position=%v, limit=%d", id, position, limit) + } + return records, nil + } + svc := newStubService(t, repo) + resource := "chats:" + actor.String() + token, err := svc.cursors.Encode(resource, previous) + if err != nil { + t.Fatal(err) + } + input := dto.PageRequestDTO{UserID: actor.String(), Limit: "2", Cursor: token} + + // Act. + got, err := svc.ChatsGetPage(t.Context(), input) + + // Assert. + + if err != nil { + t.Fatal(err) + } + if calls != 1 || !reflect.DeepEqual(got.Items, records[:2]) || got.NextCursor == nil { + t.Fatalf("calls=%d, page=%+v", calls, got) + } + position, err := svc.cursors.Decode(*got.NextCursor, resource) + expected := cursor.Position{ID: records[1].ID, CreatedAt: records[1].CreatedAt} + if err != nil || position != expected { + t.Fatalf("next position=%v, want=%v, error=%v", position, expected, err) + } + + }) + + t.Run("Positive: empty history uses default limit and no continuation", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + allowIdentity(repo, actor) + + calls := 0 + repo.chats = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) { + calls++ + if id != actor || position != (dto.PositionDTO{}) || limit != 51 { + t.Fatalf("wrong initial page query: id=%s, position=%v, limit=%d", id, position, limit) + } + return []dto.ChatDTO{}, nil + } + svc := newStubService(t, repo) + input := dto.PageRequestDTO{UserID: actor.String()} + + // Act. + got, err := svc.ChatsGetPage(t.Context(), input) + + // Assert. + if err != nil { + t.Fatal(err) + } + if calls != 1 || got.Items == nil || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("calls=%d, page=%+v", calls, got) + } + }) + + t.Run("Negative: cursor for another resource skips page lookup", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + allowIdentity(repo, actor) + + svc := newStubService(t, repo) + token, err := svc.cursors.Encode("another-resource", cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}) + if err != nil { + t.Fatal(err) + } + input := dto.PageRequestDTO{UserID: actor.String(), Cursor: token} + + // Act. + got, err := svc.ChatsGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: codec failure skips page lookup", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + allowIdentity(repo, actor) + + failure := errors.New("cursor unavailable") + svc := newStubService(t, repo) + svc.cursors = failingCursor{failure: failure} + input := dto.PageRequestDTO{UserID: actor.String(), Cursor: "token"} + + // Act. + got, err := svc.ChatsGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: page storage fails", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + allowIdentity(repo, actor) + + failure := errors.New("page unavailable") + repo.chats = func(_ context.Context, _ uuid.UUID, _ dto.PositionDTO, _ int) ([]dto.ChatDTO, error) { + return nil, failure + } + svc := newStubService(t, repo) + input := dto.PageRequestDTO{UserID: actor.String()} + + // Act. + got, err := svc.ChatsGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: malformed identity skips all storage", func(t *testing.T) { + // Arrange. + svc := newStubService(t, newStoreStub(t)) + input := dto.PageRequestDTO{UserID: "invalid", ChatID: uuid.NewString()} + + // Act. + got, err := svc.ChatsGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrUnauthorized) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) +} + +// TestService_ChatsGetPage_InvalidLimit rejects invalid limits before reading stored pages. +func TestService_ChatsGetPage_InvalidLimit(t *testing.T) { + cases := []struct { + name string + limit string + }{ + {"Negative: zero limit", "0"}, + {"Negative: negative limit", "-1"}, + {"Negative: limit above maximum", "101"}, + {"Negative: nonnumeric limit", "text"}, + {"Negative: fractional limit", "1.5"}, + {"Negative: integer overflow", "99999999999999999999999999"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + allowIdentity(repo, actor) + + svc := newStubService(t, repo) + input := dto.PageRequestDTO{UserID: actor.String(), Limit: tc.limit} + + // Act. + got, err := svc.ChatsGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + } +} diff --git a/internal/service/production/chats_test.go b/internal/service/production/chats_test.go new file mode 100644 index 00000000..11210136 --- /dev/null +++ b/internal/service/production/chats_test.go @@ -0,0 +1,261 @@ +package production + +import ( + "context" + "errors" + "reflect" + "slices" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// TestService_ChatsCreate checks membership in one batch and persists only validated chats. +func TestService_ChatsCreate(t *testing.T) { + t.Run("Positive: one membership query and original chat fields", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor, other := uuid.New(), uuid.New() + var queries [][]uuid.UUID + repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) { + queries = append(queries, slices.Clone(ids)) + return true, nil + } + var persisted dto.ChatDTO + repo.createChat = func(_ context.Context, input dto.ChatDTO) (dto.ChatDTO, error) { + persisted = input + input.CreatedAt = time.Unix(1700000000, 0).UTC() + return input, nil + } + svc := newStubService(t, repo) + input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: " Team 👋 ", MemberIDs: []string{actor.String(), other.String()}} + + // Act. + got, err := svc.ChatsCreate(t.Context(), input) + + // Assert. + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(queries, [][]uuid.UUID{{actor}, {actor, other}}) { + t.Fatalf("existence queries=%v", queries) + } + if persisted.ID == uuid.Nil || persisted.Title != input.Title || !slices.Equal(persisted.MemberIDs, []uuid.UUID{actor, other}) { + t.Fatalf("wrong persistence input: %+v", persisted) + } + if got.ID != persisted.ID || got.CreatedAt.IsZero() || got.Title != input.Title || !slices.Equal(got.MemberIDs, persisted.MemberIDs) { + t.Fatalf("wrong returned chat: %+v", got) + } + }) + + t.Run("Negative: unknown member prevents persistence", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor, missing := uuid.New(), uuid.New() + repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) { + return !slices.Contains(ids, missing), nil + } + svc := newStubService(t, repo) + input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String(), missing.String()}} + + // Act. + got, err := svc.ChatsCreate(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: membership lookup failure prevents persistence", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor, other := uuid.New(), uuid.New() + failure := errors.New("membership unavailable") + repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) { + if len(ids) == 1 { + return true, nil + } + return false, failure + } + svc := newStubService(t, repo) + input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String(), other.String()}} + + // Act. + got, err := svc.ChatsCreate(t.Context(), input) + + // Assert. + if !errors.Is(err, failure) || !reflect.DeepEqual(got, dto.ChatDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: unknown creator prevents membership and persistence calls", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + repo.usersExist = func(_ context.Context, _ []uuid.UUID) (bool, error) { + return false, nil + } + svc := newStubService(t, repo) + actor := uuid.New() + input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String()}} + + // Act. + got, err := svc.ChatsCreate(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.ChatDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) +} + +// TestService_ChatsCreate_InvalidInput rejects malformed chat fields before checking member existence. +func TestService_ChatsCreate_InvalidInput(t *testing.T) { + actor := uuid.New() + cases := []struct { + name string + title string + members []string + }{ + {"Negative: empty member set", "Team", nil}, + {"Negative: duplicate member", "Team", []string{actor.String(), actor.String()}}, + {"Negative: caller omitted", "Team", []string{uuid.NewString()}}, + {"Negative: malformed member ID", "Team", []string{actor.String(), "invalid"}}, + {"Negative: blank title", " ", []string{actor.String()}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + calls := 0 + repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) { + calls++ + if calls != 1 || !slices.Equal(ids, []uuid.UUID{actor}) { + t.Fatalf("unexpected membership check: %v", ids) + } + return true, nil + } + svc := newStubService(t, repo) + input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: tc.title, MemberIDs: tc.members} + + // Act. + got, err := svc.ChatsCreate(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + if calls != 1 { + t.Fatalf("identity checks=%d, want=1", calls) + } + }) + } +} + +// TestService_ChatsGetByID authorizes the requested chat and conceals inaccessible records. +func TestService_ChatsGetByID(t *testing.T) { + t.Run("Positive: member receives the complete chat", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + expected := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{actor}, CreatedAt: time.Unix(1700000000, 0).UTC()} + allowChatAccess(repo, actor, expected) + svc := newStubService(t, repo) + + // Act. + got, err := svc.ChatsGetByID(t.Context(), actor.String(), expected.ID.String()) + + // Assert. + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, expected) { + t.Fatalf("chat=%+v, want=%+v", got, expected) + } + }) + + t.Run("Negative: outsider receives no chat details", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), Title: "Private", MemberIDs: []uuid.UUID{uuid.New()}} + allowChatAccess(repo, actor, chat) + svc := newStubService(t, repo) + + // Act. + got, err := svc.ChatsGetByID(t.Context(), actor.String(), chat.ID.String()) + + // Assert. + if !errors.Is(err, service.ErrNotFound) || !reflect.DeepEqual(got, dto.ChatDTO{}) { + t.Fatalf("private chat exposed: %+v, error=%v", got, err) + } + }) + + t.Run("Negative: malformed chat ID skips chat lookup", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + allowIdentity(repo, actor) + svc := newStubService(t, repo) + + // Act. + got, err := svc.ChatsGetByID(t.Context(), actor.String(), "invalid") + + // Assert. + if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: malformed identity skips storage", func(t *testing.T) { + // Arrange. + svc := newStubService(t, newStoreStub(t)) + + // Act. + got, err := svc.ChatsGetByID(t.Context(), "invalid", uuid.NewString()) + + // Assert. + if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.ChatDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) +} + +// TestService_ChatsGetByID_StoreErrors translates missing records and retains unexpected failures. +func TestService_ChatsGetByID_StoreErrors(t *testing.T) { + failure := errors.New("chat lookup unavailable") + cases := []struct { + name string + cause error + want error + }{ + {"Negative: absent chat", store.ErrNotFound, service.ErrNotFound}, + {"Negative: storage unavailable", failure, failure}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + allowIdentity(repo, actor) + repo.chat = func(_ context.Context, _ uuid.UUID) (dto.ChatDTO, error) { + return dto.ChatDTO{}, tc.cause + } + svc := newStubService(t, repo) + + // Act. + got, err := svc.ChatsGetByID(t.Context(), actor.String(), uuid.NewString()) + + // Assert. + if !errors.Is(err, tc.want) || !reflect.DeepEqual(got, dto.ChatDTO{}) { + t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want) + } + }) + } +} diff --git a/internal/service/production/creation.go b/internal/service/production/creation.go new file mode 100644 index 00000000..80bdc387 --- /dev/null +++ b/internal/service/production/creation.go @@ -0,0 +1,49 @@ +package production + +import ( + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// PrepareUser validates registration fields and assigns the new user identifier. +func PrepareUser(request dto.UsersCreateRequestDTO) (dto.UserDTO, error) { + if !validUsername(request.Username) || !validText(request.DisplayName, maxDisplayNameRunes) { + return dto.UserDTO{}, service.ErrInvalid + } + return dto.UserDTO{ + ID: uuid.New(), + Username: request.Username, + DisplayName: request.DisplayName, + }, nil +} + +// prepareChat validates the title and member identifiers before storage access. +func prepareChat(request dto.ChatsCreateRequestDTO, caller uuid.UUID) (dto.ChatDTO, error) { + if !validText(request.Title, maxChatTitleRunes) { + return dto.ChatDTO{}, service.ErrInvalid + } + members, err := parseMembers(request.MemberIDs, caller) + if err != nil { + return dto.ChatDTO{}, err + } + return dto.ChatDTO{ + ID: uuid.New(), + Title: request.Title, + MemberIDs: members, + }, nil +} + +// prepareMessage validates text and creates a record for the authorized sender and chat. +func prepareMessage(request dto.MessagesCreateRequestDTO, sender, chatID uuid.UUID) (dto.MessageDTO, error) { + if !validText(request.Text, maxMessageRunes) { + return dto.MessageDTO{}, service.ErrInvalid + } + return dto.MessageDTO{ + ID: uuid.New(), + ChatID: chatID, + SenderID: sender, + Text: request.Text, + }, nil +} diff --git a/internal/service/production/errors.go b/internal/service/production/errors.go new file mode 100644 index 00000000..0a59fa72 --- /dev/null +++ b/internal/service/production/errors.go @@ -0,0 +1,23 @@ +package production + +import ( + "errors" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// normalizeStoreError maps expected storage failures to application errors. +// Unexpected failures retain their cause for the transport's safe fallback. +func normalizeStoreError(err error) error { + switch { + case errors.Is(err, store.ErrNotFound): + return service.ErrNotFound + case errors.Is(err, store.ErrConflict): + return service.ErrConflict + case errors.Is(err, store.ErrCapacity): + return service.ErrCapacity + default: + return err + } +} diff --git a/internal/service/production/fixture_test.go b/internal/service/production/fixture_test.go new file mode 100644 index 00000000..6740da4d --- /dev/null +++ b/internal/service/production/fixture_test.go @@ -0,0 +1,147 @@ +package production + +import ( + "context" + "testing" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// storeStub permits only the interactions explicitly arranged by each service scenario. +type storeStub struct { + t *testing.T + createUser func(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) + user func(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) + usersExist func(ctx context.Context, ids []uuid.UUID) (bool, error) + createChat func(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) + chat func(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) + chats func(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) + createMessage func(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) + messages func(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) +} + +// CreateUser delegates to the arranged behavior and rejects unexpected storage access. +func (repo *storeStub) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) { + repo.t.Helper() + if repo.createUser == nil { + repo.t.Fatalf("unexpected store.CreateUser call") + return dto.UserDTO{}, nil + } + return repo.createUser(ctx, user) +} + +// User delegates to the arranged behavior and rejects unexpected storage access. +func (repo *storeStub) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) { + repo.t.Helper() + if repo.user == nil { + repo.t.Fatalf("unexpected store.User call") + return dto.UserDTO{}, nil + } + return repo.user(ctx, id) +} + +// UsersExist delegates to the arranged behavior and rejects unexpected storage access. +func (repo *storeStub) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) { + repo.t.Helper() + if repo.usersExist == nil { + repo.t.Fatalf("unexpected store.UsersExist call") + return false, nil + } + return repo.usersExist(ctx, ids) +} + +// CreateChat delegates to the arranged behavior and rejects unexpected storage access. +func (repo *storeStub) CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) { + repo.t.Helper() + if repo.createChat == nil { + repo.t.Fatalf("unexpected store.CreateChat call") + return dto.ChatDTO{}, nil + } + return repo.createChat(ctx, chat) +} + +// Chat delegates to the arranged behavior and rejects unexpected storage access. +func (repo *storeStub) Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) { + repo.t.Helper() + if repo.chat == nil { + repo.t.Fatalf("unexpected store.Chat call") + return dto.ChatDTO{}, nil + } + return repo.chat(ctx, id) +} + +// Chats delegates to the arranged behavior and rejects unexpected storage access. +func (repo *storeStub) Chats(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) { + repo.t.Helper() + if repo.chats == nil { + repo.t.Fatalf("unexpected store.Chats call") + return nil, nil + } + return repo.chats(ctx, id, position, limit) +} + +// CreateMessage delegates to the arranged behavior and rejects unexpected storage access. +func (repo *storeStub) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) { + repo.t.Helper() + if repo.createMessage == nil { + repo.t.Fatalf("unexpected store.CreateMessage call") + return dto.MessageDTO{}, nil + } + return repo.createMessage(ctx, message) +} + +// Messages delegates to the arranged behavior and rejects unexpected storage access. +func (repo *storeStub) Messages(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) { + repo.t.Helper() + if repo.messages == nil { + repo.t.Fatalf("unexpected store.Messages call") + return nil, nil + } + return repo.messages(ctx, id, position, limit) +} + +// newStoreStub creates a repository that fails on every unarranged interaction. +func newStoreStub(t *testing.T) *storeStub { + t.Helper() + return &storeStub{t: t} +} + +// newStubService composes the service with controlled storage and a real cursor codec. +func newStubService(t *testing.T, repo *storeStub) *Service { + t.Helper() + codec, err := cursor.New() + if err != nil { + t.Fatal(err) + } + svc, err := New(repo, codec) + if err != nil { + t.Fatal(err) + } + return svc +} + +// allowIdentity permits exactly the arranged actor's existence lookup, never a profile read. +func allowIdentity(repo *storeStub, actor uuid.UUID) { + repo.t.Helper() + repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) { + if len(ids) != 1 || ids[0] != actor { + repo.t.Fatalf("unexpected identity query: %v", ids) + } + return true, nil + } +} + +// allowChatAccess supplies a typed chat after checking the lookup key at the service boundary. +func allowChatAccess(repo *storeStub, actor uuid.UUID, chat dto.ChatDTO) { + repo.t.Helper() + allowIdentity(repo, actor) + repo.chat = func(_ context.Context, id uuid.UUID) (dto.ChatDTO, error) { + if id != chat.ID { + repo.t.Fatalf("chat queried for %s, want %s", id, chat.ID) + } + return chat, nil + } +} diff --git a/internal/service/production/members.go b/internal/service/production/members.go new file mode 100644 index 00000000..35d1eaa7 --- /dev/null +++ b/internal/service/production/members.go @@ -0,0 +1,42 @@ +package production + +import ( + "context" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// parseMembers validates unique member identifiers and requires the caller to be included. +func parseMembers(rawIDs []string, caller uuid.UUID) ([]uuid.UUID, error) { + if len(rawIDs) == 0 || len(rawIDs) > maxChatMembers { + return nil, service.ErrInvalid + } + members := make([]uuid.UUID, 0, len(rawIDs)) + seen := make(map[uuid.UUID]bool, len(rawIDs)) + for _, rawID := range rawIDs { + id, err := parseID(rawID) + if err != nil || seen[id] { + return nil, service.ErrInvalid + } + seen[id] = true + members = append(members, id) + } + if !seen[caller] { + return nil, service.ErrInvalid + } + return members, nil +} + +// requireExistingMembers validates the complete membership set with one storage operation. +func (s *Service) requireExistingMembers(ctx context.Context, members []uuid.UUID) error { + exists, err := s.repo.UsersExist(ctx, members) + if err != nil { + return normalizeStoreError(err) + } + if !exists { + return service.ErrInvalid + } + return nil +} diff --git a/internal/service/production/messages.go b/internal/service/production/messages.go new file mode 100644 index 00000000..4797631c --- /dev/null +++ b/internal/service/production/messages.go @@ -0,0 +1,38 @@ +package production + +import ( + "context" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// MessagesCreate authorizes the sender, validates the message and stores it atomically. +func (s *Service) MessagesCreate(ctx context.Context, request dto.MessagesCreateRequestDTO) (dto.MessageDTO, error) { + caller, chat, err := s.requireChatMember(ctx, request.UserID, request.ChatID) + if err != nil { + return dto.MessageDTO{}, err + } + message, err := prepareMessage(request, caller, chat.ID) + if err != nil { + return dto.MessageDTO{}, err + } + created, err := s.repo.CreateMessage(ctx, message) + return created, normalizeStoreError(err) +} + +// MessagesGetPage authorizes access, loads history and prepares its continuation. +func (s *Service) MessagesGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.MessagePageDTO, error) { + _, chat, err := s.requireChatMember(ctx, request.UserID, request.ChatID) + if err != nil { + return dto.MessagePageDTO{}, err + } + page, err := s.parsePage(request, messageHistoryResource(chat.ID)) + if err != nil { + return dto.MessagePageDTO{}, err + } + items, err := s.repo.Messages(ctx, chat.ID, page.position, page.fetchLimit()) + if err != nil { + return dto.MessagePageDTO{}, normalizeStoreError(err) + } + return s.messagePage(items, page) +} diff --git a/internal/service/production/messages_page_test.go b/internal/service/production/messages_page_test.go new file mode 100644 index 00000000..83d3fd32 --- /dev/null +++ b/internal/service/production/messages_page_test.go @@ -0,0 +1,231 @@ +package production + +import ( + "context" + "errors" + "reflect" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// TestService_MessagesGetPage validates access and pagination before issuing a typed store query. +func TestService_MessagesGetPage(t *testing.T) { + t.Run("Positive: continuation uses scope, position and lookahead", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + + previous := cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()} + records := []dto.MessageDTO{ + {ID: uuid.New(), CreatedAt: time.Unix(1700000001, 0).UTC()}, + {ID: uuid.New(), CreatedAt: time.Unix(1700000002, 0).UTC()}, + {ID: uuid.New(), CreatedAt: time.Unix(1700000003, 0).UTC()}, + } + calls := 0 + repo.messages = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) { + calls++ + expected := dto.PositionDTO{ID: previous.ID, CreatedAt: previous.CreatedAt} + if id != chat.ID || position != expected || limit != 3 { + t.Fatalf("wrong page query: id=%s, position=%v, limit=%d", id, position, limit) + } + return records, nil + } + svc := newStubService(t, repo) + resource := "messages:" + chat.ID.String() + token, err := svc.cursors.Encode(resource, previous) + if err != nil { + t.Fatal(err) + } + input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Limit: "2", Cursor: token} + + // Act. + got, err := svc.MessagesGetPage(t.Context(), input) + + // Assert. + + if err != nil { + t.Fatal(err) + } + if calls != 1 || !reflect.DeepEqual(got.Items, records[:2]) || got.NextCursor == nil { + t.Fatalf("calls=%d, page=%+v", calls, got) + } + position, err := svc.cursors.Decode(*got.NextCursor, resource) + expected := cursor.Position{ID: records[1].ID, CreatedAt: records[1].CreatedAt} + if err != nil || position != expected { + t.Fatalf("next position=%v, want=%v, error=%v", position, expected, err) + } + + }) + + t.Run("Positive: empty history uses default limit and no continuation", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + + calls := 0 + repo.messages = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) { + calls++ + if id != chat.ID || position != (dto.PositionDTO{}) || limit != 51 { + t.Fatalf("wrong initial page query: id=%s, position=%v, limit=%d", id, position, limit) + } + return []dto.MessageDTO{}, nil + } + svc := newStubService(t, repo) + input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()} + + // Act. + got, err := svc.MessagesGetPage(t.Context(), input) + + // Assert. + if err != nil { + t.Fatal(err) + } + if calls != 1 || got.Items == nil || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("calls=%d, page=%+v", calls, got) + } + }) + + t.Run("Negative: cursor for another resource skips page lookup", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + + svc := newStubService(t, repo) + token, err := svc.cursors.Encode("another-resource", cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}) + if err != nil { + t.Fatal(err) + } + input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Cursor: token} + + // Act. + got, err := svc.MessagesGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: codec failure skips page lookup", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + + failure := errors.New("cursor unavailable") + svc := newStubService(t, repo) + svc.cursors = failingCursor{failure: failure} + input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Cursor: "token"} + + // Act. + got, err := svc.MessagesGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: page storage fails", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + + failure := errors.New("page unavailable") + repo.messages = func(_ context.Context, _ uuid.UUID, _ dto.PositionDTO, _ int) ([]dto.MessageDTO, error) { + return nil, failure + } + svc := newStubService(t, repo) + input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()} + + // Act. + got, err := svc.MessagesGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: malformed identity skips all storage", func(t *testing.T) { + // Arrange. + svc := newStubService(t, newStoreStub(t)) + input := dto.PageRequestDTO{UserID: "invalid", ChatID: uuid.NewString()} + + // Act. + got, err := svc.MessagesGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrUnauthorized) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: outsider cannot read message history", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}} + allowChatAccess(repo, actor, chat) + svc := newStubService(t, repo) + input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()} + + // Act. + got, err := svc.MessagesGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrNotFound) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) +} + +// TestService_MessagesGetPage_InvalidLimit rejects invalid limits before reading stored pages. +func TestService_MessagesGetPage_InvalidLimit(t *testing.T) { + cases := []struct { + name string + limit string + }{ + {"Negative: zero limit", "0"}, + {"Negative: negative limit", "-1"}, + {"Negative: limit above maximum", "101"}, + {"Negative: nonnumeric limit", "text"}, + {"Negative: fractional limit", "1.5"}, + {"Negative: integer overflow", "99999999999999999999999999"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + + svc := newStubService(t, repo) + input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Limit: tc.limit} + + // Act. + got, err := svc.MessagesGetPage(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil { + t.Fatalf("page=%+v, error=%v", got, err) + } + }) + } +} diff --git a/internal/service/production/messages_test.go b/internal/service/production/messages_test.go new file mode 100644 index 00000000..f42c94b8 --- /dev/null +++ b/internal/service/production/messages_test.go @@ -0,0 +1,147 @@ +package production + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// TestService_MessagesCreate authorizes the sender before validating and persisting the message. +func TestService_MessagesCreate(t *testing.T) { + t.Run("Positive: authenticated sender and original text persisted", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + var persisted dto.MessageDTO + repo.createMessage = func(_ context.Context, input dto.MessageDTO) (dto.MessageDTO, error) { + persisted = input + input.CreatedAt = time.Unix(1700000000, 0).UTC() + return input, nil + } + svc := newStubService(t, repo) + input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: " Original 👋 "} + + // Act. + got, err := svc.MessagesCreate(t.Context(), input) + + // Assert. + if err != nil { + t.Fatal(err) + } + if persisted.ID == uuid.Nil || persisted.SenderID != actor || persisted.ChatID != chat.ID || persisted.Text != input.Text { + t.Fatalf("wrong persistence input: %+v", persisted) + } + if got.ID != persisted.ID || got.SenderID != actor || got.ChatID != chat.ID || got.Text != input.Text || got.CreatedAt.IsZero() { + t.Fatalf("wrong acknowledgement: %+v", got) + } + }) + + t.Run("Negative: outsider cannot persist messages", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}} + allowChatAccess(repo, actor, chat) + svc := newStubService(t, repo) + input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"} + + // Act. + got, err := svc.MessagesCreate(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrNotFound) || got != (dto.MessageDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) + + t.Run("Negative: malformed identity skips storage", func(t *testing.T) { + // Arrange. + svc := newStubService(t, newStoreStub(t)) + input := dto.MessagesCreateRequestDTO{UserID: "invalid", ChatID: uuid.NewString(), Text: "text"} + + // Act. + got, err := svc.MessagesCreate(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrUnauthorized) || got != (dto.MessageDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) +} + +// TestService_MessagesCreate_InvalidText refuses invalid text without attempting persistence. +func TestService_MessagesCreate_InvalidText(t *testing.T) { + cases := []struct { + name string + text string + }{ + {"Negative: empty text", ""}, + {"Negative: whitespace only", " \t"}, + {"Negative: rune limit exceeded", strings.Repeat("界", 4001)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + svc := newStubService(t, repo) + input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: tc.text} + + // Act. + got, err := svc.MessagesCreate(t.Context(), input) + + // Assert. + if !errors.Is(err, service.ErrInvalid) || got != (dto.MessageDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) + } +} + +// TestService_MessagesCreate_StoreErrors propagates persistence failures without acknowledging a record. +func TestService_MessagesCreate_StoreErrors(t *testing.T) { + failure := errors.New("write unavailable") + cases := []struct { + name string + cause error + want error + }{ + {"Negative: capacity exhausted", store.ErrCapacity, service.ErrCapacity}, + {"Negative: chat disappeared", store.ErrNotFound, service.ErrNotFound}, + {"Negative: unexpected write failure", failure, failure}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + actor := uuid.New() + chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}} + allowChatAccess(repo, actor, chat) + repo.createMessage = func(_ context.Context, _ dto.MessageDTO) (dto.MessageDTO, error) { + return dto.MessageDTO{}, tc.cause + } + svc := newStubService(t, repo) + input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"} + + // Act. + got, err := svc.MessagesCreate(t.Context(), input) + + // Assert. + if !errors.Is(err, tc.want) || got != (dto.MessageDTO{}) { + t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want) + } + }) + } +} diff --git a/internal/service/production/pages.go b/internal/service/production/pages.go new file mode 100644 index 00000000..9b3497de --- /dev/null +++ b/internal/service/production/pages.go @@ -0,0 +1,49 @@ +package production + +import ( + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// chatPage adapts the shared page result to the chat response DTO. +func (s *Service) chatPage(items []dto.ChatDTO, page pagination) (dto.ChatPageDTO, error) { + items, next, err := buildPage(items, page, s.cursors, chatPosition) + if err != nil { + return dto.ChatPageDTO{}, err + } + return dto.ChatPageDTO{Items: items, NextCursor: next}, nil +} + +// messagePage adapts the shared page result to the message response DTO. +func (s *Service) messagePage(items []dto.MessageDTO, page pagination) (dto.MessagePageDTO, error) { + items, next, err := buildPage(items, page, s.cursors, messagePosition) + if err != nil { + return dto.MessagePageDTO{}, err + } + return dto.MessagePageDTO{Items: items, NextCursor: next}, nil +} + +// buildPage trims lookahead and signs the last returned record when more data exists. +// The page limit must be validated before calling this helper. +func buildPage[T any](items []T, page pagination, codec service.CursorCodec, position func(T) cursor.Position) ([]T, *string, error) { + if len(items) <= page.limit { + return items, nil, nil + } + items = items[:page.limit] + next, err := codec.Encode(page.resource, position(items[len(items)-1])) + if err != nil { + return nil, nil, err + } + return items, new(next), nil +} + +// chatPosition extracts the stable pagination boundary from a stored chat. +func chatPosition(chat dto.ChatDTO) cursor.Position { + return cursor.Position{CreatedAt: chat.CreatedAt, ID: chat.ID} +} + +// messagePosition extracts the stable pagination boundary from a stored message. +func messagePosition(message dto.MessageDTO) cursor.Position { + return cursor.Position{CreatedAt: message.CreatedAt, ID: message.ID} +} diff --git a/internal/service/production/pages_test.go b/internal/service/production/pages_test.go new file mode 100644 index 00000000..cca603b8 --- /dev/null +++ b/internal/service/production/pages_test.go @@ -0,0 +1,53 @@ +package production + +import ( + "reflect" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// TestService_messagePage checks boundaries and signs the last returned item, not lookahead. +func TestService_messagePage(t *testing.T) { + for _, count := range []int{0, 2, 3} { + names := map[int]string{0: "Positive: empty page", 2: "Positive: exact limit is final", 3: "Positive: lookahead creates continuation"} + t.Run(names[count], func(t *testing.T) { + // Arrange. + svc := newStubService(t, newStoreStub(t)) + items := make([]dto.MessageDTO, count) + for i := range items { + items[i] = dto.MessageDTO{ID: uuid.New(), Text: "message", CreatedAt: time.Unix(int64(i+1), 0).UTC()} + } + expected := items[:min(count, 2)] + + // Act. + page, err := svc.messagePage(items, pagination{limit: 2, resource: "messages:chat"}) + + // Assert. + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(page.Items, expected) { + t.Fatalf("page=%v, want=%v", page.Items, expected) + } + if count <= 2 { + if page.NextCursor != nil { + t.Fatal("final page has a continuation") + } + return + } + if page.NextCursor == nil { + t.Fatal("lookahead did not produce continuation") + } + decoded, err := svc.cursors.Decode(*page.NextCursor, "messages:chat") + want := cursor.Position{ID: items[1].ID, CreatedAt: items[1].CreatedAt} + if err != nil || decoded != want { + t.Fatalf("cursor=%v, want=%v, error=%v", decoded, want, err) + } + }) + } +} diff --git a/internal/service/production/pagination.go b/internal/service/production/pagination.go new file mode 100644 index 00000000..2c3d2c78 --- /dev/null +++ b/internal/service/production/pagination.go @@ -0,0 +1,78 @@ +package production + +import ( + "errors" + "strconv" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +const ( + defaultPageLimit = 50 + maxPageLimit = 100 + // Fetching one extra record determines whether to issue a next cursor. + pageLookahead = 1 +) + +type pagination struct { + position dto.PositionDTO + limit int + resource string +} + +// parsePage validates the page size and resource-bound cursor. +func (s *Service) parsePage(request dto.PageRequestDTO, resource string) (pagination, error) { + limit, err := parseLimit(request.Limit) + if err != nil { + return pagination{}, err + } + position, err := s.cursors.Decode(request.Cursor, resource) + if errors.Is(err, cursor.ErrInvalid) { + return pagination{}, service.ErrInvalid + } + if err != nil { + return pagination{}, err + } + return pagination{ + position: dto.PositionDTO{CreatedAt: position.CreatedAt, ID: position.ID}, + limit: limit, + resource: resource, + }, nil +} + +// parseLimit parses a bounded page size or supplies the default. +func parseLimit(raw string) (int, error) { + if raw == "" { + return defaultPageLimit, nil + } + for _, char := range raw { + if char < '0' || char > '9' { + return 0, service.ErrInvalid + } + } + limit, err := strconv.Atoi(raw) + if err != nil || limit < 1 || limit > maxPageLimit { + return 0, service.ErrInvalid + } + return limit, nil +} + +// fetchLimit includes one lookahead record to detect a following page. +func (page pagination) fetchLimit() int { + return page.limit + pageLookahead +} + +// chatListResource scopes a cursor to one user's visible chats. +func chatListResource(userID uuid.UUID) string { + return "chats:" + userID.String() +} + +// messageHistoryResource scopes a cursor to one chat's message history. +func messageHistoryResource(chatID uuid.UUID) string { + return "messages:" + chatID.String() +} diff --git a/internal/service/production/pagination_test.go b/internal/service/production/pagination_test.go new file mode 100644 index 00000000..89833e4c --- /dev/null +++ b/internal/service/production/pagination_test.go @@ -0,0 +1,74 @@ +package production + +import ( + "errors" + "testing" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +type failingCursor struct { + failure error +} + +// Encode injects a signing failure at the service dependency boundary. +func (codec failingCursor) Encode(_ string, _ cursor.Position) (string, error) { + return "", codec.failure +} + +// Decode injects a verification failure at the service dependency boundary. +func (codec failingCursor) Decode(_, _ string) (cursor.Position, error) { + return cursor.Position{}, codec.failure +} + +// TestService_parsePage translates invalid tokens while retaining unexpected dependency failures. +func TestService_parsePage(t *testing.T) { + failure := errors.New("codec unavailable") + cases := []struct { + name string + cause error + want error + }{ + {"Negative: invalid token", cursor.ErrInvalid, service.ErrInvalid}, + {"Negative: unavailable codec", failure, failure}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + svc := &Service{cursors: failingCursor{failure: tc.cause}} + input := dto.PageRequestDTO{Cursor: "supplied-token"} + + // Act. + page, err := svc.parsePage(input, "messages:chat") + + // Assert. + if !errors.Is(err, tc.want) { + t.Fatalf("error=%v, want=%v", err, tc.want) + } + if page != (pagination{}) { + t.Fatalf("failed cursor produced a page: %+v", page) + } + }) + } +} + +// TestService_messagePage_EncodeFailure returns no partial page when signing fails. +func TestService_messagePage_EncodeFailure(t *testing.T) { + // Arrange. + failure := errors.New("signing unavailable") + svc := &Service{cursors: failingCursor{failure: failure}} + items := []dto.MessageDTO{{Text: "first"}, {Text: "lookahead"}} + + // Act. + page, err := svc.messagePage(items, pagination{limit: 1, resource: "messages:chat"}) + + // Assert. + if !errors.Is(err, failure) { + t.Fatalf("lost signing failure: %v", err) + } + if page.Items != nil || page.NextCursor != nil { + t.Fatalf("partial page escaped: %+v", page) + } +} diff --git a/internal/service/production/service.go b/internal/service/production/service.go new file mode 100644 index 00000000..11b53fcb --- /dev/null +++ b/internal/service/production/service.go @@ -0,0 +1,39 @@ +// Package production implements the messenger application operations. +package production + +import ( + "fmt" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// Service orchestrates operations through storage and cursor interfaces. +type Service struct { + repo store.Interface + cursors service.CursorCodec + cache service.ProfileCache +} + +var _ service.Service = (*Service)(nil) + +// New creates an application service using explicitly supplied dependencies. +func New(repo store.Interface, cursors service.CursorCodec) (*Service, error) { + if repo == nil || cursors == nil { + return nil, fmt.Errorf("store and cursor codec are required") + } + return &Service{repo: repo, cursors: cursors}, nil +} + +// NewCached builds the business service with optional immutable-profile caching. +func NewCached(repo store.Interface, cursors service.CursorCodec, cache service.ProfileCache) (*Service, error) { + instance, err := New(repo, cursors) + if err != nil { + return nil, err + } + if cache == nil { + return nil, fmt.Errorf("profile cache is required") + } + instance.cache = cache + return instance, nil +} diff --git a/internal/service/production/service_test.go b/internal/service/production/service_test.go new file mode 100644 index 00000000..1b4f3291 --- /dev/null +++ b/internal/service/production/service_test.go @@ -0,0 +1,39 @@ +package production + +import ( + "testing" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/cursor" +) + +// TestService_New rejects each missing dependency separately. +func TestService_New(t *testing.T) { + t.Run("Negative: missing store", func(t *testing.T) { + // Arrange. + codec, err := cursor.New() + if err != nil { + t.Fatal(err) + } + + // Act. + svc, err := New(nil, codec) + + // Assert. + if err == nil || svc != nil { + t.Fatalf("service=%v, error=%v", svc, err) + } + }) + + t.Run("Negative: missing codec", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + + // Act. + svc, err := New(repo, nil) + + // Assert. + if err == nil || svc != nil { + t.Fatalf("service=%v, error=%v", svc, err) + } + }) +} diff --git a/internal/service/production/users.go b/internal/service/production/users.go new file mode 100644 index 00000000..083111c3 --- /dev/null +++ b/internal/service/production/users.go @@ -0,0 +1,47 @@ +package production + +import ( + "context" + "errors" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// UsersCreate validates registration and atomically reserves the unique username. +func (s *Service) UsersCreate(ctx context.Context, request dto.UsersCreateRequestDTO) (dto.UserDTO, error) { + user, err := PrepareUser(request) + if err != nil { + return dto.UserDTO{}, err + } + created, err := s.repo.CreateUser(ctx, user) + return created, normalizeStoreError(err) +} + +// UsersGetMe loads the current user's profile; malformed and missing identities are unauthorized. +func (s *Service) UsersGetMe(ctx context.Context, rawID string) (dto.UserDTO, error) { + id, err := parseIdentity(rawID) + if err != nil { + return dto.UserDTO{}, err + } + if s.cache != nil { + if cached, ok := s.cache.GetProfile(ctx, id); ok { + return cached, nil + } + } + user, err := s.repo.User(ctx, id) + if errors.Is(err, store.ErrNotFound) { + return dto.UserDTO{}, service.ErrUnauthorized + } + if err == nil && s.cache != nil { + s.cache.PutProfile(ctx, user) + } + return user, normalizeStoreError(err) +} + +// UsersCheckIdentity validates the current identity without loading its profile. +func (s *Service) UsersCheckIdentity(ctx context.Context, rawID string) error { + _, err := s.requireUserID(ctx, rawID) + return err +} diff --git a/internal/service/production/users_test.go b/internal/service/production/users_test.go new file mode 100644 index 00000000..667aebc2 --- /dev/null +++ b/internal/service/production/users_test.go @@ -0,0 +1,289 @@ +package production + +import ( + "context" + "errors" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// TestService_UsersCreate validates registration before persistence and preserves storage failures. +func TestService_UsersCreate(t *testing.T) { + t.Run("Positive: validates and persists the original profile", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + expected := dto.UserDTO{Username: "alice", DisplayName: "Алиса 👋", CreatedAt: time.Unix(1700000000, 0).UTC()} + calls := 0 + repo.createUser = func(_ context.Context, input dto.UserDTO) (dto.UserDTO, error) { + calls++ + if input.ID == uuid.Nil || input.Username != expected.Username || input.DisplayName != expected.DisplayName { + t.Fatalf("wrong persistence input: %+v", input) + } + expected.ID = input.ID + return expected, nil + } + svc := newStubService(t, repo) + input := dto.UsersCreateRequestDTO{Username: expected.Username, DisplayName: expected.DisplayName} + + // Act. + got, err := svc.UsersCreate(t.Context(), input) + + // Assert. + if err != nil { + t.Fatal(err) + } + if calls != 1 || got != expected { + t.Fatalf("calls=%d, got=%+v, want=%+v", calls, got, expected) + } + }) +} + +// TestService_UsersCreate_InvalidInput refuses malformed registrations without calling storage. +func TestService_UsersCreate_InvalidInput(t *testing.T) { + cases := []struct { + name string + input dto.UsersCreateRequestDTO + }{ + {"Negative: short username", dto.UsersCreateRequestDTO{Username: "a", DisplayName: "Alice"}}, + {"Negative: uppercase username", dto.UsersCreateRequestDTO{Username: "Alice", DisplayName: "Alice"}}, + {"Negative: blank display name", dto.UsersCreateRequestDTO{Username: "alice", DisplayName: " "}}, + {"Negative: display name exceeds rune limit", dto.UsersCreateRequestDTO{Username: "alice", DisplayName: strings.Repeat("界", 101)}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange: every store method fails immediately if called. + svc := newStubService(t, newStoreStub(t)) + + // Act. + got, err := svc.UsersCreate(t.Context(), tc.input) + + // Assert. + if !errors.Is(err, service.ErrInvalid) || got != (dto.UserDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) + } +} + +// TestService_UsersCreate_StoreErrors preserves the application meaning of persistence failures. +func TestService_UsersCreate_StoreErrors(t *testing.T) { + unexpected := errors.New("storage unavailable") + cases := []struct { + name string + cause error + want error + }{ + {"Negative: duplicate username", store.ErrConflict, service.ErrConflict}, + {"Negative: capacity exhausted", store.ErrCapacity, service.ErrCapacity}, + {"Negative: unexpected failure", unexpected, unexpected}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + repo.createUser = func(_ context.Context, _ dto.UserDTO) (dto.UserDTO, error) { + return dto.UserDTO{}, tc.cause + } + svc := newStubService(t, repo) + + // Act. + got, err := svc.UsersCreate(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}) + + // Assert. + if !errors.Is(err, tc.want) || got != (dto.UserDTO{}) { + t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want) + } + }) + } +} + +// TestService_UsersGetMe loads only the requested profile and hides unknown identities. +func TestService_UsersGetMe(t *testing.T) { + t.Run("Positive: returns stored profile", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + expected := dto.UserDTO{ID: uuid.New(), Username: "alice", DisplayName: "Alice", CreatedAt: time.Unix(1700000000, 0).UTC()} + calls := 0 + repo.user = func(_ context.Context, id uuid.UUID) (dto.UserDTO, error) { + calls++ + if id != expected.ID { + t.Fatalf("profile queried for %s instead of %s", id, expected.ID) + } + return expected, nil + } + svc := newStubService(t, repo) + + // Act. + got, err := svc.UsersGetMe(t.Context(), expected.ID.String()) + + // Assert. + if err != nil { + t.Fatal(err) + } + if calls != 1 || got != expected { + t.Fatalf("calls=%d, got=%+v, want=%+v", calls, got, expected) + } + }) + + t.Run("Negative: unknown identity", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + repo.user = func(_ context.Context, _ uuid.UUID) (dto.UserDTO, error) { + return dto.UserDTO{}, store.ErrNotFound + } + svc := newStubService(t, repo) + wantErr := service.ErrUnauthorized + + // Act. + got, err := svc.UsersGetMe(t.Context(), uuid.NewString()) + + // Assert. + if !errors.Is(err, wantErr) { + t.Fatalf("error=%v, want=%v", err, wantErr) + } + if got != (dto.UserDTO{}) { + t.Fatalf("failed operation returned a profile: %+v", got) + } + }) + + t.Run("Negative: storage failure preserved", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + wantErr := errors.New("profile unavailable") + repo.user = func(_ context.Context, _ uuid.UUID) (dto.UserDTO, error) { + return dto.UserDTO{}, wantErr + } + svc := newStubService(t, repo) + + // Act. + got, err := svc.UsersGetMe(t.Context(), uuid.NewString()) + + // Assert. + if !errors.Is(err, wantErr) { + t.Fatalf("error=%v, want=%v", err, wantErr) + } + if got != (dto.UserDTO{}) { + t.Fatalf("failed operation returned a profile: %+v", got) + } + }) +} + +// TestService_UsersGetMe_InvalidIdentity rejects malformed identifiers before any store call. +func TestService_UsersGetMe_InvalidIdentity(t *testing.T) { + cases := []struct { + name string + raw string + }{ + {"Negative: missing header", ""}, + {"Negative: short ID", "invalid"}, + {"Negative: non-UUID characters", strings.Repeat("z", 36)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + svc := newStubService(t, newStoreStub(t)) + + // Act. + got, err := svc.UsersGetMe(t.Context(), tc.raw) + + // Assert. + if !errors.Is(err, service.ErrUnauthorized) || got != (dto.UserDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + }) + } +} + +// TestService_UsersCheckIdentity uses the existence query and never loads a profile. +func TestService_UsersCheckIdentity(t *testing.T) { + t.Run("Positive: existence check without profile loading", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + id := uuid.New() + calls := 0 + repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) { + calls++ + if !slices.Equal(ids, []uuid.UUID{id}) { + t.Fatalf("queried IDs=%v", ids) + } + return true, nil + } + svc := newStubService(t, repo) + + // Act. + err := svc.UsersCheckIdentity(t.Context(), id.String()) + + // Assert. + if !errors.Is(err, nil) || calls != 1 { + t.Fatalf("calls=%d, error=%v", calls, err) + } + }) + + t.Run("Negative: identity does not exist", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + id := uuid.New() + calls := 0 + repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) { + calls++ + if !slices.Equal(ids, []uuid.UUID{id}) { + t.Fatalf("queried IDs=%v", ids) + } + return false, nil + } + svc := newStubService(t, repo) + + // Act. + err := svc.UsersCheckIdentity(t.Context(), id.String()) + + // Assert. + if !errors.Is(err, service.ErrUnauthorized) || calls != 1 { + t.Fatalf("calls=%d, error=%v", calls, err) + } + }) + + t.Run("Negative: existence lookup fails", func(t *testing.T) { + // Arrange. + repo := newStoreStub(t) + id := uuid.New() + calls := 0 + failure := errors.New("identity unavailable") + repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) { + calls++ + if !slices.Equal(ids, []uuid.UUID{id}) { + t.Fatalf("queried IDs=%v", ids) + } + return false, failure + } + svc := newStubService(t, repo) + + // Act. + err := svc.UsersCheckIdentity(t.Context(), id.String()) + + // Assert. + if !errors.Is(err, failure) || calls != 1 { + t.Fatalf("calls=%d, error=%v", calls, err) + } + }) + + t.Run("Negative: malformed identity skips storage", func(t *testing.T) { + // Arrange. + svc := newStubService(t, newStoreStub(t)) + + // Act. + err := svc.UsersCheckIdentity(t.Context(), "invalid") + + // Assert. + if !errors.Is(err, service.ErrUnauthorized) { + t.Fatalf("error=%v", err) + } + }) +} diff --git a/internal/service/production/validation.go b/internal/service/production/validation.go new file mode 100644 index 00000000..102620c8 --- /dev/null +++ b/internal/service/production/validation.go @@ -0,0 +1,51 @@ +package production + +import ( + "strings" + "unicode/utf8" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service" +) + +// These bounds come from the mandatory lab1 OpenAPI schema. +const ( + minUsernameLength = 3 + maxUsernameLength = 32 + maxDisplayNameRunes = 100 + maxChatTitleRunes = 100 + maxChatMembers = 100 + maxMessageRunes = 4000 + canonicalUUIDLength = len("00000000-0000-0000-0000-000000000000") +) + +// validText checks that text is nonblank and within its Unicode length limit. +func validText(value string, maxRunes int) bool { + return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes +} + +// validUsername checks the username length and permitted ASCII characters. +func validUsername(value string) bool { + if len(value) < minUsernameLength || len(value) > maxUsernameLength { + return false + } + for _, char := range value { + if (char < 'a' || char > 'z') && (char < '0' || char > '9') && char != '_' { + return false + } + } + return true +} + +// parseID parses a canonical UUID or returns a validation error. +func parseID(value string) (uuid.UUID, error) { + if len(value) != canonicalUUIDLength { + return uuid.Nil, service.ErrInvalid + } + id, err := uuid.Parse(value) + if err != nil { + return uuid.Nil, service.ErrInvalid + } + return id, nil +} diff --git a/internal/store/interface.go b/internal/store/interface.go new file mode 100644 index 00000000..02dff4d8 --- /dev/null +++ b/internal/store/interface.go @@ -0,0 +1,54 @@ +// Package store defines typed persistence operations and storage errors. +package store + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +var ( + // ErrUnavailable means a required storage dependency cannot serve the operation. + ErrUnavailable = errors.New("storage unavailable") + + // ErrNotFound means a record does not exist. + ErrNotFound = errors.New("record not found") + + // ErrConflict means a unique constraint failed. + ErrConflict = errors.New("record already exists") + + // ErrCapacity means the bounded store cannot accept more data. + ErrCapacity = errors.New("storage capacity reached") +) + +// Interface defines persistence operations on validated typed records. +// Implementations own atomicity, unique constraints and storage capacity, but not +// authorization. Callers must validate membership before accessing chat records. +type Interface interface { + // CreateUser atomically enforces username uniqueness and assigns CreatedAt. + CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) + + // User returns a user by ID or ErrNotFound. + User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) + + // UsersExist reports whether every supplied ID exists; an empty set returns true. + UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) + + // CreateChat atomically stores a chat and its member indexes, assigning CreatedAt. + CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) + + // Chat returns a defensive copy of the stored chat or ErrNotFound. + Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) + + // Chats reads up to limit records after position from the user's chat index. + Chats(ctx context.Context, userID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) + + // CreateMessage appends one message atomically and assigns its ordering timestamp. + CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) + + // Messages reads up to limit records strictly after position in one chat. + Messages(ctx context.Context, chatID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) +} diff --git a/internal/store/memory/capacity.go b/internal/store/memory/capacity.go new file mode 100644 index 00000000..cd5f3bc4 --- /dev/null +++ b/internal/store/memory/capacity.go @@ -0,0 +1,38 @@ +package memory + +import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + +// Conservative logical charges, not measurements of Go allocations or RSS. +// The budget includes record metadata and index entries; HTTP buffers are separate. +const ( + userRecordOverheadBytes = 256 + chatRecordOverheadBytes = 256 + messageRecordOverheadBytes = 256 + chatMemberIndexBytes = 128 + usernameIndexCopies = 2 +) + +// userCost calculates the logical storage charge for a user and its index entries. +func userCost(user dto.UserDTO) int { + return userRecordOverheadBytes + len(user.Username)*usernameIndexCopies + len(user.DisplayName) +} + +// chatCost calculates the logical storage charge for a chat and its membership index. +func chatCost(chat dto.ChatDTO) int { + return chatRecordOverheadBytes + len(chat.Title) + chatMemberIndexBytes*len(chat.MemberIDs) +} + +// messageCost calculates the logical storage charge for a message. +func messageCost(message dto.MessageDTO) int { + return messageRecordOverheadBytes + len(message.Text) +} + +// reserve checks and charges capacity while the caller holds the write lock. +// Callers must not perform a fallible operation after reserving this budget. +func (s *Store) reserve(bytes int) bool { + if bytes > s.limits.MaxStateBytes-s.usedBytes { + return false + } + s.usedBytes += bytes + return true +} diff --git a/internal/store/memory/chats.go b/internal/store/memory/chats.go new file mode 100644 index 00000000..f35761c7 --- /dev/null +++ b/internal/store/memory/chats.go @@ -0,0 +1,66 @@ +package memory + +import ( + "context" + "slices" + "sort" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// copyChat copies the membership slice to keep stored chat state private. +func copyChat(c dto.ChatDTO) dto.ChatDTO { + c.MemberIDs = slices.Clone(c.MemberIDs) + return c +} + +// CreateChat stores the chat and its member index atomically. +func (s *Store) CreateChat(_ context.Context, c dto.ChatDTO) (dto.ChatDTO, error) { + s.mu.Lock() + defer s.mu.Unlock() + for _, id := range c.MemberIDs { + if _, ok := s.users[id]; !ok { + return dto.ChatDTO{}, store.ErrNotFound + } + } + if len(s.chats) >= s.limits.MaxChats || !s.reserve(chatCost(c)) { + return dto.ChatDTO{}, store.ErrCapacity + } + c.CreatedAt = s.timestamp() + c = copyChat(c) + s.chats[c.ID] = c + for _, id := range c.MemberIDs { + s.userChats[id] = append(s.userChats[id], c) + } + return copyChat(c), nil +} + +// Chat retrieves a defensive copy. Authorization belongs to the service. +func (s *Store) Chat(_ context.Context, id uuid.UUID) (dto.ChatDTO, error) { + s.mu.RLock() + defer s.mu.RUnlock() + c, ok := s.chats[id] + if !ok { + return c, store.ErrNotFound + } + return copyChat(c), nil +} + +// Chats uses the per-member index and binary search, without scanning other chats. +func (s *Store) Chats(_ context.Context, user uuid.UUID, p dto.PositionDTO, limit int) ([]dto.ChatDTO, error) { + s.mu.RLock() + defer s.mu.RUnlock() + all := s.userChats[user] + i := sort.Search(len(all), func(i int) bool { + return after(all[i].CreatedAt, all[i].ID, p) + }) + end := min(len(all), i+limit) + out := make([]dto.ChatDTO, 0, end-i) + for _, c := range all[i:end] { + out = append(out, copyChat(c)) + } + return out, nil +} diff --git a/internal/store/memory/chats_test.go b/internal/store/memory/chats_test.go new file mode 100644 index 00000000..385ba67d --- /dev/null +++ b/internal/store/memory/chats_test.go @@ -0,0 +1,148 @@ +package memory + +import ( + "errors" + "reflect" + "testing" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// TestStore_CreateChat_RejectsWithoutMutation checks atomic rejection of invalid or excess chats. +func TestStore_CreateChat_RejectsWithoutMutation(t *testing.T) { + t.Run("Negative: chat capacity reached", func(t *testing.T) { + // Arrange. + cfg := config.Default().Memory + cfg.MaxChats = 1 + repo := newTestStore(t, cfg) + member := seedUser(t, repo, "alice") + original := seedChat(t, repo, member.ID) + input := dto.ChatDTO{ID: uuid.New(), Title: "Rejected", MemberIDs: []uuid.UUID{member.ID}} + wantErr := store.ErrCapacity + + previousBytes := repo.usedBytes + + // Act. + got, err := repo.CreateChat(t.Context(), input) + + // Assert. + if !errors.Is(err, wantErr) || got.ID != uuid.Nil { + t.Fatalf("result=%+v, error=%v, want=%v", got, err, wantErr) + } + items, readErr := repo.Chats(t.Context(), member.ID, dto.PositionDTO{}, 10) + if readErr != nil { + t.Fatal(readErr) + } + if !reflect.DeepEqual(items, []dto.ChatDTO{original}) || len(repo.chats) != 1 || repo.usedBytes != previousBytes { + t.Fatalf("rejected chat changed stored state: %v", items) + } + }) + + t.Run("Negative: member does not exist", func(t *testing.T) { + // Arrange. + cfg := config.Default().Memory + cfg.MaxChats = 1 + repo := newTestStore(t, cfg) + member := seedUser(t, repo, "alice") + original := seedChat(t, repo, member.ID) + input := dto.ChatDTO{ID: uuid.New(), Title: "Rejected", MemberIDs: []uuid.UUID{member.ID}} + wantErr := store.ErrNotFound + input.MemberIDs = append(input.MemberIDs, uuid.New()) + + previousBytes := repo.usedBytes + + // Act. + got, err := repo.CreateChat(t.Context(), input) + + // Assert. + if !errors.Is(err, wantErr) || got.ID != uuid.Nil { + t.Fatalf("result=%+v, error=%v, want=%v", got, err, wantErr) + } + items, readErr := repo.Chats(t.Context(), member.ID, dto.PositionDTO{}, 10) + if readErr != nil { + t.Fatal(readErr) + } + if !reflect.DeepEqual(items, []dto.ChatDTO{original}) || len(repo.chats) != 1 || repo.usedBytes != previousBytes { + t.Fatalf("rejected chat changed stored state: %v", items) + } + }) +} + +// TestStore_CreateChat_DefensiveCopy ensures callers cannot mutate membership through write boundaries. +func TestStore_CreateChat_DefensiveCopy(t *testing.T) { + t.Run("Positive: isolated input membership", func(t *testing.T) { + // Arrange. + repo := newTestStore(t, config.Default().Memory) + member := seedUser(t, repo, "alice") + input := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{member.ID}} + _, err := repo.CreateChat(t.Context(), input) + if err != nil { + t.Fatal(err) + } + + // Act: a caller modifies the slice it owns after CreateChat returns. + + input.MemberIDs[0] = uuid.New() + + // Assert. + stored, err := repo.Chat(t.Context(), input.ID) + if err != nil { + t.Fatal(err) + } + if len(stored.MemberIDs) != 1 || stored.MemberIDs[0] != member.ID { + t.Fatalf("caller mutated stored membership: %+v", stored) + } + }) + + t.Run("Positive: isolated result membership", func(t *testing.T) { + // Arrange. + repo := newTestStore(t, config.Default().Memory) + member := seedUser(t, repo, "alice") + input := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{member.ID}} + created, err := repo.CreateChat(t.Context(), input) + if err != nil { + t.Fatal(err) + } + + // Act: a caller modifies the slice it owns after CreateChat returns. + + created.MemberIDs[0] = uuid.New() + + // Assert. + stored, err := repo.Chat(t.Context(), input.ID) + if err != nil { + t.Fatal(err) + } + if len(stored.MemberIDs) != 1 || stored.MemberIDs[0] != member.ID { + t.Fatalf("caller mutated stored membership: %+v", stored) + } + }) +} + +// TestStore_Chat_DefensiveCopy ensures a fetched detail cannot alter future reads. +func TestStore_Chat_DefensiveCopy(t *testing.T) { + // Arrange. + repo := newTestStore(t, config.Default().Memory) + member := seedUser(t, repo, "alice") + original := seedChat(t, repo, member.ID) + fetched, err := repo.Chat(t.Context(), original.ID) + if err != nil { + t.Fatal(err) + } + + // Act. + fetched.MemberIDs[0] = uuid.New() + + // Assert. + stored, err := repo.Chat(t.Context(), original.ID) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(stored, original) { + t.Fatalf("read changed stored chat: %+v", stored) + } +} diff --git a/internal/store/memory/messages.go b/internal/store/memory/messages.go new file mode 100644 index 00000000..360a3e9e --- /dev/null +++ b/internal/store/memory/messages.go @@ -0,0 +1,41 @@ +package memory + +import ( + "context" + "sort" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// CreateMessage assigns ordering and publishes one complete message atomically. +func (s *Store) CreateMessage(_ context.Context, m dto.MessageDTO) (dto.MessageDTO, error) { + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.chats[m.ChatID]; !ok { + return dto.MessageDTO{}, store.ErrNotFound + } + if s.messageCount >= s.limits.MaxMessages || !s.reserve(messageCost(m)) { + return dto.MessageDTO{}, store.ErrCapacity + } + m.CreatedAt = s.timestamp() + s.messages[m.ChatID] = append(s.messages[m.ChatID], m) + s.messageCount++ + return m, nil +} + +// Messages performs keyset pagination over an append-only ordered history. +func (s *Store) Messages(_ context.Context, chat uuid.UUID, p dto.PositionDTO, limit int) ([]dto.MessageDTO, error) { + s.mu.RLock() + defer s.mu.RUnlock() + all := s.messages[chat] + i := sort.Search(len(all), func(i int) bool { + return after(all[i].CreatedAt, all[i].ID, p) + }) + end := min(len(all), i+limit) + out := make([]dto.MessageDTO, end-i) + copy(out, all[i:end]) + return out, nil +} diff --git a/internal/store/memory/messages_test.go b/internal/store/memory/messages_test.go new file mode 100644 index 00000000..b1f66307 --- /dev/null +++ b/internal/store/memory/messages_test.go @@ -0,0 +1,72 @@ +package memory + +import ( + "errors" + "reflect" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// TestStore_CreateMessage_ByteCapacity preserves acknowledged history and accounting on rejection. +func TestStore_CreateMessage_ByteCapacity(t *testing.T) { + // Arrange. + cfg := config.Default().Memory + cfg.MaxStateBytes = 2048 + repo := newTestStore(t, cfg) + member := seedUser(t, repo, "alice") + chat := seedChat(t, repo, member.ID) + original := seedMessage(t, repo, chat, "kept") + input := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: member.ID, Text: strings.Repeat("x", 2000)} + previousBytes := repo.usedBytes + + // Act. + got, err := repo.CreateMessage(t.Context(), input) + + // Assert. + if !errors.Is(err, store.ErrCapacity) || got != (dto.MessageDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + items, readErr := repo.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 10) + if readErr != nil { + t.Fatal(readErr) + } + if !reflect.DeepEqual(items, []dto.MessageDTO{original}) || repo.messageCount != 1 || repo.usedBytes != previousBytes { + t.Fatalf("overflow changed history or accounting: %v", items) + } +} + +// TestStore_CreateMessage_ClockRollback preserves chronological append order after a clock rollback. +func TestStore_CreateMessage_ClockRollback(t *testing.T) { + // Arrange. + repo := newTestStore(t, config.Default().Memory) + member := seedUser(t, repo, "alice") + chat := seedChat(t, repo, member.ID) + repo.lastTime = time.Now().UTC().Add(time.Hour) + first := seedMessage(t, repo, chat, "first") + input := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: member.ID, Text: "second"} + + // Act. + second, err := repo.CreateMessage(t.Context(), input) + + // Assert. + if err != nil { + t.Fatal(err) + } + if !second.CreatedAt.After(first.CreatedAt) { + t.Fatalf("second=%s must follow first=%s", second.CreatedAt, first.CreatedAt) + } + page, readErr := repo.Messages(t.Context(), chat.ID, dto.PositionDTO{CreatedAt: first.CreatedAt, ID: first.ID}, 10) + if readErr != nil { + t.Fatal(readErr) + } + if !reflect.DeepEqual(page, []dto.MessageDTO{second}) { + t.Fatalf("continuation lost the later message: %v", page) + } +} diff --git a/internal/store/memory/ordering.go b/internal/store/memory/ordering.go new file mode 100644 index 00000000..90e2c1a5 --- /dev/null +++ b/internal/store/memory/ordering.go @@ -0,0 +1,25 @@ +package memory + +import ( + "bytes" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// timestamp is called under the write lock, keeping append order during clock rollback. +func (s *Store) timestamp() time.Time { + now := time.Now().UTC() + if !now.After(s.lastTime) { + now = s.lastTime.Add(time.Nanosecond) + } + s.lastTime = now + return now +} + +// after compares a record with a keyset pagination position. +func after(t time.Time, id uuid.UUID, p dto.PositionDTO) bool { + return t.After(p.CreatedAt) || (t.Equal(p.CreatedAt) && bytes.Compare(id[:], p.ID[:]) > 0) +} diff --git a/internal/store/memory/store.go b/internal/store/memory/store.go new file mode 100644 index 00000000..20333e11 --- /dev/null +++ b/internal/store/memory/store.go @@ -0,0 +1,47 @@ +// Package memory implements synchronized storage within one bounded process. +package memory + +import ( + "sync" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// Store owns all mutable state and its indexes under one lock. +// Records are immutable once published; membership slices are copied on both +// write and read boundaries. Its zero value is not usable; construct it with New. +type Store struct { + mu sync.RWMutex + limits config.Memory + users map[uuid.UUID]dto.UserDTO + usernames map[string]uuid.UUID + chats map[uuid.UUID]dto.ChatDTO + userChats map[uuid.UUID][]dto.ChatDTO + messages map[uuid.UUID][]dto.MessageDTO + messageCount int + usedBytes int + lastTime time.Time +} + +var _ store.Interface = (*Store)(nil) + +// New validates and copies capacity settings, then initializes an empty store. +// It creates no files, goroutines or external connections. +func New(cfg *config.Memory) (*Store, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + return &Store{ + limits: *cfg, + users: make(map[uuid.UUID]dto.UserDTO), + usernames: make(map[string]uuid.UUID), + chats: make(map[uuid.UUID]dto.ChatDTO), + userChats: make(map[uuid.UUID][]dto.ChatDTO), + messages: make(map[uuid.UUID][]dto.MessageDTO), + }, nil +} diff --git a/internal/store/memory/store_test.go b/internal/store/memory/store_test.go new file mode 100644 index 00000000..13aecf79 --- /dev/null +++ b/internal/store/memory/store_test.go @@ -0,0 +1,64 @@ +package memory + +import ( + "testing" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// TestStore_New rejects missing capacity settings. +func TestStore_New(t *testing.T) { + // Arrange. + var cfg *config.Memory + + // Act. + repo, err := New(cfg) + + // Assert. + if err == nil || repo != nil { + t.Fatalf("missing configuration accepted: %v, %v", repo, err) + } +} + +// newTestStore creates independent storage for one scenario. +func newTestStore(t *testing.T, cfg *config.Memory) *Store { + t.Helper() + repo, err := New(cfg) + if err != nil { + t.Fatal(err) + } + return repo +} + +// seedUser creates a fixture user and checks preparation errors. +func seedUser(t *testing.T, repo *Store, username string) dto.UserDTO { + t.Helper() + user, err := repo.CreateUser(t.Context(), dto.UserDTO{ID: uuid.New(), Username: username}) + if err != nil { + t.Fatal(err) + } + return user +} + +// seedChat creates a fixture chat for an existing member. +func seedChat(t *testing.T, repo *Store, member uuid.UUID) dto.ChatDTO { + t.Helper() + chat, err := repo.CreateChat(t.Context(), dto.ChatDTO{ID: uuid.New(), Title: "Fixture", MemberIDs: []uuid.UUID{member}}) + if err != nil { + t.Fatal(err) + } + return chat +} + +// seedMessage creates an acknowledged fixture message. +func seedMessage(t *testing.T, repo *Store, chat dto.ChatDTO, text string) dto.MessageDTO { + t.Helper() + message, err := repo.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: chat.MemberIDs[0], Text: text}) + if err != nil { + t.Fatal(err) + } + return message +} diff --git a/internal/store/memory/users.go b/internal/store/memory/users.go new file mode 100644 index 00000000..5d34a6f6 --- /dev/null +++ b/internal/store/memory/users.go @@ -0,0 +1,50 @@ +package memory + +import ( + "context" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// CreateUser atomically enforces uniqueness and resource limits. +func (s *Store) CreateUser(_ context.Context, u dto.UserDTO) (dto.UserDTO, error) { + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.usernames[u.Username]; ok { + return dto.UserDTO{}, store.ErrConflict + } + if len(s.users) >= s.limits.MaxUsers || !s.reserve(userCost(u)) { + return dto.UserDTO{}, store.ErrCapacity + } + u.CreatedAt = s.timestamp() + s.users[u.ID] = u + s.usernames[u.Username] = u.ID + return u, nil +} + +// User retrieves an immutable user. +func (s *Store) User(_ context.Context, id uuid.UUID) (dto.UserDTO, error) { + s.mu.RLock() + defer s.mu.RUnlock() + u, ok := s.users[id] + if !ok { + return u, store.ErrNotFound + } + return u, nil +} + +// UsersExist checks the complete set under one read lock without loading user records. +// Empty sets return true, and duplicate IDs do not affect the result. +func (s *Store) UsersExist(_ context.Context, ids []uuid.UUID) (bool, error) { + s.mu.RLock() + defer s.mu.RUnlock() + for _, id := range ids { + if _, exists := s.users[id]; !exists { + return false, nil + } + } + return true, nil +} diff --git a/internal/store/memory/users_test.go b/internal/store/memory/users_test.go new file mode 100644 index 00000000..eb72ff36 --- /dev/null +++ b/internal/store/memory/users_test.go @@ -0,0 +1,116 @@ +package memory + +import ( + "errors" + "testing" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// TestStore_UsersExist checks all-members semantics on an independent store per case. +func TestStore_UsersExist(t *testing.T) { + t.Run("Positive: existing user", func(t *testing.T) { + // Arrange. + repo := newTestStore(t, config.Default().Memory) + user := seedUser(t, repo, "alice") + ids := []uuid.UUID{user.ID} + want := true + + // Act. + got, err := repo.UsersExist(t.Context(), ids) + + // Assert. + if err != nil { + t.Fatal(err) + } + if got != want { + t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want) + } + }) + + t.Run("Positive: duplicate IDs", func(t *testing.T) { + // Arrange. + repo := newTestStore(t, config.Default().Memory) + user := seedUser(t, repo, "alice") + ids := []uuid.UUID{user.ID} + want := true + + ids = append(ids, user.ID) + + // Act. + got, err := repo.UsersExist(t.Context(), ids) + + // Assert. + if err != nil { + t.Fatal(err) + } + if got != want { + t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want) + } + }) + + t.Run("Positive: empty set", func(t *testing.T) { + // Arrange. + repo := newTestStore(t, config.Default().Memory) + var ids []uuid.UUID + want := true + + // Act. + got, err := repo.UsersExist(t.Context(), ids) + + // Assert. + if err != nil { + t.Fatal(err) + } + if got != want { + t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want) + } + }) + + t.Run("Negative: missing member", func(t *testing.T) { + // Arrange. + repo := newTestStore(t, config.Default().Memory) + user := seedUser(t, repo, "alice") + ids := []uuid.UUID{user.ID} + want := false + + ids = append(ids, uuid.New()) + + // Act. + got, err := repo.UsersExist(t.Context(), ids) + + // Assert. + if err != nil { + t.Fatal(err) + } + if got != want { + t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want) + } + }) +} + +// TestStore_CreateUser_Capacity checks that a refused user consumes no storage or username index. +func TestStore_CreateUser_Capacity(t *testing.T) { + // Arrange. + cfg := config.Default().Memory + cfg.MaxUsers = 1 + repo := newTestStore(t, cfg) + original := seedUser(t, repo, "alice") + rejected := dto.UserDTO{ID: uuid.New(), Username: "bob"} + previousBytes := repo.usedBytes + + // Act. + got, err := repo.CreateUser(t.Context(), rejected) + + // Assert. + if !errors.Is(err, store.ErrCapacity) || got != (dto.UserDTO{}) { + t.Fatalf("result=%+v, error=%v", got, err) + } + if len(repo.users) != 1 || repo.users[original.ID] != original || len(repo.usernames) != 1 || repo.usernames[original.Username] != original.ID || repo.usedBytes != previousBytes { + t.Fatal("refused registration changed storage or indexes") + } +} diff --git a/internal/store/postgres/chats.go b/internal/store/postgres/chats.go new file mode 100644 index 00000000..518a34ce --- /dev/null +++ b/internal/store/postgres/chats.go @@ -0,0 +1,58 @@ +package postgres + +import ( + "context" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// CreateChat commits the chat and every member together, rolling back on any failure. +func (s *Store) CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { + if err := tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES(@id,@title) RETURNING created_at`, pgx.StrictNamedArgs{"id": chat.ID, "title": chat.Title}).Scan(&chat.CreatedAt); err != nil { + return err + } + _, err := tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) SELECT @chat,id FROM unnest(@members::uuid[]) AS member(id)`, pgx.StrictNamedArgs{"chat": chat.ID, "members": chat.MemberIDs}) + return err + }) + return chat, normalize(err) +} + +// Chat reads a chat and its immutable membership in one snapshot. +func (s *Store) Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + var chat dto.ChatDTO + err := s.pool.QueryRow(ctx, `SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) + FROM chats c WHERE c.id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs) + return chat, normalize(err) +} + +// Chats returns the requested keyset page of chats visible to a user. +func (s *Store) Chats(ctx context.Context, userID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + rows, err := s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) + FROM chats c JOIN chat_members m ON m.chat_id=c.id + WHERE m.user_id=@user AND (c.created_at,c.id)>(@time,@id) ORDER BY c.created_at,c.id LIMIT @limit`, pgx.StrictNamedArgs{ + "user": userID, "time": position.CreatedAt, "id": position.ID, "limit": limit, + }) + if err != nil { + return nil, normalize(err) + } + defer rows.Close() + chats := make([]dto.ChatDTO, 0) + for rows.Next() { + var chat dto.ChatDTO + if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil { + return nil, normalize(err) + } + chats = append(chats, chat) + } + return chats, normalize(rows.Err()) +} diff --git a/internal/store/postgres/errors_test.go b/internal/store/postgres/errors_test.go new file mode 100644 index 00000000..2257de00 --- /dev/null +++ b/internal/store/postgres/errors_test.go @@ -0,0 +1,52 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// TestNormalizeUnavailable classifies dependency failures while retaining their causes. +func TestNormalizeUnavailable(t *testing.T) { + cases := []struct { + name string + err error + }{ + {"deadline", context.DeadlineExceeded}, + {"closed stream", io.EOF}, + {"truncated stream", io.ErrUnexpectedEOF}, + {"network", &net.OpError{Op: "dial", Net: "tcp", Err: errors.New("refused")}}, + {"connection exception", &pgconn.PgError{Code: "08006"}}, + {"connection limit", &pgconn.PgError{Code: "53300"}}, + {"shutdown", &pgconn.PgError{Code: "57P01"}}, + {"crash", &pgconn.PgError{Code: "57P02"}}, + {"starting", &pgconn.PgError{Code: "57P03"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := normalize(fmt.Errorf("operation failed: %w", tc.err)) + if !errors.Is(err, store.ErrUnavailable) || !errors.Is(err, tc.err) { + t.Fatalf("failure category or cause lost: %T", tc.err) + } + }) + } +} + +// TestNormalizeUnexpected preserves programming errors instead of misclassifying them as outages. +func TestNormalizeUnexpected(t *testing.T) { + for _, code := range []string{"42601", "23503", "42P01"} { + t.Run(code, func(t *testing.T) { + err := &pgconn.PgError{Code: code} + if normalize(err) != err { + t.Fatal("unexpected SQL error was reclassified") + } + }) + } +} diff --git a/internal/store/postgres/messages.go b/internal/store/postgres/messages.go new file mode 100644 index 00000000..ced60b33 --- /dev/null +++ b/internal/store/postgres/messages.go @@ -0,0 +1,50 @@ +package postgres + +import ( + "context" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// CreateMessage serializes timestamps on the owning chat and atomically appends a message. +func (s *Store) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { + if err := tx.QueryRow(ctx, `UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond') + WHERE id=@chat RETURNING last_message_at`, pgx.StrictNamedArgs{"chat": message.ChatID}).Scan(&message.CreatedAt); err != nil { + return err + } + _, err := tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES(@id,@chat,@sender,@text,@time)`, pgx.StrictNamedArgs{ + "id": message.ID, "chat": message.ChatID, "sender": message.SenderID, "text": message.Text, "time": message.CreatedAt, + }) + return err + }) + return message, normalize(err) +} + +// Messages reads an indexed keyset page without scanning earlier history. +func (s *Store) Messages(ctx context.Context, chatID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + rows, err := s.pool.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages + WHERE chat_id=@chat AND (created_at,id)>(@time,@id) ORDER BY created_at,id LIMIT @limit`, pgx.StrictNamedArgs{ + "chat": chatID, "time": position.CreatedAt, "id": position.ID, "limit": limit, + }) + if err != nil { + return nil, normalize(err) + } + defer rows.Close() + messages := make([]dto.MessageDTO, 0) + for rows.Next() { + var message dto.MessageDTO + if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt); err != nil { + return nil, normalize(err) + } + messages = append(messages, message) + } + return messages, normalize(rows.Err()) +} diff --git a/internal/store/postgres/migrations/001_initial.sql b/internal/store/postgres/migrations/001_initial.sql new file mode 100644 index 00000000..0a19d68d --- /dev/null +++ b/internal/store/postgres/migrations/001_initial.sql @@ -0,0 +1,34 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE, + display_name text NOT NULL, + password_hash text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + last_message_at timestamptz NOT NULL DEFAULT '-infinity' +); +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY(chat_id,user_id) +); +CREATE INDEX chat_members_user ON chat_members(user_id,chat_id); +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL, + created_at timestamptz NOT NULL, + FOREIGN KEY(chat_id,sender_id) REFERENCES chat_members(chat_id,user_id) +); +CREATE INDEX messages_history ON messages(chat_id,created_at,id); +CREATE TABLE sessions ( + token_hash text PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL +); +CREATE INDEX sessions_expiry ON sessions(expires_at); diff --git a/internal/store/postgres/sessions.go b/internal/store/postgres/sessions.go new file mode 100644 index 00000000..3e64d274 --- /dev/null +++ b/internal/store/postgres/sessions.go @@ -0,0 +1,36 @@ +package postgres + +import ( + "context" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +// SaveSession persists an absolute expiry and a token digest in PostgreSQL. +func (s *Store) SaveSession(ctx context.Context, hash string, userID uuid.UUID, expiry time.Time) error { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + _, err := s.pool.Exec(ctx, `INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(@hash,@user,@expiry)`, pgx.StrictNamedArgs{ + "hash": hash, "user": userID, "expiry": expiry, + }) + return normalize(err) +} + +// SessionUser rejects absent, revoked and expired sessions using database time. +func (s *Store) SessionUser(ctx context.Context, hash string) (uuid.UUID, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + var id uuid.UUID + err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=@hash AND expires_at>clock_timestamp()`, pgx.StrictNamedArgs{"hash": hash}).Scan(&id) + return id, normalize(err) +} + +// RevokeSession deletes the authoritative session before logout succeeds. +func (s *Store) RevokeSession(ctx context.Context, hash string) error { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + _, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash=@hash`, pgx.StrictNamedArgs{"hash": hash}) + return normalize(err) +} diff --git a/internal/store/postgres/store.go b/internal/store/postgres/store.go new file mode 100644 index 00000000..cf75cfb0 --- /dev/null +++ b/internal/store/postgres/store.go @@ -0,0 +1,127 @@ +// Package postgres persists messenger records in PostgreSQL. +package postgres + +import ( + "context" + _ "embed" + "errors" + "fmt" + "io" + "net" + "strings" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +//go:embed migrations/001_initial.sql +var initialMigration string + +const migrationLockID = 202602 + +// Options bounds database resource use. +type Options struct { + // URL identifies the isolated application database. + URL string + // MaxConnections bounds concurrent database connections. + MaxConnections int32 + // Timeout bounds each persistence operation. + Timeout time.Duration +} + +// Store owns the PostgreSQL pool; Start and Close belong to application lifecycle. +type Store struct { + pool *pgxpool.Pool + timeout time.Duration +} + +var _ store.Interface = (*Store)(nil) + +// New validates options and builds a lazy pool without opening connections. +func New(options Options) (*Store, error) { + if options.URL == "" || options.MaxConnections < 1 || options.Timeout <= 0 { + return nil, fmt.Errorf("database URL, pool bound and timeout are required") + } + cfg, err := pgxpool.ParseConfig(options.URL) + if err != nil { + return nil, fmt.Errorf("invalid database configuration") + } + cfg.AfterConnect = func(_ context.Context, conn *pgx.Conn) error { + conn.TypeMap().RegisterType(&pgtype.Type{Name: "timestamptz", OID: pgtype.TimestamptzOID, Codec: &pgtype.TimestamptzCodec{ScanLocation: time.UTC}}) + return nil + } + cfg.MaxConns = options.MaxConnections + cfg.ConnConfig.ConnectTimeout = options.Timeout + pool, err := pgxpool.NewWithConfig(context.Background(), cfg) + if err != nil { + return nil, err + } + return &Store{pool: pool, timeout: options.Timeout}, nil +} + +// Start verifies connectivity and applies versioned migrations under a transaction lock. +func (s *Store) Start(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { + if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(@id)", pgx.StrictNamedArgs{"id": migrationLockID}); err != nil { + return err + } + if _, err := tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil { + return err + } + var exists bool + if err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=1)").Scan(&exists); err != nil { + return err + } + if exists { + return nil + } + + if _, err := tx.Exec(ctx, initialMigration); err != nil { + return err + } + _, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES(1)") + return err + }) +} + +// Close releases owned pool resources after serving has stopped. +func (s *Store) Close() { + s.pool.Close() +} + +// Ping checks whether mandatory persistence can serve requests. +func (s *Store) Ping(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + return s.pool.Ping(ctx) +} + +// normalize translates expected database errors without exposing SQL to higher layers. +func normalize(err error) error { + if errors.Is(err, pgx.ErrNoRows) { + return store.ErrNotFound + } + if databaseError, ok := errors.AsType[*pgconn.PgError](err); ok { + if databaseError.Code == "23505" { + return store.ErrConflict + } + if strings.HasPrefix(databaseError.Code, "08") || strings.HasPrefix(databaseError.Code, "53") || + databaseError.Code == "57P01" || databaseError.Code == "57P02" || databaseError.Code == "57P03" { + return fmt.Errorf("%w: %w", store.ErrUnavailable, err) + } + } + var networkError net.Error + var connectError *pgconn.ConnectError + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || + errors.As(err, &networkError) || errors.As(err, &connectError) || pgconn.SafeToRetry(err) { + return fmt.Errorf("%w: %w", store.ErrUnavailable, err) + } + return err +} diff --git a/internal/store/postgres/store_test.go b/internal/store/postgres/store_test.go new file mode 100644 index 00000000..91c2e101 --- /dev/null +++ b/internal/store/postgres/store_test.go @@ -0,0 +1,336 @@ +package postgres + +import ( + "context" + "errors" + "os" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store" +) + +// testStore creates an isolated schema inside the explicitly configured test database. +func testStore(t *testing.T) *Store { + t.Helper() + url := os.Getenv("TEST_DATABASE_URL") + if url == "" { + t.Skip("TEST_DATABASE_URL is required for PostgreSQL integration tests") + } + admin, err := pgx.Connect(t.Context(), url) + if err != nil { + t.Fatal(err) + } + schema := "test_" + uuid.New().String()[:8] + identifier := pgx.Identifier{schema}.Sanitize() + if _, err := admin.Exec(t.Context(), "CREATE SCHEMA "+identifier); err != nil { + t.Fatal(err) + } + separator := "?" + if containsQuery(url) { + separator = "&" + } + s, err := New(Options{URL: url + separator + "search_path=" + schema, MaxConnections: 4, Timeout: 3 * time.Second}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + s.Close() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if _, err := admin.Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil { + t.Error(err) + } + if err := admin.Close(ctx); err != nil { + t.Error(err) + } + }) + if err := s.Start(t.Context()); err != nil { + t.Fatal(err) + } + return s +} + +// containsQuery identifies URL parameters without exposing credentials in test logs. +func containsQuery(value string) bool { + for _, char := range value { + if char == '?' { + return true + } + } + return false +} + +// fixtureUser creates an independent profile for a persistence scenario. +func fixtureUser(t *testing.T, s *Store) dto.UserDTO { + t.Helper() + user, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "u_" + uuid.NewString()[:8], DisplayName: "Test"}, "test-hash") + if err != nil { + t.Fatal(err) + } + return user +} + +// fixtureChat creates a chat containing an existing user. +func fixtureChat(t *testing.T, s *Store, user dto.UserDTO) dto.ChatDTO { + t.Helper() + chat, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: uuid.New(), Title: "Test", MemberIDs: []uuid.UUID{user.ID}}) + if err != nil { + t.Fatal(err) + } + return chat +} + +// TestMigrationsRepeat verifies idempotent schema initialization. +func TestMigrationsRepeat(t *testing.T) { + s := testStore(t) + user := fixtureUser(t, s) + if err := s.Start(t.Context()); err != nil { + t.Fatal(err) + } + read, err := s.User(t.Context(), user.ID) + if err != nil || read.ID != user.ID || read.CreatedAt.Location() != time.UTC { + t.Fatalf("migration changed data or UTC: %v", err) + } + if err := s.Ping(t.Context()); err != nil { + t.Fatal(err) + } +} + +// TestRegistrationRace verifies database uniqueness under concurrent registration. +func TestRegistrationRace(t *testing.T) { + s := testStore(t) + outcomes := make(chan error, 12) + var wg sync.WaitGroup + for range 12 { + wg.Go(func() { + _, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "same", DisplayName: "Test"}, "hash") + outcomes <- err + }) + } + wg.Wait() + close(outcomes) + successes := 0 + for err := range outcomes { + if err == nil { + successes++ + } else if !errors.Is(err, store.ErrConflict) { + t.Fatal(err) + } + } + if successes != 1 { + t.Fatalf("got %d successful registrations", successes) + } +} + +// TestCreateChatRollsBack verifies failure of membership insertion leaves no chat. +func TestCreateChatRollsBack(t *testing.T) { + s := testStore(t) + id := uuid.New() + _, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: id, Title: "Rollback", MemberIDs: []uuid.UUID{uuid.New()}}) + if err == nil { + t.Fatal("foreign key failure absent") + } + if _, err := s.Chat(t.Context(), id); !errors.Is(err, store.ErrNotFound) { + t.Fatalf("chat survived rollback: %v", err) + } +} + +// TestChatPageUsesMembershipAndCursor verifies one compound visibility/page invariant. +func TestChatPageUsesMembershipAndCursor(t *testing.T) { + s := testStore(t) + owner := fixtureUser(t, s) + outsider := fixtureUser(t, s) + first := fixtureChat(t, s, owner) + second := fixtureChat(t, s, owner) + fixtureChat(t, s, outsider) + page, err := s.Chats(t.Context(), owner.ID, dto.PositionDTO{CreatedAt: first.CreatedAt, ID: first.ID}, 10) + if err != nil || len(page) != 1 || page[0].ID != second.ID || len(page[0].MemberIDs) != 1 { + t.Fatalf("invalid membership page: %+v %v", page, err) + } +} + +// TestMessagePageOrdersConcurrentWrites verifies monotonic durable ordering and continuation. +func TestMessagePageOrdersConcurrentWrites(t *testing.T) { + s := testStore(t) + user := fixtureUser(t, s) + chat := fixtureChat(t, s, user) + var wg sync.WaitGroup + failures := make(chan error, 20) + for range 20 { + wg.Go(func() { + _, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "synthetic"}) + failures <- err + }) + } + wg.Wait() + close(failures) + for err := range failures { + if err != nil { + t.Fatal(err) + } + } + page, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 10) + if err != nil || len(page) != 10 { + t.Fatalf("first page: %d %v", len(page), err) + } + for index := 1; index < len(page); index++ { + if !page[index].CreatedAt.After(page[index-1].CreatedAt) { + t.Fatal("timestamps are not monotonic") + } + } + last := page[len(page)-1] + next, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{CreatedAt: last.CreatedAt, ID: last.ID}, 20) + if err != nil || len(next) != 10 || !next[0].CreatedAt.After(last.CreatedAt) { + t.Fatalf("continuation: %d %v", len(next), err) + } +} + +// TestCredentialsReadsStoredHash checks credential lookup independently of public profiles. +func TestCredentialsReadsStoredHash(t *testing.T) { + s := testStore(t) + user := fixtureUser(t, s) + got, hash, err := s.Credentials(t.Context(), user.Username) + if err != nil || got.ID != user.ID || hash != "test-hash" { + t.Fatalf("credentials mismatch: %v", err) + } +} + +// TestUsersExistChecksAllIDs verifies the set membership contract. +func TestUsersExistChecksAllIDs(t *testing.T) { + for _, missing := range []bool{false, true} { + t.Run(map[bool]string{false: "all exist", true: "missing member"}[missing], func(t *testing.T) { + s := testStore(t) + ids := []uuid.UUID{fixtureUser(t, s).ID} + if missing { + ids = append(ids, uuid.New()) + } + exists, err := s.UsersExist(t.Context(), ids) + if err != nil || exists == missing { + t.Fatalf("exists=%v error=%v", exists, err) + } + }) + } +} + +// TestSessionExpiry rejects persisted sessions whose absolute deadline has passed. +func TestSessionExpiry(t *testing.T) { + s := testStore(t) + user := fixtureUser(t, s) + if err := s.SaveSession(t.Context(), "expired", user.ID, time.Now().Add(-time.Second)); err != nil { + t.Fatal(err) + } + if _, err := s.SessionUser(t.Context(), "expired"); !errors.Is(err, store.ErrNotFound) { + t.Fatalf("expired session accepted: %v", err) + } +} + +// TestSessionRevocation removes a still-valid session from the source of truth. +func TestSessionRevocation(t *testing.T) { + s := testStore(t) + user := fixtureUser(t, s) + if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + if err := s.RevokeSession(t.Context(), "live"); err != nil { + t.Fatal(err) + } + if _, err := s.SessionUser(t.Context(), "live"); !errors.Is(err, store.ErrNotFound) { + t.Fatalf("revoked session accepted: %v", err) + } +} + +// TestSessionResolvesOwner verifies a live session's immutable identity. +func TestSessionResolvesOwner(t *testing.T) { + s := testStore(t) + user := fixtureUser(t, s) + if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + id, err := s.SessionUser(t.Context(), "live") + if err != nil || id != user.ID { + t.Fatalf("invalid owner: %v", err) + } +} + +// TestNewRejectsInvalidOptions verifies pool construction errors without connecting. +func TestNewRejectsInvalidOptions(t *testing.T) { + for _, options := range []Options{{}, {URL: "://invalid", MaxConnections: 1, Timeout: time.Second}} { + if _, err := New(options); err == nil { + t.Fatal("invalid options accepted") + } + } +} + +// TestCreateMessageMissingChat reports a typed missing-record error. +func TestCreateMessageMissingChat(t *testing.T) { + s := testStore(t) + _, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: uuid.New(), SenderID: uuid.New(), Text: "test"}) + if !errors.Is(err, store.ErrNotFound) { + t.Fatal(err) + } +} + +// TestMessagesCanceledReturnsError verifies bounded cancellation before query execution. +func TestMessagesCanceledReturnsError(t *testing.T) { + s := testStore(t) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := s.Messages(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil { + t.Fatal("canceled query succeeded") + } +} + +// TestChatsCanceledReturnsError verifies bounded cancellation of membership pages. +func TestChatsCanceledReturnsError(t *testing.T) { + s := testStore(t) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := s.Chats(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil { + t.Fatal("canceled query succeeded") + } +} + +// TestMigrationCancellationReturnsError checks startup cancellation before migration work. +func TestMigrationCancellationReturnsError(t *testing.T) { + s := testStore(t) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if err := s.Start(ctx); err == nil { + t.Fatal("canceled migration succeeded") + } +} + +// TestMigrationFailureRollsBackVersion verifies a failed migration is never marked applied. +func TestMigrationFailureRollsBackVersion(t *testing.T) { + s := testStore(t) + if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations"); err != nil { + t.Fatal(err) + } + if err := s.Start(t.Context()); err == nil { + t.Fatal("conflicting unversioned schema accepted") + } + var count int + if err := s.pool.QueryRow(t.Context(), "SELECT count(*) FROM schema_migrations").Scan(&count); err != nil { + t.Fatal(err) + } + if count != 0 { + t.Fatal("failed migration version committed") + } +} + +// TestMigrationRejectsBrokenVersionLedger verifies corrupt migration metadata stops startup safely. +func TestMigrationRejectsBrokenVersionLedger(t *testing.T) { + s := testStore(t) + if _, err := s.pool.Exec(t.Context(), "ALTER TABLE schema_migrations RENAME COLUMN version TO broken_version"); err != nil { + t.Fatal(err) + } + if err := s.Start(t.Context()); err == nil { + t.Fatal("broken version ledger accepted") + } +} diff --git a/internal/store/postgres/users.go b/internal/store/postgres/users.go new file mode 100644 index 00000000..db22c474 --- /dev/null +++ b/internal/store/postgres/users.go @@ -0,0 +1,58 @@ +package postgres + +import ( + "context" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// CreateUser inserts a profile and enforces uniqueness inside PostgreSQL. +func (s *Store) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) { + return s.Register(ctx, user, "") +} + +// Register atomically stores a profile and its password hash. +func (s *Store) Register(ctx context.Context, user dto.UserDTO, passwordHash string) (dto.UserDTO, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash) + VALUES(@id,@username,@display_name,@password_hash) RETURNING created_at`, pgx.StrictNamedArgs{ + "id": user.ID, + "username": user.Username, + "display_name": user.DisplayName, + "password_hash": passwordHash, + }).Scan(&user.CreatedAt) + return user, normalize(err) +} + +// User reads a profile without credentials. +func (s *Store) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + var user dto.UserDTO + err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at FROM users WHERE id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + return user, normalize(err) +} + +// Credentials reads the account needed for password verification. +func (s *Store) Credentials(ctx context.Context, username string) (dto.UserDTO, string, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + var user dto.UserDTO + var hash string + err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=@username`, pgx.StrictNamedArgs{"username": username}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash) + return user, hash, normalize(err) +} + +// UsersExist checks all distinct requested identifiers in one bounded query. +func (s *Store) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + var exists bool + err := s.pool.QueryRow(ctx, `SELECT NOT EXISTS (SELECT id FROM unnest(@ids::uuid[]) AS requested(id) + WHERE NOT EXISTS (SELECT 1 FROM users WHERE users.id=requested.id))`, pgx.StrictNamedArgs{"ids": ids}).Scan(&exists) + return exists, normalize(err) +} diff --git a/internal/strictjson/decode.go b/internal/strictjson/decode.go new file mode 100644 index 00000000..366b92d4 --- /dev/null +++ b/internal/strictjson/decode.go @@ -0,0 +1,79 @@ +// Package strictjson decodes objects with an exact set of required, non-null fields. +package strictjson + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "slices" + "unicode/utf8" +) + +// ErrInvalid indicates invalid JSON, encoding, fields or destination field types. +var ErrInvalid = errors.New("invalid JSON object") + +// DecodeObject decodes one UTF-8 object with exactly the listed required fields. +// Duplicate, unknown, missing and null fields are rejected before unmarshaling. +// The destination must describe the supplied fields; this is not a general schema validator. +func DecodeObject(body []byte, target any, requiredFields ...string) error { + if !utf8.Valid(body) { + return ErrInvalid + } + if err := validateObject(body, requiredFields); err != nil { + return err + } + if err := json.Unmarshal(body, target); err != nil { + return ErrInvalid + } + return nil +} + +// validateObject enforces exact, unique, non-null required keys and one JSON value. +// All lab1 request properties are required; this is not a generic schema validator. +func validateObject(body []byte, requiredFields []string) error { + decoder := json.NewDecoder(bytes.NewReader(body)) + token, err := decoder.Token() + if err != nil || token != json.Delim('{') { + return ErrInvalid + } + seen := make(map[string]bool, len(requiredFields)) + for decoder.More() { + key, err := readObjectField(decoder, requiredFields, seen) + if err != nil { + return err + } + seen[key] = true + } + if token, err = decoder.Token(); err != nil || token != json.Delim('}') { + return ErrInvalid + } + if len(seen) != len(requiredFields) { + return ErrInvalid + } + var trailing any + if err := decoder.Decode(&trailing); err != io.EOF { + return ErrInvalid + } + return nil +} + +// readObjectField reads a known, unique, non-null JSON object field. +func readObjectField(decoder *json.Decoder, requiredFields []string, seen map[string]bool) (string, error) { + token, err := decoder.Token() + if err != nil { + return "", ErrInvalid + } + key, ok := token.(string) + if !ok || seen[key] || !slices.Contains(requiredFields, key) { + return "", ErrInvalid + } + var value json.RawMessage + if err := decoder.Decode(&value); err != nil { + return "", ErrInvalid + } + if bytes.Equal(bytes.TrimSpace(value), []byte("null")) { + return "", ErrInvalid + } + return key, nil +} diff --git a/internal/strictjson/decode_test.go b/internal/strictjson/decode_test.go new file mode 100644 index 00000000..5c3b4285 --- /dev/null +++ b/internal/strictjson/decode_test.go @@ -0,0 +1,52 @@ +package strictjson + +import ( + "errors" + "testing" +) + +type input struct { + // Name contains the only accepted field in these fixed-schema tests. + Name string `json:"name"` +} + +// TestDecodeObject checks each fixed-schema rule with a fresh destination. +func TestDecodeObject(t *testing.T) { + cases := []struct { + name string + body string + want string + wantErr error + }{ + {"Positive: Unicode preserved", `{"name":"Алиса 👋"}`, "Алиса 👋", nil}, + {"Negative: missing field", `{}`, "", ErrInvalid}, + {"Negative: unknown field", `{"name":"alice","extra":true}`, "", ErrInvalid}, + {"Negative: duplicate field", `{"name":"alice","name":"bob"}`, "", ErrInvalid}, + {"Negative: case mismatch", `{"Name":"alice"}`, "", ErrInvalid}, + {"Negative: null field", `{"name":null}`, "", ErrInvalid}, + {"Negative: wrong value type", `{"name":12}`, "", ErrInvalid}, + {"Negative: invalid UTF-8", "{\"name\":\"\xff\"}", "", ErrInvalid}, + {"Negative: array root", `[]`, "", ErrInvalid}, + {"Negative: unclosed object", `{"name":"alice"`, "", ErrInvalid}, + {"Negative: invalid value", `{"name":}`, "", ErrInvalid}, + {"Negative: invalid key", `{name:"alice"}`, "", ErrInvalid}, + {"Negative: trailing value", `{"name":"alice"} {}`, "", ErrInvalid}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Arrange. + var destination input + + // Act. + err := DecodeObject([]byte(tc.body), &destination, "name") + + // Assert. + if !errors.Is(err, tc.wantErr) { + t.Fatalf("error=%v, want=%v", err, tc.wantErr) + } + if destination.Name != tc.want { + t.Fatalf("decoded name=%q, want=%q", destination.Name, tc.want) + } + }) + } +} diff --git a/internal/valkey/admission.go b/internal/valkey/admission.go new file mode 100644 index 00000000..e0d3b8bd --- /dev/null +++ b/internal/valkey/admission.go @@ -0,0 +1,132 @@ +package valkey + +import ( + "context" + "fmt" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission" +) + +const ( + admissionWindow = time.Second + admissionLease = 30 * time.Second + releaseTimeout = time.Second +) + +// Budget defines a rate window and concurrent execution capacity. +type Budget struct { + // Rate is the maximum attempts per one-second window. + Rate int + // Slots is the maximum requests executing concurrently. + Slots int +} + +// Limits separates global, route-group and user budgets. +type Limits struct { + // Global covers every business request before authentication. + Global Budget + // Groups covers auth, read and write independently. + Groups map[string]Budget + // User covers all authenticated requests made by one account. + User Budget + // UserGroups limits each authenticated account within a route group. + UserGroups map[string]Budget +} + +// Limiter applies atomic local-shard decisions; global reservations precede user reservations. +type Limiter struct { + client *Client + limits Limits +} + +// NewLimiter validates independent rate and concurrency budgets. +func NewLimiter(client *Client, limits Limits) (*Limiter, error) { + if client == nil || limits.Global.Rate < 1 || limits.Global.Slots < 1 || limits.User.Rate < 1 || limits.User.Slots < 1 { + return nil, fmt.Errorf("client and positive budgets are required") + } + for _, group := range []string{"auth", "read", "write"} { + global := limits.Groups[group] + user := limits.UserGroups[group] + if global.Rate < 1 || global.Slots < 1 || user.Rate < 1 || user.Slots < 1 { + return nil, fmt.Errorf("positive budgets for every group are required") + } + } + groups := make(map[string]Budget, len(limits.Groups)) + userGroups := make(map[string]Budget, len(limits.UserGroups)) + for key, value := range limits.Groups { + groups[key] = value + } + for key, value := range limits.UserGroups { + userGroups[key] = value + } + limits.Groups = groups + limits.UserGroups = userGroups + return &Limiter{client: client, limits: limits}, nil +} + +// Enter atomically reserves two rate and slot budgets on one shard. +// Global admission precedes authentication; user admission follows verified identity. +func (l *Limiter) Enter(ctx context.Context, group, user string) (func(), error) { + groupBudget, ok := l.limits.Groups[group] + if !ok { + return nil, fmt.Errorf("unknown admission group") + } + totalBudget := l.limits.Global + node := l.client.coordinator + prefix := "admission:global" + if user != "" { + prefix = "admission:user:" + user + node = l.client.nodes[l.client.ring.Owner(prefix)] + totalBudget = l.limits.User + groupBudget = l.limits.UserGroups[group] + } + keys := []string{prefix + ":rate", prefix + ":slots", prefix + ":" + group + ":rate", prefix + ":" + group + ":slots"} + token := uuid.NewString() + ctx, cancel := context.WithTimeout(ctx, l.client.timeout) + defer cancel() + result, err := node.Eval(ctx, reserveScript, keys, token, admissionWindow.Milliseconds(), admissionLease.Milliseconds(), totalBudget.Rate, totalBudget.Slots, groupBudget.Rate, groupBudget.Slots).Int() + if err != nil { + return nil, err + } + if result == 1 { + return nil, admission.ErrRate + } + if result == 2 { + return nil, admission.ErrSlots + } + return func() { + releaseCtx, releaseCancel := context.WithTimeout(context.Background(), releaseTimeout) + defer releaseCancel() + // Failed release is bounded by the lease; tokens are never reused. + _ = node.Eval(releaseCtx, releaseScript, []string{keys[1], keys[3]}, token).Err() + }, nil +} + +// Redis TIME and one Lua operation make check-and-reserve indivisible within a shard. +const reserveScript = ` +local clock = redis.call('TIME') +local now = clock[1]*1000 + math.floor(clock[2]/1000) +for i=1,3,2 do + redis.call('ZREMRANGEBYSCORE',KEYS[i+1],'-inf',now) + local rate = tonumber(redis.call('GET',KEYS[i]) or '0') + local limitIndex = i==1 and 4 or 6 + if rate >= tonumber(ARGV[limitIndex]) then return 1 end + if redis.call('ZCARD',KEYS[i+1]) >= tonumber(ARGV[limitIndex+1]) then return 2 end +end +for i=1,3,2 do + local count = redis.call('INCR',KEYS[i]) + if count==1 then redis.call('PEXPIRE',KEYS[i],ARGV[2]) end + redis.call('ZADD',KEYS[i+1],now+tonumber(ARGV[3]),ARGV[1]) + redis.call('PEXPIRE',KEYS[i+1],ARGV[3]) +end +return 0 +` + +const releaseScript = ` +redis.call('ZREM',KEYS[1],ARGV[1]) +redis.call('ZREM',KEYS[2],ARGV[1]) +return 0 +` diff --git a/internal/valkey/cache.go b/internal/valkey/cache.go new file mode 100644 index 00000000..46d03567 --- /dev/null +++ b/internal/valkey/cache.go @@ -0,0 +1,42 @@ +package valkey + +import ( + "context" + "encoding/json" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +const profileTTL = 5 * time.Minute + +// GetProfile reads an immutable profile; corrupt values and outages are cache misses. +func (c *Client) GetProfile(ctx context.Context, id uuid.UUID) (dto.UserDTO, bool) { + ctx, cancel := context.WithTimeout(ctx, c.timeout) + defer cancel() + key := "profile:" + id.String() + value, err := c.nodes[c.ring.Owner(key)].Get(ctx, key).Bytes() + if err != nil { + return dto.UserDTO{}, false + } + var user dto.UserDTO + if json.Unmarshal(value, &user) != nil || user.ID != id { + return dto.UserDTO{}, false + } + return user, true +} + +// PutProfile populates the immutable profile cache with a bounded TTL. +func (c *Client) PutProfile(ctx context.Context, user dto.UserDTO) { + ctx, cancel := context.WithTimeout(ctx, c.timeout) + defer cancel() + value, err := json.Marshal(user) + if err != nil { + return + } + key := "profile:" + user.ID.String() + // Cache writes are best effort; PostgreSQL remains the source of truth. + _ = c.nodes[c.ring.Owner(key)].Set(ctx, key, value, profileTTL).Err() +} diff --git a/internal/valkey/client.go b/internal/valkey/client.go new file mode 100644 index 00000000..35a1a780 --- /dev/null +++ b/internal/valkey/client.go @@ -0,0 +1,113 @@ +// Package valkey implements sharded cache and admission infrastructure. +package valkey + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "sort" + "strings" + "time" + + "github.com/redis/go-redis/v9" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/hashring" +) + +const virtualNodes = 256 + +// Options bounds each independent Valkey connection pool. +type Options struct { + // Nodes maps stable shard identities to network addresses. + Nodes map[string]string + // Coordinator identifies the stable global admission shard. + Coordinator string + // Timeout bounds operations and pool acquisition. + Timeout time.Duration + // PoolSize bounds connections to each shard. + PoolSize int +} + +// Client owns a fixed topology; callers must drain before changing it. +type Client struct { + nodes map[string]*redis.Client + ring *hashring.Ring + coordinator *redis.Client + timeout time.Duration + topology string +} + +// New prepares lazy clients without opening network connections. +func New(options Options) (*Client, error) { + if len(options.Nodes) < 1 || options.PoolSize < 1 || options.Timeout <= 0 { + return nil, fmt.Errorf("valkey nodes, pool bound and timeout are required") + } + ids := make([]string, 0, len(options.Nodes)) + for id, address := range options.Nodes { + if address == "" { + return nil, fmt.Errorf("valkey address is required") + } + ids = append(ids, id) + } + ring, err := hashring.New(ids, virtualNodes) + if err != nil { + return nil, err + } + if _, ok := options.Nodes[options.Coordinator]; !ok { + return nil, fmt.Errorf("coordinator must identify a configured node") + } + sort.Strings(ids) + topologyHash := sha256.Sum256([]byte(strings.Join(ids, ","))) + client := &Client{nodes: make(map[string]*redis.Client), ring: ring, timeout: options.Timeout} + for id, address := range options.Nodes { + client.nodes[id] = redis.NewClient(&redis.Options{ + Addr: address, + PoolSize: options.PoolSize, + MaxActiveConns: options.PoolSize, + PoolTimeout: options.Timeout, + DialTimeout: options.Timeout, + ReadTimeout: options.Timeout, + WriteTimeout: options.Timeout, + ContextTimeoutEnabled: true, + MaxRetries: -1, + }) + } + client.topology = hex.EncodeToString(topologyHash[:]) + client.coordinator = client.nodes[options.Coordinator] + return client, nil +} + +// Ping checks every shard required for safe admission. +func (c *Client) Ping(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, c.timeout) + defer cancel() + for _, node := range c.nodes { + if err := node.Ping(ctx).Err(); err != nil { + return err + } + } + stored, err := c.coordinator.Eval(ctx, topologyScript, []string{"admission:topology"}, c.topology).Text() + if err != nil { + return err + } + if stored != c.topology { + return fmt.Errorf("valkey topology differs: stop admission and drain before changing the ring") + } + return nil +} + +const topologyScript = ` +redis.call('SET',KEYS[1],ARGV[1],'NX') +return redis.call('GET',KEYS[1]) +` + +// Close releases every connection pool owned by the client. +func (c *Client) Close() error { + var result error + for _, node := range c.nodes { + result = errors.Join(result, node.Close()) + } + return result +} diff --git a/internal/valkey/client_test.go b/internal/valkey/client_test.go new file mode 100644 index 00000000..70607e5b --- /dev/null +++ b/internal/valkey/client_test.go @@ -0,0 +1,247 @@ +package valkey + +import ( + "context" + "errors" + "os" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto" +) + +// testClient connects only to explicitly configured disposable Valkey shards. +func testClient(t *testing.T) *Client { + t.Helper() + address := os.Getenv("TEST_VALKEY_ADDRESS") + if address == "" { + t.Skip("TEST_VALKEY_ADDRESS is required for Valkey integration tests") + } + client, err := New(Options{Nodes: map[string]string{"test": address}, Coordinator: "test", PoolSize: 16, Timeout: time.Second}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := client.Close(); err != nil { + t.Error(err) + } + }) + if err := client.Ping(t.Context()); err != nil { + t.Fatal(err) + } + return client +} + +// testLimits builds independent small budgets for admission scenarios. +func testLimits() Limits { + return Limits{ + Global: Budget{Rate: 10000, Slots: 100}, + User: Budget{Rate: 1000, Slots: 3}, + Groups: map[string]Budget{ + "auth": {Rate: 100, Slots: 4}, + "read": {Rate: 1000, Slots: 50}, + "write": {Rate: 1000, Slots: 50}, + }, + UserGroups: map[string]Budget{ + "auth": {Rate: 10, Slots: 1}, + "read": {Rate: 100, Slots: 2}, + "write": {Rate: 100, Slots: 2}, + }, + } +} + +// TestPerUserSlotsAreAtomic verifies concurrent reservations cannot exceed the group budget. +func TestPerUserSlotsAreAtomic(t *testing.T) { + client := testClient(t) + limiter, err := NewLimiter(client, testLimits()) + if err != nil { + t.Fatal(err) + } + user := uuid.NewString() + var accepted atomic.Int32 + releases := make(chan func(), 30) + failures := make(chan error, 30) + var wg sync.WaitGroup + for range 30 { + wg.Go(func() { + release, err := limiter.Enter(t.Context(), "read", user) + if err == nil { + accepted.Add(1) + releases <- release + } else if !errors.Is(err, admission.ErrSlots) { + failures <- err + } + }) + } + wg.Wait() + close(releases) + close(failures) + for release := range releases { + release() + } + for err := range failures { + t.Error(err) + } + if accepted.Load() != 2 { + t.Fatalf("accepted %d, want exactly two", accepted.Load()) + } +} + +// TestUserGroupsHaveSeparateSlots verifies read saturation does not consume write-group capacity. +func TestUserGroupsHaveSeparateSlots(t *testing.T) { + client := testClient(t) + limiter, err := NewLimiter(client, testLimits()) + if err != nil { + t.Fatal(err) + } + user := uuid.NewString() + for range 2 { + release, err := limiter.Enter(t.Context(), "read", user) + if err != nil { + t.Fatal(err) + } + t.Cleanup(release) + } + release, err := limiter.Enter(t.Context(), "write", user) + if err != nil { + t.Fatal(err) + } + release() +} + +// TestUserRateSurvivesSlotRelease checks that release returns concurrency but not rate tokens. +func TestUserRateSurvivesSlotRelease(t *testing.T) { + client := testClient(t) + limits := testLimits() + limits.User.Rate = 1 + limiter, err := NewLimiter(client, limits) + if err != nil { + t.Fatal(err) + } + user := uuid.NewString() + release, err := limiter.Enter(t.Context(), "read", user) + if err != nil { + t.Fatal(err) + } + release() + if _, err := limiter.Enter(t.Context(), "read", user); !errors.Is(err, admission.ErrRate) { + t.Fatalf("rate budget reset after release: %v", err) + } +} + +// TestAdmissionRejectsUnavailableBackend verifies fail-closed behavior without network fallback. +func TestAdmissionRejectsUnavailableBackend(t *testing.T) { + client := testClient(t) + limiter, err := NewLimiter(client, testLimits()) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := limiter.Enter(ctx, "read", ""); err == nil { + t.Fatal("canceled backend operation admitted request") + } +} + +// TestGlobalAdmissionReleasesSlots verifies the coordinator path and release semantics. +func TestGlobalAdmissionReleasesSlots(t *testing.T) { + client := testClient(t) + limiter, err := NewLimiter(client, testLimits()) + if err != nil { + t.Fatal(err) + } + release, err := limiter.Enter(t.Context(), "read", "") + if err != nil { + t.Fatal(err) + } + release() +} + +// TestProfileRoundTrip checks storage and ownership of immutable cached profiles. +func TestProfileRoundTrip(t *testing.T) { + client := testClient(t) + user := dto.UserDTO{ID: uuid.New(), Username: "synthetic", DisplayName: "Test", CreatedAt: time.Now().UTC()} + client.PutProfile(t.Context(), user) + got, ok := client.GetProfile(t.Context(), user.ID) + if !ok || got.ID != user.ID || got.Username != user.Username { + t.Fatal("profile cache did not preserve account") + } +} + +// TestProfileMissHandlesCorruption verifies corrupt cache entries cannot impersonate another account. +func TestProfileMissHandlesCorruption(t *testing.T) { + client := testClient(t) + id := uuid.New() + key := "profile:" + id.String() + if err := client.nodes[client.ring.Owner(key)].Set(t.Context(), key, `{"ID":"00000000-0000-0000-0000-000000000000"}`, time.Minute).Err(); err != nil { + t.Fatal(err) + } + if _, ok := client.GetProfile(t.Context(), id); ok { + t.Fatal("corrupt profile accepted") + } +} + +// TestProfileBackendFailureIsMiss checks optional-cache fallback semantics. +func TestProfileBackendFailureIsMiss(t *testing.T) { + client := testClient(t) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, ok := client.GetProfile(ctx, uuid.New()); ok { + t.Fatal("failed cache read treated as hit") + } + client.PutProfile(ctx, dto.UserDTO{ID: uuid.New()}) + if err := client.Ping(ctx); err == nil { + t.Fatal("canceled readiness succeeded") + } +} + +// TestClientRejectsInvalidConfiguration covers configuration boundaries without opening sockets. +func TestClientRejectsInvalidConfiguration(t *testing.T) { + cases := []Options{ + {}, + {Nodes: map[string]string{"a": ""}, Coordinator: "a", PoolSize: 1, Timeout: time.Second}, + {Nodes: map[string]string{"": "localhost:6379"}, Coordinator: "", PoolSize: 1, Timeout: time.Second}, + {Nodes: map[string]string{"a": "localhost:6379"}, Coordinator: "b", PoolSize: 1, Timeout: time.Second}, + } + for index, options := range cases { + t.Run(string(rune('a'+index)), func(t *testing.T) { + if _, err := New(options); err == nil { + t.Fatal("invalid client options accepted") + } + }) + } +} + +// TestLimiterRejectsInvalidConfiguration verifies policy completeness. +func TestLimiterRejectsInvalidConfiguration(t *testing.T) { + if _, err := NewLimiter(nil, testLimits()); err == nil { + t.Fatal("nil client accepted") + } + client := testClient(t) + limits := testLimits() + delete(limits.Groups, "auth") + if _, err := NewLimiter(client, limits); err == nil { + t.Fatal("missing group accepted") + } + limiter, err := NewLimiter(client, testLimits()) + if err != nil { + t.Fatal(err) + } + if _, err := limiter.Enter(t.Context(), "unknown", ""); err == nil { + t.Fatal("unknown group accepted") + } +} + +// TestTopologyMismatchFailsClosed prevents replicas from silently splitting user budgets. +func TestTopologyMismatchFailsClosed(t *testing.T) { + client := testClient(t) + client.topology = "different-ring" + if err := client.Ping(t.Context()); err == nil { + t.Fatal("incompatible topology accepted") + } +} diff --git a/scripts/coverage.awk b/scripts/coverage.awk new file mode 100644 index 00000000..982f844f --- /dev/null +++ b/scripts/coverage.awk @@ -0,0 +1,35 @@ +# Aggregate covered statements once per merged block; keep files with no statements as N/A. +FNR == NR { + split($0, fields, "\t") + paths[fields[1]] = fields[2] + hashes[fields[1]] = fields[3] + executable[fields[1]] = fields[4] + next +} +/^mode:/ { next } +{ + file = $1 + sub(/:[^:]*$/, "", file) + if (!(file in paths)) { + print "unknown coverage source: " file > "/dev/stderr" + invalid = 1 + } + total[file] += $2 + if ($3 > 0) covered[file] += $2 +} +END { + print "{\"threshold_per_file\":90,\"files\":[" > summary + separator = "" + for (file in paths) { + percent = total[file] ? sprintf("%.8f", covered[file] * 100 / total[file]) : "null" + printf "%s{\"file\":\"%s\",\"statements\":%d,\"covered\":%d,\"percent\":%s,\"sha256\":\"%s\"}", separator, paths[file], total[file], covered[file], percent, hashes[file] > summary + separator = ",\n" + printf "%8s %s\n", (total[file] ? sprintf("%.2f%%", covered[file] * 100 / total[file]) : "N/A"), paths[file] + if (covered[file] * 100 < total[file] * 90 || (executable[file] && !total[file])) invalid = 1 + } + printf "\n],\"passed\":%s}\n", (invalid ? "false" : "true") > summary + if (invalid) { + print "FAIL: per-file coverage must reach 90%" > "/dev/stderr" + exit 1 + } +} diff --git a/scripts/coverage.sh b/scripts/coverage.sh new file mode 100755 index 00000000..56210675 --- /dev/null +++ b/scripts/coverage.sh @@ -0,0 +1,80 @@ +#!/bin/sh +# Measure unit and real-process coverage, enforcing 90% separately for each Go source file. +set -eu +cd "$(dirname "$0")/.." +GO=${GO:-go} +: "${DATABASE_URL:?Use an isolated test database}" "${VALKEY_SHARDS:?Use test shards}" +: "${TEST_DATABASE_URL:?Use an isolated test database}" "${TEST_VALKEY_ADDRESS:?Use a test shard}" +export APP_PORT=${COVERAGE_PORT:-18080} +export LOG_LEVEL=error +server_pid= +watchdog_pid= +mkdir -p coverage +run_dir=$(mktemp -d "$PWD/coverage/run.XXXXXX") +cleanup() { + if [ -n "$server_pid" ]; then kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; fi + if [ -n "$watchdog_pid" ]; then kill "$watchdog_pid" 2>/dev/null || true; wait "$watchdog_pid" 2>/dev/null || true; fi + rm -rf "$run_dir" +} +trap cleanup EXIT +trap 'exit 129' HUP +trap 'exit 130' INT +trap 'exit 143' TERM +mkdir "$run_dir/process" +"$GO" build -race -cover -covermode=atomic -coverpkg=./... -o "$run_dir/server" ./cmd/server +"$GO" test -race -coverpkg=./... -coverprofile="$run_dir/unit.out" ./... +export GOCOVERDIR="$run_dir/process" +if "$run_dir/server" unknown >"$run_dir/server-invalid.log" 2>&1; then + echo 'server accepted an unknown command' >&2 + exit 1 +else + test "$?" -eq 1 +fi +"$run_dir/server" >"$run_dir/server.log" 2>&1 & +server_pid=$! +ready=false +for attempt in $(seq 1 60); do + kill -0 "$server_pid" 2>/dev/null || { cat "$run_dir/server.log"; exit 1; } + if curl --fail --silent --max-time 1 "http://localhost:$APP_PORT/health/ready" >/dev/null; then ready=true; break; fi + sleep .25 +done +$ready || { cat "$run_dir/server.log"; exit 1; } +"$run_dir/server" healthcheck +"${PYTHON:-python3}" tests/smoke.py --base-url "http://localhost:$APP_PORT" +kill -TERM "$server_pid" +# Bound the real-process shutdown check; a forced kill makes wait fail. +(sleep 12; kill -KILL "$server_pid" 2>/dev/null || true) & +watchdog_pid=$! +wait "$server_pid" +server_pid= +kill "$watchdog_pid" 2>/dev/null || true +wait "$watchdog_pid" 2>/dev/null || true +watchdog_pid= +unset GOCOVERDIR +"$GO" tool covdata textfmt -i="$run_dir/process" -o="$run_dir/process.out" +awk ' +/^mode:/ { if ($0 != "mode: atomic") exit 1; next } +{ + if (($1 in statements) && statements[$1] != $2) exit 1; + statements[$1] = $2; hits[$1] += $3 +} +END { + print "mode: atomic"; + for (block in statements) print block, statements[block], hits[block] +}' "$run_dir/unit.out" "$run_dir/process.out" > coverage/coverage.out +"$GO" list -f '{{.ImportPath}} {{.Dir}} {{join .GoFiles ","}}' ./... > "$run_dir/packages.txt" +: > "$run_dir/inventory.tsv" +while read -r import_path directory names; do + old_ifs=$IFS + IFS=, + for name in $names; do + checksum=$(shasum -a 256 "$directory/$name") + checksum=${checksum%% *} + relative=${directory#"$PWD/"}/$name + executable=$(awk '/^func[ (]/ {found=1} END {print found+0}' "$directory/$name") + printf '%s\t%s\t%s\t%s\n' "$import_path/$name" "$relative" "$checksum" "$executable" >> "$run_dir/inventory.tsv" + done + IFS=$old_ifs +done < "$run_dir/packages.txt" +awk -v summary=coverage/summary.json -f scripts/coverage.awk "$run_dir/inventory.tsv" coverage/coverage.out +"$GO" version > coverage/go-version.txt diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 00000000..af9529b1 --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Create lab credentials once, outside Helm values and release history. +set -eu +: "${KUBE_CONTEXT:=dev}" "${NAMESPACE:=highload-applications}" +: "${REGISTRY:=asisti.registry.twcstorage.ru}" "${REGISTRY_USER:=token}" +: "${REGISTRY_TOKEN_FILE:=$HOME/.secrets/twc-registry-token}" +test -s "$REGISTRY_TOKEN_FILE" || { echo 'Registry token file is missing or empty' >&2; exit 1; } +umask 077 +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +kubectl --context "$KUBE_CONTEXT" create namespace "$NAMESPACE" --dry-run=client -o yaml | kubectl --context "$KUBE_CONTEXT" apply -f - +if ! kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get secret messenger-secrets >/dev/null 2>&1; then + openssl rand -hex 32 | tr -d '\n' > "$work/postgres-password" + printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable' "$(cat "$work/postgres-password")" > "$work/database-url" + kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" create secret generic messenger-secrets --from-file="$work/postgres-password" --from-file="$work/database-url" +fi +jq -n --arg registry "$REGISTRY" --arg user "$REGISTRY_USER" --rawfile token "$REGISTRY_TOKEN_FILE" \ + '{auths:{($registry):{auth:(($user+":"+($token | sub("[\\r\\n]+$"; "")))|@base64)}}}' > "$work/config.json" +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" create secret generic registry-pull \ + --type=kubernetes.io/dockerconfigjson --from-file=".dockerconfigjson=$work/config.json" \ + --dry-run=client -o yaml | kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" apply -f - diff --git a/scripts/port-forward.sh b/scripts/port-forward.sh new file mode 100755 index 00000000..84dfa080 --- /dev/null +++ b/scripts/port-forward.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Reconnect the loopback tunnel after the API pod is replaced during restart tests. +set -eu +: "${KUBE_CONTEXT:=dev}" "${NAMESPACE:=highload-applications}" +LOCAL_PORT=${LOCAL_PORT:-8080} +child= +cleanup() { + if [ -n "$child" ]; then + kill "$child" 2>/dev/null || true + wait "$child" 2>/dev/null || true + fi + exit 0 +} +trap cleanup INT TERM +while :; do + kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" port-forward service/api "$LOCAL_PORT:8080" --address 127.0.0.1 & + child=$! + wait "$child" || true + child= + sleep 1 +done diff --git a/scripts/research.sh b/scripts/research.sh new file mode 100755 index 00000000..4728cc61 --- /dev/null +++ b/scripts/research.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# Run the SQL experiment in a fresh disposable container, never the deployed DB. +set -eu +cd "$(dirname "$0")/.." +mkdir -p evidence +work=$(mktemp -d) +container= +cleanup() { + if [ -n "$container" ]; then docker rm -f "$container" >/dev/null; fi + rm -rf "$work" +} +trap cleanup EXIT +container=$(docker run -d --label purpose=lab2-research --memory=512m --cpus=1 -e POSTGRES_HOST_AUTH_METHOD=trust postgres:17.6-alpine) +for attempt in $(seq 1 60); do + if docker exec "$container" pg_isready -U postgres >/dev/null 2>&1; then break; fi + sleep 1 +done +docker exec "$container" createdb -U postgres messenger +docker exec -i "$container" psql -X -v ON_ERROR_STOP=1 -U postgres -d messenger < internal/store/postgres/migrations/001_initial.sql > /dev/null +docker cp student-tests/plans.sql "$container:/tmp/plans.sql" >/dev/null +{ + date -u '+UTC: %Y-%m-%dT%H:%M:%SZ' + echo 'Hypothesis: composite index improves late-page reads, with additional write cost.' + echo '100000 rows, distribution 90/9/1%; three reads and 1000-row rollback writes per index.' + echo 'Limits: 1 CPU, 512MiB; single local Docker instance; no concurrent writes or PITR.' + docker inspect --format 'Image: {{.Image}}' "$container" + git ls-files --cached --others --exclude-standard cmd internal student-tests/research.sql student-tests/plans.sql scripts/research.sh | sort | while read -r file; do shasum -a 256 "$file"; done + docker exec -i "$container" psql -XAt -v ON_ERROR_STOP=1 -U postgres -d messenger < student-tests/research.sql +} > evidence/sql-research-helm.txt +# Use the actual schema, all table contents, and a fresh target database. +query="SELECT count(*),md5(string_agg(id||':'||chat_id||':'||sender_id||':'||text||':'||created_at,',' ORDER BY id)) FROM messages" +docker exec "$container" psql -XAt -U postgres -d messenger -c "$query" > "$work/before" +{ time docker exec "$container" pg_dump -U postgres -d messenger --no-owner --no-acl > "$work/dump.sql"; } 2>> evidence/sql-research-helm.txt +docker exec "$container" createdb -U postgres restored +{ time docker exec -i "$container" psql -X -v ON_ERROR_STOP=1 -U postgres -d restored < "$work/dump.sql" > /dev/null; } 2>> evidence/sql-research-helm.txt +docker exec "$container" psql -XAt -U postgres -d restored -c "$query" > "$work/after" +diff -u "$work/before" "$work/after" +{ + echo 'PASS: restore row count and checksum match' + cat "$work/after" + wc -c < "$work/dump.sql" + docker exec "$container" psql -X -U postgres -d restored -c "SELECT id,text FROM messages WHERE id IN(md5('1')::uuid,md5('50000')::uuid,md5('100000')::uuid) ORDER BY id" +} >> evidence/sql-research-helm.txt +echo 'PASS: evidence/sql-research-helm.txt' diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..6a56d3da --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Restart only this lab's API and persistent stores, retaining every PVC. +set -eu +: "${KUBE_CONTEXT:=dev}" "${NAMESPACE:=highload-applications}" +replicas=$(kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get deployment api -o jsonpath='{.spec.replicas}') +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" scale deployment/api --replicas=0 +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" wait --for=delete pod -l app=api --timeout=60s +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" rollout restart statefulset/postgres statefulset/valkey +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" rollout status statefulset/postgres --timeout=120s +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" rollout status statefulset/valkey --timeout=120s +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" scale deployment/api --replicas="$replicas" +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" rollout status deployment/api --timeout=120s diff --git a/scripts/scale-shards.sh b/scripts/scale-shards.sh new file mode 100755 index 00000000..8cdbbe8c --- /dev/null +++ b/scripts/scale-shards.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Change the ring only after all API pods and their leases have drained. +set -eu +cd "$(dirname "$0")/.." +: "${KUBE_CONTEXT:=dev}" "${NAMESPACE:=highload-applications}" "${RELEASE:=lab2}" +: "${SHARDS:?Set SHARDS=2 or SHARDS=3}" +case "$SHARDS" in 2|3) ;; *) echo 'SHARDS must be 2 or 3' >&2; exit 2 ;; esac +# Keep the desired replica count explicit so an interrupted run can resume from zero. +: "${API_REPLICAS:=1}" +helm upgrade "$RELEASE" charts/messenger --kube-context "$KUBE_CONTEXT" -n "$NAMESPACE" --reuse-values --set api.replicas=0 --wait --timeout 180s +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" wait --for=delete pod -l app=api --timeout=60s +# Maximum lease is 30 seconds; the rate window is one second. +sleep 31 +helm upgrade "$RELEASE" charts/messenger --kube-context "$KUBE_CONTEXT" -n "$NAMESPACE" --reuse-values --set api.replicas=0 --set "valkey.shards=$SHARDS" --wait --timeout 180s +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" exec valkey-0 -- valkey-cli DEL admission:topology +helm upgrade "$RELEASE" charts/messenger --kube-context "$KUBE_CONTEXT" -n "$NAMESPACE" --reuse-values --set "api.replicas=$API_REPLICAS" --wait --timeout 180s +printf 'Ring updated. Set valkey.shards=%s in your values file before the next make deploy.\n' "$SHARDS" diff --git a/scripts/test-faults.sh b/scripts/test-faults.sh new file mode 100755 index 00000000..b80a7e0c --- /dev/null +++ b/scripts/test-faults.sh @@ -0,0 +1,112 @@ +#!/bin/sh +# Exercise real dependency outages on disposable containers; never target the dev cluster. +set -eu +cd "$(dirname "$0")/.." +umask 077 +work=$(mktemp -d) +name="lab2-fault-$(basename "$work" | tr '[:upper:].' '[:lower:]-')" +containers= +cleanup() { + for container in $containers; do + docker unpause "$container" >/dev/null 2>&1 || true + docker rm -f "$container" >/dev/null 2>&1 || true + done + docker network rm "$name" >/dev/null 2>&1 || true + docker image rm "$name" >/dev/null 2>&1 || true + rm -rf "$work" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +printf 'UTC %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" +git rev-parse HEAD +shasum -a 256 internal/store/postgres/*.go internal/service/errors.go internal/store/interface.go internal/controller/http/fiber/public_errors.go scripts/test-faults.sh +# Build the working tree, including uncommitted fixes, without publishing an image. +docker build -q -t "$name" . > "$work/build.txt" +docker network create "$name" >/dev/null +pg=$(docker run -d --network "$name" --network-alias postgres -e POSTGRES_PASSWORD=synthetic-fault-password -e POSTGRES_DB=messenger postgres:17.6-alpine) +containers="$pg" +cache=$(docker run -d --network "$name" --network-alias valkey valkey/valkey:8.1.3-alpine) +containers="$containers $cache" +for attempt in $(seq 1 60); do + if docker exec "$pg" pg_isready -U postgres >/dev/null 2>&1; then break; fi + sleep 1 + done +api=$(docker run -d --network "$name" -p 127.0.0.1::8080 \ + -e DATABASE_URL=postgres://postgres:synthetic-fault-password@postgres:5432/messenger?sslmode=disable \ + -e VALKEY_SHARDS=shard0=valkey:6379 -e VALKEY_COORDINATOR=shard0 \ + -e DEPENDENCY_TIMEOUT_MS=500 -e LOG_LEVEL=error "$name") +containers="$containers $api" +base="http://$(docker port "$api" 8080/tcp)" +: > "$work/anonymous" +wait_ready() { + for attempt in $(seq 1 60); do + if curl -fsS --max-time 2 "$base/health/ready" >/dev/null 2>&1; then return; fi + sleep 1 + done + echo 'FAIL: API did not recover within 60 seconds' >&2 + exit 1 +} +# Credentials remain in private temporary curl config files, never in evidence or argv. +request() { + method=$1; path=$2; expected=$3; auth=$4 + shift 4 + result=$(curl -sS --max-time 3 --config "$work/$auth" -X "$method" \ + -H 'Content-Type: application/json' -o "$work/response" \ + -w '%{http_code} %{time_total}' "$base$path" "$@") + status=${result%% *} + elapsed=${result#* } + if [ "$status" != "$expected" ]; then + printf 'FAIL: %s %s expected=%s actual=%s\n' "$method" "$path" "$expected" "$status" >&2 + exit 1 + fi +} +assert_error() { + jq -e --arg code "$1" '.error.code == $code and (.error.request_id | type == "string") and (has("items") | not)' "$work/response" >/dev/null + if rg -qi 'postgres|synthetic-fault-password|dial tcp|SELECT |SQLSTATE|redis|valkey|token_hash' "$work/response"; then + echo 'FAIL: internal dependency details exposed' >&2 + exit 1 + fi +} +wait_ready +request POST /api/v1/users 201 anonymous --data '{"username":"fault_actor","display_name":"Synthetic","password":"synthetic-user-password"}' +user=$(jq -er .id "$work/response") +printf 'header = "Authorization: Basic %s"\n' "$(printf 'fault_actor:synthetic-user-password' | openssl base64 -A)" > "$work/basic" +request POST /api/v1/auth/sessions 201 basic +jq -er '"header = \"Authorization: Bearer " + .token + "\""' "$work/response" > "$work/bearer" +printf 'header = "X-User-Id: %s"\n' "$user" > "$work/spoofed" +printf 'header = "Authorization: Bearer malformed"\n' > "$work/malformed" +printf 'header = "Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"\n' > "$work/unknown" +request POST /api/v1/chats 201 bearer --data "{\"title\":\"Synthetic fault chat\",\"member_ids\":[\"$user\"]}" +chat=$(jq -er .id "$work/response") +history="/api/v1/chats/$chat/messages" +request POST "$history" 201 bearer --data '{"text":"confirmed before outage"}' +cp "$work/response" "$work/message" +request GET "$history" 200 bearer +for dependency in "$pg" "$cache"; do + if [ "$dependency" = "$pg" ]; then label=postgres; else label=valkey; fi + for fault in stop pause; do + docker "$fault" "$dependency" >/dev/null + request GET "$history" 503 bearer + assert_error unavailable + printf 'PASS: %s %s authenticated history => 503 unavailable (%ss)\n' "$label" "$fault" "$elapsed" + request GET /health/ready 503 anonymous + assert_error unavailable + request GET /health/live 200 anonymous + for auth in anonymous spoofed malformed unknown; do + expected=503 + if [ "$label" = postgres ] && [ "$auth" != unknown ]; then expected=401; fi + request GET "$history" "$expected" "$auth" + if [ "$expected" = 401 ]; then assert_error unauthorized; else assert_error unavailable; fi + done + printf 'PASS: %s %s rejects anonymous/spoofed/malformed/unknown identity; liveness=200 readiness=503\n' "$label" "$fault" + if [ "$fault" = stop ]; then docker start "$dependency" >/dev/null; else docker unpause "$dependency" >/dev/null; fi + wait_ready + request GET "$history" 200 bearer + jq -e --slurpfile message "$work/message" '.items == $message' "$work/response" >/dev/null + request GET "$history" 401 anonymous + assert_error unauthorized + printf 'PASS: %s %s recovery preserves the original session and message\n' "$label" "$fault" + done + done +printf 'PASS: real dependency fault scenarios completed\n' diff --git a/student-tests/README.md b/student-tests/README.md new file mode 100644 index 00000000..a477fa34 --- /dev/null +++ b/student-tests/README.md @@ -0,0 +1,13 @@ +# Собственные проверки + +Go-тесты расположены рядом с кодом. `quality_test.go` проверяет документацию объявлений и направление импортов. PostgreSQL-тесты используют реальные запросы и изолированные схемы; Valkey-тесты проверяют атомарные бюджеты, группы, cache hit/miss и topology mismatch. + +Для unit tests: `make test-student`. Для всех интеграционных проверок задать переменные из [REPORT](../REPORT.md). `make coverage` запускает race detector и настоящий инструментированный процесс, проверяет публичный HTTP smoke и SIGTERM, затем применяет порог ≥90% statements отдельно к каждому Go-файлу. + +Тестовые controller fixtures заменяют только Authentication/Admission/Readiness: fixture Bearer равен UUID для изоляции бизнес-сценариев. Production Authentication всегда использует случайный токен и PostgreSQL; это отдельно проверяют unit tests authentication и настоящие HTTP smoke/expiry/persistence. Fixture токены не являются доступным режимом приложения. + +`make research` запускает SQL из `research.sql` и `plans.sql` в новом временном контейнере, с ограничениями 1 CPU и 512 MiB. Исследуемые запросы находятся непосредственно в SQL, shell отвечает только за запуск PostgreSQL и dump/restore. + +`make test-faults` — воспроизводимый HTTP-сценарий реальных отказов PostgreSQL и Valkey. Нужны Docker, curl, jq, rg, OpenSSL и shasum. Скрипт собирает текущий код в локальный образ, создаёт отдельную Docker-сеть и временные контейнеры. Каждый backend по очереди останавливается и приостанавливается (`stop`/`pause`). Проверяются 503/unavailable с действительным токеном, ограничение ожидания 3 секундами при timeout зависимости 500 мс, readiness=503, liveness=200, отсутствие доступа без токена, по X-User-Id, с повреждённым и неизвестным Bearer. После каждого восстановления прежняя сессия читает подтверждённое сообщение без повторного входа. Секреты находятся только во временных файлах; вывод не содержит токенов или тел сообщений. Ресурсы удаляются через trap, dev-кластер не используется. + +Свежий результат: [fault-regression.txt](../evidence/fault-regression.txt). Старые проверки в [dependencies.json](../evidence/dependencies.json) остаются историческими измерениями; текущий сценарий не зависит от удалённой Python-обвязки. TTL отдельно проверяется Go-тестами. diff --git a/student-tests/plans.sql b/student-tests/plans.sql new file mode 100644 index 00000000..9e1ea28f --- /dev/null +++ b/student-tests/plans.sql @@ -0,0 +1,16 @@ +-- Repeat the same read and rolled-back write three times for each index. +SELECT 'EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) +SELECT id,chat_id,sender_id,text,created_at FROM messages +WHERE chat_id=md5(''1'')::uuid +AND (created_at,id)>(''2026-01-01Z''::timestamptz+85000*interval ''1 microsecond'',md5(''85000'')::uuid) +ORDER BY created_at,id LIMIT 51; +BEGIN; +EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) +INSERT INTO messages +SELECT md5(n::text)::uuid,md5(''1'')::uuid, +''11111111-1111-4111-8111-111111111111'',''new-synthetic-''||n, +''2026-01-01Z''::timestamptz+n*interval ''1 microsecond'' +FROM generate_series(100001,101000) n; +ROLLBACK;' +FROM generate_series(1,3) +\gexec diff --git a/student-tests/quality_test.go b/student-tests/quality_test.go new file mode 100644 index 00000000..dcbfecc5 --- /dev/null +++ b/student-tests/quality_test.go @@ -0,0 +1,125 @@ +// Package quality checks source-level conventions required by the lab implementation. +package quality + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "strconv" + "strings" + "testing" +) + +// TestExportedDocumentation checks functions, types, constants, fields and interface methods. +func TestExportedDocumentation(t *testing.T) { + visitProductionFiles(t, func(path string, file *ast.File) { + ast.Inspect(file, func(node ast.Node) bool { + switch declaration := node.(type) { + case *ast.FuncDecl: + if declaration.Doc == nil || !strings.HasPrefix(strings.TrimSpace(declaration.Doc.Text()), declaration.Name.Name+" ") { + t.Errorf("%s: function %s needs a prefixed doc comment", path, declaration.Name.Name) + } + case *ast.GenDecl: + for _, spec := range declaration.Specs { + switch spec := spec.(type) { + case *ast.TypeSpec: + doc := spec.Doc + if doc == nil { + doc = declaration.Doc + } + requireDoc(t, path, spec.Name, doc) + case *ast.ValueSpec: + doc := spec.Doc + if doc == nil { + doc = declaration.Doc + } + for _, name := range spec.Names { + requireDoc(t, path, name, doc) + } + } + } + case *ast.StructType: + for _, field := range declaration.Fields.List { + for _, name := range field.Names { + requireDoc(t, path, name, field.Doc) + } + } + case *ast.InterfaceType: + for _, method := range declaration.Methods.List { + for _, name := range method.Names { + requireDoc(t, path, name, method.Doc) + } + } + } + return true + }) + }) +} + +// requireDoc checks that an exported declaration has a correctly prefixed doc comment. +func requireDoc(t *testing.T, path string, name *ast.Ident, doc *ast.CommentGroup) { + t.Helper() + if !name.IsExported() { + return + } + if doc == nil || !strings.HasPrefix(strings.TrimSpace(doc.Text()), name.Name+" ") { + t.Errorf("%s: %s needs a Go doc comment starting with its name", path, name.Name) + } +} + +// TestDependencyDirection prevents concrete infrastructure leaking into higher layers. +func TestDependencyDirection(t *testing.T) { + visitProductionFiles(t, func(path string, file *ast.File) { + normalized := filepath.ToSlash(path) + for _, dependency := range file.Imports { + imported, err := strconv.Unquote(dependency.Path.Value) + if err != nil { + t.Fatal(err) + } + var forbidden []string + switch { + case strings.Contains(normalized, "internal/service/"): + forbidden = []string{"net/http", "github.com/gofiber/", "/internal/controller", "/internal/store/memory", "/internal/store/postgres", "/internal/valkey", "/internal/config", "go.lab260.ru/fielderr"} + case strings.Contains(normalized, "internal/admission/"), strings.Contains(normalized, "internal/strictjson/"): + forbidden = []string{"net/http", "github.com/gofiber/", "/internal/"} + case strings.Contains(normalized, "internal/cursor/"): + forbidden = []string{"net/http", "github.com/gofiber/", "/internal/service", "/internal/store", "/internal/controller", "/internal/model"} + case strings.Contains(normalized, "internal/store/"): + forbidden = []string{"net/http", "github.com/gofiber/", "/internal/controller", "/internal/service"} + case strings.Contains(normalized, "internal/controller/"): + forbidden = []string{"/internal/service/production", "/internal/store"} + } + for _, fragment := range forbidden { + if strings.Contains(imported, fragment) { + t.Errorf("%s: forbidden dependency %s", path, imported) + } + } + } + }) +} + +// visitProductionFiles parses application Go files and visits their syntax trees. +func visitProductionFiles(t *testing.T, visit func(string, *ast.File)) { + t.Helper() + for _, root := range []string{"../cmd", "../internal"} { + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + file, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ParseComments) + if err != nil { + return err + } + visit(path, file) + return nil + }) + if err != nil { + t.Fatal(err) + } + } +} diff --git a/student-tests/research.sql b/student-tests/research.sql new file mode 100644 index 00000000..c43c67b1 --- /dev/null +++ b/student-tests/research.sql @@ -0,0 +1,26 @@ +-- Isolated database: actual application schema and a deliberately skewed history. +\set ON_ERROR_STOP on +\timing on +SELECT version(); +INSERT INTO users(id,username,display_name,password_hash) +VALUES('11111111-1111-4111-8111-111111111111','research','Synthetic','not-a-login-hash'); +INSERT INTO chats(id,title) +SELECT md5(n::text)::uuid,'Synthetic '||n FROM generate_series(1,3) n; +INSERT INTO chat_members(chat_id,user_id) +SELECT id,'11111111-1111-4111-8111-111111111111' FROM chats; +INSERT INTO messages(id,chat_id,sender_id,text,created_at) +SELECT md5(n::text)::uuid, + md5((CASE WHEN n<=90000 THEN 1 WHEN n<=99000 THEN 2 ELSE 3 END)::text)::uuid, + '11111111-1111-4111-8111-111111111111','synthetic-'||n, + '2026-01-01Z'::timestamptz+n*interval '1 microsecond' +FROM generate_series(1,100000) AS n; +DROP INDEX messages_history; +CREATE INDEX candidate ON messages(chat_id); +\echo 'VARIANT: chat_only' +ANALYZE messages; +\i /tmp/plans.sql +DROP INDEX candidate; +CREATE INDEX candidate ON messages(chat_id,created_at,id); +\echo 'VARIANT: history_keyset' +ANALYZE messages; +\i /tmp/plans.sql