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 d32b9be0..e824eb8b 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +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 -API_REPLICAS=2 -IDEMPOTENCY_TTL_SECONDS=86400 +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 5d86d171..cf02b534 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,10 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +.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 @@ -25,6 +25,59 @@ 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) -test-failover: - @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) - $(PYTHON) tests/resilience.py --mode failover --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 c2679005..8dd58bcf 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,3 @@ -# Отчёт — лабораторная 3 +# Базовое состояние -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO - -## Запуск из чистого clone - -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. - -## Архитектура и решения - -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. - -## Доказательства критериев - -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. - -## Эксперименты и отказы - -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. - -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | - -## Ограничения и следующие шаги - -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Перенесена собственная реализация lab2 из коммита 8173f70. Контракт и публичные проверки lab3 сохранены. Требования lab3 на этом этапе ещё не реализованы. 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..8555b539 --- /dev/null +++ b/cmd/server/app.go @@ -0,0 +1,97 @@ +package main + +import ( + "time" + + "go.uber.org/fx" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/controller" + fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/controller/http/fiber" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/password" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service/production" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store/postgres" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..ac283300 --- /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/mtusi2026lab3/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..a0cbf386 --- /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/mtusi2026lab3/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..af07c237 --- /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/mtusi2026lab3/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..3aab61bb --- /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/mtusi2026lab3/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..5cf5674b --- /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/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service/authentication" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store/postgres" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..efe9660b --- /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/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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/go.mod b/go.mod new file mode 100644 index 00000000..388ca407 --- /dev/null +++ b/go.mod @@ -0,0 +1,36 @@ +module gitea.privcloud.tech/vlad_marlo/mtusi2026lab3 + +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..88e4d383 --- /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/mtusi2026lab3/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..52795d4d --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..a541ae39 --- /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/mtusi2026lab3/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/controller" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..09a1ea4e --- /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/mtusi2026lab3/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service/production" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..5ab57a37 --- /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/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..e183f8b3 --- /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/mtusi2026lab3/internal/model/http" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..1cde1271 --- /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/mtusi2026lab3/internal/model/http" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..7212eb67 --- /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/mtusi2026lab3/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..e5b5c4e6 --- /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/mtusi2026lab3/internal/model/dto" + httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..c800b21a --- /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/mtusi2026lab3/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..3ceae8c8 --- /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/mtusi2026lab3/internal/model/dto" + httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..9efe0664 --- /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/mtusi2026lab3/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..4bd2f817 --- /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/mtusi2026lab3/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..653205db --- /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/mtusi2026lab3/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..416974c3 --- /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/mtusi2026lab3/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..d26ff3f6 --- /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/mtusi2026lab3/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..57a96c93 --- /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/mtusi2026lab3/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..a1a76b99 --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service/production" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..3a8d8ca7 --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..2eee452e --- /dev/null +++ b/internal/service/cache.go @@ -0,0 +1,17 @@ +package service + +import ( + "context" + + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..17850d82 --- /dev/null +++ b/internal/service/cursor.go @@ -0,0 +1,12 @@ +package service + +import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..d15e0af8 --- /dev/null +++ b/internal/service/errors.go @@ -0,0 +1,23 @@ +package service + +import ( + "errors" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..0baac14a --- /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/mtusi2026lab3/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..6510a335 --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..fb6e97d5 --- /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/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..56ef0e52 --- /dev/null +++ b/internal/service/production/chats.go @@ -0,0 +1,47 @@ +package production + +import ( + "context" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..b325fd42 --- /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/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..f2085395 --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..772e7226 --- /dev/null +++ b/internal/service/production/creation.go @@ -0,0 +1,49 @@ +package production + +import ( + "github.com/google/uuid" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..15dc4035 --- /dev/null +++ b/internal/service/production/errors.go @@ -0,0 +1,23 @@ +package production + +import ( + "errors" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..e067de6e --- /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/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..3c1437b9 --- /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/mtusi2026lab3/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..4885b04b --- /dev/null +++ b/internal/service/production/messages.go @@ -0,0 +1,38 @@ +package production + +import ( + "context" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..e54fe8e8 --- /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/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..24eaf706 --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..4ff66f2c --- /dev/null +++ b/internal/service/production/pages.go @@ -0,0 +1,49 @@ +package production + +import ( + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..0638f7ce --- /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/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..c5326b6e --- /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/mtusi2026lab3/internal/cursor" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..6861ea45 --- /dev/null +++ b/internal/service/production/pagination_test.go @@ -0,0 +1,74 @@ +package production + +import ( + "errors" + "testing" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..c069823a --- /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/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..461fc3cf --- /dev/null +++ b/internal/service/production/service_test.go @@ -0,0 +1,39 @@ +package production + +import ( + "testing" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..9db4b1c0 --- /dev/null +++ b/internal/service/production/users.go @@ -0,0 +1,47 @@ +package production + +import ( + "context" + "errors" + + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..70f91a6f --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..84d12bd8 --- /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/mtusi2026lab3/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..90ef47a1 --- /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/mtusi2026lab3/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..715e266d --- /dev/null +++ b/internal/store/memory/capacity.go @@ -0,0 +1,38 @@ +package memory + +import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..b0a7501d --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..a433cb25 --- /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/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..a56eb98c --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..9550729e --- /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/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..a3576b1d --- /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/mtusi2026lab3/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..9df013c6 --- /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/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..2d516760 --- /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/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..bae9971e --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..a2dfaccc --- /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/mtusi2026lab3/internal/config" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..8946c12d --- /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/mtusi2026lab3/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..e326ee84 --- /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/mtusi2026lab3/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..1b7ba212 --- /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/mtusi2026lab3/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..12968062 --- /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/mtusi2026lab3/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..fdda0eef --- /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/mtusi2026lab3/internal/model/dto" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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..3cac3225 --- /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/mtusi2026lab3/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..28cddc45 --- /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/mtusi2026lab3/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..a3a407a9 --- /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/mtusi2026lab3/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..93eb629f --- /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/mtusi2026lab3/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..5abe3992 --- /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/mtusi2026lab3/internal/admission" + "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/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/experiment.sh b/scripts/experiment.sh new file mode 100755 index 00000000..31554c23 --- /dev/null +++ b/scripts/experiment.sh @@ -0,0 +1,27 @@ +#!/bin/sh +# Compare controlled replica/resource budgets, then restore the normal HPA configuration. +set -eu +cd "$(dirname "$0")/.." +: "${KUBE_CONTEXT:=dev}" "${NAMESPACE:=highload-applications}" "${RELEASE:=lab3}" +: "${DURATION:=30}" "${VUS:=32}" +run_id=$(date -u +%Y%m%d%H%M%S) +export KUBE_CONTEXT NAMESPACE DURATION VUS +mkdir -p evidence +restore() { + helm upgrade "$RELEASE" charts/messenger --kube-context "$KUBE_CONTEXT" -n "$NAMESPACE" -f charts/messenger/values.yaml --wait --wait-for-jobs --timeout 240s +} +trap restore EXIT +printf 'profile,run,replicas,cpu_millicores_per_replica,memory_mib_per_replica,pool\n' > evidence/scaling-profiles.csv +for profile in fixed1 fixed2 fixed4 growing1 growing2 growing4; do + case "$profile" in + fixed1) replicas=1; cpu=1000; memory=512 ;; + fixed2) replicas=2; cpu=500; memory=256 ;; + fixed4) replicas=4; cpu=250; memory=128 ;; + growing1) replicas=1; cpu=250; memory=128 ;; + growing2) replicas=2; cpu=250; memory=128 ;; + growing4) replicas=4; cpu=250; memory=128 ;; + esac + helm upgrade "$RELEASE" charts/messenger --kube-context "$KUBE_CONTEXT" -n "$NAMESPACE" --reuse-values --set autoscaling.enabled=false --set "api.replicas=$replicas" --set "api.resources.requests.cpu=${cpu}m,api.resources.limits.cpu=${cpu}m,api.resources.requests.memory=${memory}Mi,api.resources.limits.memory=${memory}Mi" --set-string api.env.GOMEMLIMIT=80MiB --wait --wait-for-jobs --timeout 240s > "evidence/rollout-$profile.txt" + printf '%s,%s,%s,%s,%s,8\n' "$profile" "$profile-$run_id" "$replicas" "$cpu" "$memory" >> evidence/scaling-profiles.csv + RUN="$profile-$run_id" scripts/run-load.sh + done 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/run-load.sh b/scripts/run-load.sh new file mode 100755 index 00000000..49286023 --- /dev/null +++ b/scripts/run-load.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# Run the pinned k6 workload inside the cluster and retain raw results and resource samples. +set -eu +cd "$(dirname "$0")/.." +: "${KUBE_CONTEXT:=dev}" "${NAMESPACE:=highload-applications}" +: "${RUN:=manual-$(date -u +%Y%m%d%H%M%S)}" "${DURATION:=30}" "${VUS:=32}" "${LOAD_SCRIPT:=scaling.js}" +case "$RUN" in *[!a-z0-9-]*|'') echo 'RUN must be a DNS label' >&2; exit 2 ;; esac +mkdir -p evidence +manifest=$(mktemp) +sampler= +cleanup() { + if [ -n "$sampler" ]; then kill "$sampler" 2>/dev/null || true; wait "$sampler" 2>/dev/null || true; fi + rm -f "$manifest" +} +trap cleanup EXIT +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" create configmap lab3-load-scripts --from-file=student-tests/load/ --dry-run=client -o yaml | kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" apply -f - +helm template lab3 charts/messenger -n "$NAMESPACE" -s templates/load.yaml --set load.enabled=true --set-string "load.run=$RUN" --set-string "load.script=$LOAD_SCRIPT" --set "load.duration=$DURATION" --set "load.vus=$VUS" > "$manifest" +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" apply -f "$manifest" +( + while :; do + date -u '+UTC %Y-%m-%dT%H:%M:%SZ' + kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" top pods -l 'app in (lab3-api,lab3-lb,lab3-postgres,lab3-valkey,lab3-load)' || true + kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" exec lab3-postgres-0 -- psql -U messenger -d messenger -Atc "SELECT state,wait_event_type,wait_event,count(*) FROM pg_stat_activity WHERE datname='messenger' GROUP BY state,wait_event_type,wait_event" || true + sleep 5 + done +) > "evidence/resources-$RUN.txt" 2>&1 & +sampler=$! +complete=false +for attempt in $(seq 1 140); do + state=$(kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get "job/lab3-load-$RUN" -o json) + if printf '%s' "$state" | jq -e '.status.succeeded > 0' >/dev/null; then complete=true; break; fi + if printf '%s' "$state" | jq -e '.status.failed > 0' >/dev/null; then break; fi + sleep 2 +done +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" logs "job/lab3-load-$RUN" > "evidence/load-$RUN.txt" +$complete || { echo "Load failed; inspect evidence/load-$RUN.txt" >&2; exit 1; } +if [ "$LOAD_SCRIPT" = scaling.js ]; then + jq -R 'fromjson? | select(has("profile"))' "evidence/load-$RUN.txt" > "evidence/load-$RUN.json" + test -s "evidence/load-$RUN.json" +fi 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/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..adfe8665 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Terminate the exact observed API pod; its replacement receives a different instance ID. +set -eu +: "${KUBE_CONTEXT:=dev}" "${NAMESPACE:=highload-applications}" "${TARGET_INSTANCE_ID:?Expected API pod name}" +case "$TARGET_INSTANCE_ID" in lab3-api-*) ;; *) echo 'Target is not a lab3 API pod' >&2; exit 2 ;; esac +label=$(kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get pod "$TARGET_INSTANCE_ID" -o jsonpath='{.metadata.labels.app}') +test "$label" = lab3-api +mkdir -p evidence +printf '%s target=%s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$TARGET_INSTANCE_ID" >> evidence/failover-targets.txt +kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" delete pod "$TARGET_INSTANCE_ID" --wait=false 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