Перенести актуальную lab2 как базу lab3

This commit is contained in:
Vladislav Agapov
2026-10-16 11:42:02 +03:00
parent 0ab3a341aa
commit a57cbcf329
150 changed files with 10826 additions and 71 deletions
+8 -20
View File
@@ -1,20 +1,8 @@
.git *
.github !go.mod
.env !go.sum
.env.* !cmd/
!.env.example !cmd/**
secrets !internal/
certs !internal/**
volumes !Dockerfile
data
backups
*.key
*.pem
*.p12
*.pfx
*.jks
.venv
__pycache__
node_modules
evidence
.DS_Store
+19 -10
View File
@@ -1,13 +1,22 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Synthetic isolated environment only. Never commit the local .env.
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0 APP_HOST=0.0.0.0
APP_PORT=8080 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 SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values. DEPENDENCY_POOL_SIZE=8
DATABASE_URL_FILE=/run/secrets/database_url DEPENDENCY_TIMEOUT_MS=1000
# Optional on 3, required use on 4 in lab2; Redis OR Valkey: REQUEST_TIMEOUT_SECONDS=3
SESSION_STORE=postgres SHUTDOWN_TIMEOUT_SECONDS=5
CACHE_URL_FILE=/run/secrets/cache_url MAX_IN_FLIGHT=32
API_REPLICAS=2 REQUESTS_PER_SECOND=1000
IDEMPOTENCY_TTL_SECONDS=86400 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
+50
View File
@@ -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/
+3
View File
@@ -30,3 +30,6 @@ coverage/
.vscode/ .vscode/
# Keep small, sanitized evidence summaries in evidence/ under version control. # Keep small, sanitized evidence summaries in evidence/ under version control.
# Inspect git diff --cached: ignore rules are not a secret scanner. # Inspect git diff --cached: ignore rules are not a secret scanner.
/server
/key.json
+21
View File
@@ -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
+44
View File
@@ -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).
+16
View File
@@ -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"]
+58 -5
View File
@@ -4,10 +4,10 @@ CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) 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: 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: check:
$(PYTHON) scripts/check_contract.py $(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) @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) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-failover: GO ?= go
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) .PHONY: build test-student coverage vet lint fmt research
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) 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
+2 -36
View File
@@ -1,37 +1,3 @@
# Отчёт — лабораторная 3 # Базовое состояние
- Автор, группа: TODO Перенесена собственная реализация lab2 из коммита 8173f70. Контракт и публичные проверки lab3 сохранены. Требования lab3 на этом этапе ещё не реализованы.
- Целевая оценка; выбранный трек 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: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
+6
View File
@@ -0,0 +1,6 @@
apiVersion: v2
name: messenger
description: Учебный мессенджер с PostgreSQL и шардированным Valkey
version: 0.1.0
appVersion: lab2
type: application
+7
View File
@@ -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 -}}
+88
View File
@@ -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]
+7
View File
@@ -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 -}}
@@ -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
+66
View File
@@ -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 }}
+57
View File
@@ -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 }}
+9
View File
@@ -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}$"}}}
}
}
+34
View File
@@ -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: ''
+97
View File
@@ -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
}
+104
View File
@@ -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")
}
}
+19
View File
@@ -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]")
}
+46
View File
@@ -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
}
+111
View File
@@ -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)
}
})
}
+29
View File
@@ -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")}
}
+15
View File
@@ -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)
}
}
+77
View File
@@ -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}
}
+48
View File
@@ -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")
}
}
+89
View File
@@ -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 после рестарта может стать недействительным; исторические измерения отделены от свежих проверок. Оценку определяет преподаватель.
+23
View File
@@ -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-* |
+48
View File
@@ -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 не изменяются.
@@ -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 реализованы в этом репозитории.
+15
View File
@@ -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: он нужен только при переносе существующей установки.
+36
View File
@@ -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
)
+77
View File
@@ -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=
+18
View File
@@ -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)
}
+73
View File
@@ -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
}
+148
View File
@@ -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)
}
})
}
}
+53
View File
@@ -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()
}
+241
View File
@@ -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")
}
}
+157
View File
@@ -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
}
+41
View File
@@ -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
}
+32
View File
@@ -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")
}
}
+54
View File
@@ -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
}
+52
View File
@@ -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
}
+34
View File
@@ -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)
}
})
}
}
+8
View File
@@ -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})
}
+76
View File
@@ -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"
}
+161
View File
@@ -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)
}
}
@@ -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")
}
@@ -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())
}
@@ -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
}
@@ -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
}
+22
View File
@@ -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
}
@@ -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
}
@@ -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"
)
@@ -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,
}
}
+71
View File
@@ -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,
},
}
}
@@ -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)
}
})
}
@@ -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
}
@@ -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))
}
@@ -0,0 +1,7 @@
package fiber
const (
headerUserID = "X-User-Id"
headerRequestID = "X-Request-Id"
retryAfterSeconds = 1
)
+28
View File
@@ -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
}
@@ -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()
}
}
@@ -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")
}
}
+77
View File
@@ -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
}
@@ -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)
}
}
@@ -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
}
@@ -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)
}
})
}
@@ -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
}
}
@@ -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)
}
}
+22
View File
@@ -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)
}
@@ -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)
}
}
+12
View File
@@ -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
}
+108
View File
@@ -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
}
+179
View File
@@ -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
}
+62
View File
@@ -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])
}
+73
View File
@@ -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")
}
}
}
+110
View File
@@ -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
}
+13
View File
@@ -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
}
+98
View File
@@ -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"`
}
+54
View File
@@ -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
}
+37
View File
@@ -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")
}
})
}
}
+44
View File
@@ -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
}
+123
View File
@@ -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
}
@@ -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)
}
})
}
+17
View File
@@ -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)
}
+12
View File
@@ -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)
}
+23
View File
@@ -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")
)
+36
View File
@@ -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)
}
+62
View File
@@ -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)
}
+84
View File
@@ -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")
}
})
}
+47
View File
@@ -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)
}
@@ -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)
}
})
}
}
+261
View File
@@ -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)
}
})
}
}
+49
View File
@@ -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
}
+23
View File
@@ -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
}
}
+147
View File
@@ -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
}
}
+42
View File
@@ -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
}
+38
View File
@@ -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)
}
@@ -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)
}
})
}
}

Some files were not shown because too many files have changed in this diff Show More