Compare commits

3 Commits
220 changed files with 15059 additions and 44 deletions
+8 -20
View File
@@ -1,20 +1,8 @@
.git
.github
.env
.env.*
!.env.example
secrets
certs
volumes
data
backups
*.key
*.pem
*.p12
*.pfx
*.jks
.venv
__pycache__
node_modules
evidence
.DS_Store
*
!go.mod
!go.sum
!cmd/
!cmd/**
!internal/
!internal/**
!Dockerfile
+20
View File
@@ -0,0 +1,20 @@
name: Go correctness and per-file coverage
on: [push, pull_request]
jobs:
verify:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.26.1'
- run: sudo apt-get update && sudo apt-get install -y jq ruby
- run: go vet ./...
- run: test -z "$(gofmt -l cmd internal)"
- run: LOCAL_COVERAGE=true scripts/test-local.sh
- uses: actions/upload-artifact@v4
if: always()
with:
name: coverage
path: coverage/summary.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/mtusi2026lab4
+5
View File
@@ -0,0 +1,5 @@
# Архитектура lab4
Fiber controller зависит от интерфейса приложения; application service проверяет пользователя, чат и файл. PostgreSQL store обеспечивает атомарность метаданных/сообщений. S3 adapter хранит приватные байты по server-generated UUID key. Fx связывает реализации. Метаданные DTO не содержат транспортных типов, ключ S3 не попадает в HTTP.
Upload ограничен по размеру и числу одновременно декодируемых изображений. Сначала DecodeConfig проверяет пиксели, затем полный decode выявляет повреждение. После проверки временный decoded buffer освобождается; исходные байты передаются S3 без повторного полного буфера. Между PostgreSQL и S3 нет распределённой транзакции: резервирование, ready commit и периодическая сверка явно закрывают окна отказа.
+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"]
+29
View File
@@ -28,3 +28,32 @@ test-persistence:
test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
.PHONY: test-student vet lint coverage chart-check
test-student:
go test -race ./...
vet:
go vet ./...
lint:
golangci-lint run ./...
coverage:
scripts/coverage.sh
chart-check:
helm lint charts/messenger
helm template lab2 charts/messenger >/dev/null
KUBE_CONTEXT ?= dev
NAMESPACE ?= highload-applications
RELEASE ?= lab2
IMAGE ?= asisti.registry.twcstorage.ru/mtusi2026lab4
TAG ?= local
.PHONY: init-secrets deploy build-push test-local
init-secrets:
KUBE_CONTEXT=$(KUBE_CONTEXT) NAMESPACE=$(NAMESPACE) scripts/init-secrets.sh
build-push:
docker buildx build --platform linux/amd64 --target runtime --tag $(IMAGE):$(TAG) --metadata-file image-build.json --push .
@echo 'Copy containerimage.digest from image-build.json into charts/messenger/values.yaml before deploy.'
deploy: chart-check
helm upgrade --install $(RELEASE) --reset-values charts/messenger --kube-context $(KUBE_CONTEXT) --namespace $(NAMESPACE) --wait --wait-for-jobs --timeout 8m
test-local:
scripts/test-local.sh
+63 -24
View File
@@ -1,37 +1,76 @@
# Отчёт — лабораторная 4
# Лабораторная 4: приватные вложения
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
Автор: Агапов, БПИ2303. Целевой уровень: 5, трек 2 — согласованность PostgreSQL и S3. Оценка не выставлена.
## Запуск из чистого clone
## Запуск
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Нужны Go 1.26.1, Docker, Helm, kubectl, jq, openssl; для публичных тестов Python 3.9+, для нагрузки k6. Образы и ресурсы закреплены в `charts/messenger/values.yaml`. Используется SeaweedFS 3.85 с закреплённым digest, PostgreSQL 17.6 и Valkey 8.1.3. SDK — minio-go v7.0.95.
## Архитектура и решения
```sh
export GOTOOLCHAIN=go1.26.1
make check
make test-local
make chart-check
# Токен реестра находится только в локальном файле ~/.secrets/twc-registry-token.
make init-secrets
make deploy
make test BASE_URL=https://hl.agapov.space
```
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Helm добавляет S3 в существующий release `lab2`, namespace `highload-applications`, context `dev`. Для другого стенда переопределить Make-параметры и `ingress.host`. Bootstrap создаёт приватный bucket идемпотентно; миграции выполняет Job. Secret генерация сохраняет уже существующие SQL/S3 credentials. Registry secret создаётся из файла токена; секреты не попадают в values.
## Доказательства критериев
Для своего образа: `make build-push TAG=<revision>`, перенести `containerimage.digest` из `image-build.json` в values, затем `make deploy`. Опубликованный образ указан в [image.json](evidence/current/image.json). Публикация образа не означает применение в кластере.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
Безопасная остановка — масштабирование API до нуля после выключения HPA через values. PVC сохраняются. Для намеренного удаления данных отдельного учебного стенда: сначала `helm uninstall lab2 -n highload-applications --kube-context dev`, затем вручную удалить только принадлежащие этому стенду PVC, сверив имена. Общий namespace не удалять. Для проверки перезапуска с реальными PVC предусмотрен `scripts/restart.sh`; HPA должен быть заранее отключён, затем восстановлен.
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
## Устройство
## Эксперименты и отказы
[Архитектура](ARCHITECTURE.md), [требования](docs/SPEC.md). Сохранены текстовые сообщения, сессии, распределённый admission control, идемпотентность, курсорная пагинация и идентификатор API-реплики.
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
PostgreSQL хранит метаданные; приватное S3 — исходные байты. Сначала создаётся `uploading` reservation, затем выполняется PUT, затем metadata становится `ready`. Только после этого HTTP возвращает 201. Неопределённый результат COMMIT не вызывает опасного компенсирующего удаления. Download авторизуется через членство в чате и передаётся потоком. Его context и admission lease живут до закрытия потока.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
MIME определяется по данным, полный decode обнаруживает повреждение; до него проверяются 10 MiB и 40 млн пикселей. Одновременно декодируются не более двух изображений на процесс. Transport ограничен 16 соединениями; в chart memory limit 768 MiB и GOMEMLIMIT 640 MiB. Последний не является жёстким пределом RSS. API имеет права только Read/Write/List для bucket attachments; административные credentials доступны bootstrap Job. S3 Service не открывает консоль; NetworkPolicy разрешает порт 9000 только учебным клиентам.
## Ограничения и следующие шаги
## Проверки
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Измерения выполнены 29.10.2026 на локальном Apple Silicon, API — native Go, зависимости — Docker Desktop. Локальные процессы не имели Kubernetes CPU/RAM limits; эти результаты не измеряют dev-кластер.
| Критерий | Проверка | Доказательство |
| --- | --- | --- |
| Upload/message/download/checksum/ACL | Публичный smoke | [smoke](evidence/local/smoke.txt) |
| Другая API-реплика после остановки | Публичный failover, остановка наблюдаемого INSTANCE_ID | [failover](evidence/local/failover.txt), [actions](evidence/local/actions.txt) |
| Сохранность после рестарта PG/Valkey/S3/API | Публичный persistence с настоящим hook, затем smoke | [persistence](evidence/local/persistence.txt), [smoke-after](evidence/local/smoke-after.txt) |
| MIME, повреждение, размер, пиксели, filename, чужой чат | Go regression tests media/controller/store | [race+coverage](evidence/current/coverage.txt) |
| Приватность и отдельные credentials | Реальные S3 тесты: anonymous GET запрещён, чужой bucket запрещён, повтор bootstrap | Тот же coverage log |
| Ограничение отказов S3 | Недоступный endpoint с timeout, безопасное HTTP-маппирование | Тот же coverage log |
| Уровень 90% для каждого файла | Общий профиль unit/integration/process | [JSON](evidence/current/coverage-per-file.json) |
| 10 одновременных загрузок | k6 + RSS sampler | [summary](evidence/current/upload-summary.json), [RSS](evidence/current/upload-rss-kib.txt) |
| Сверка и защита используемых/свежих объектов | Fault tests + реальные SQL CAS/leases | coverage log; [измерение](evidence/current/reconciliation.txt) |
Первый вариант restart hook обращался к прежним портам после Docker restart и не прошёл. Исправленный hook заново получает назначенные порты. Итоговые доказательства относятся к исправленному сценарию. Он сохраняет файловые системы контейнеров; пересоздание StatefulSet с PVC этим локальным тестом не проверено.
## Эксперимент с памятью
Гипотеза: ограниченная конкурентность decode и потоковый download удерживают память при десяти одновременных upload. `student-tests/load/attachments.js`: 10 VU, 100 операций, fixture PNG 320×200, RSS опрашивается каждые 100 ms скриптом `scripts/measure-upload.sh`. Успешны 67 upload, 33 запроса отклонены ограничителями; p95 upload — 19.586 ms. Пиковый RSS — 80032 KiB (78.16 MiB). Raw-данные сохранены в таблице выше.
Это один короткий прогон с небольшим файлом, без прогрева и повторов. Он подтверждает измеренный пик и обработку перегрузки, но не доказывает такой же RSS для 40-мегапиксельных изображений или выполнение SLO. Отклонения не включены в число успешных операций.
## Трек 2: сверка двух хранилищ
Гипотеза: durable reservation и ограниченный повторяемый обход позволяют безопасно исправлять разрывы без распределённой транзакции.
```sh
# Команды запускаются с теми же конфигурацией и credentials, что API.
./server reconcile
./server reconcile --apply
```
Dry-run — по умолчанию. Сканирование ограничено страницами по 1000 записей/объектов, grace period не менее часа, PUT ограничен 15 секундами. Старый uploading атомарно переводится в deleting только при отсутствии ссылок из сообщений; поздний publish после этого запрещён. Неопределённое удаление повторяется. Существующий ready без объекта становится missing, метаданные и ссылки сохраняются. Найденный снова объект позволяет восстановить ready. Наличие любого reservation защищает объект от orphan-cleanup. При ошибке зависимости обход прекращается, а не принимает недоступность за отсутствие данных.
Проверены dry-run, повтор apply, свежие/используемые объекты, отказ PUT/публикации, повтор удаления, гонка publish/reclaim. Это управляемые fault tests и реальные SQL/S3 операции, а не убийство процесса на каждой инструкции. Для инвентаря ready без объектов стоимость dry-run: 100 записей — 45.622 ms, 1000 — 457.760 ms. По одному прогону каждого размера; в данном профиле рост приблизительно линейный. Бounded pagination ограничивает память, но число HEAD/LIST и полное время остаются пропорциональны объёму. Восстановление missing проверяет наличие объекта, не повторный checksum.
## Ограничения и источники
Kubernetes — реализованный путь развёртывания; замена требуемого заданием Compose/Swarm требует подтверждения преподавателя. Нет HA PostgreSQL/S3, репликации между площадками и восстановления после потери диска. Отдельного доказательства полного развёртывания этой версии в dev пока нет. Локальные проверки и публикация образа не заменяют его.
Контракт и публичные тесты сохранены. Использованы официальные [S3 API minio-go](https://github.com/minio/minio-go/blob/master/docs/API.md) и [конфигурация SeaweedFS S3](https://github.com/seaweedfs/seaweedfs/blob/master/weed/command/s3.go). При разработке использовалась помощь ИИ; приведённые результаты относятся к выполненным проверкам, ограничения указаны отдельно.
+6
View File
@@ -0,0 +1,6 @@
apiVersion: v2
name: messenger
description: Учебный мессенджер с PostgreSQL и шардированным Valkey
version: 0.1.0
appVersion: lab3
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 -}}
+135
View File
@@ -0,0 +1,135 @@
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:
labels:
app: api
name: api
namespace: {{ .Release.Namespace }}
spec:
selector:
app: api
ports:
- name: http
port: 8080
targetPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
namespace: {{ .Release.Namespace }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.api.replicas }}
{{- end }}
strategy:
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
selector:
matchLabels:
app: api
template:
metadata:
annotations:
checksum/config: {{ printf "%s%s" (include "messenger.shards" .) (toJson .Values.api.env) | sha256sum }}
labels:
app: api
spec:
{{- with .Values.api.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
imagePullSecrets:
- name: {{ .Values.imagePullSecret }}
terminationGracePeriodSeconds: 20
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: api
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: S3_ENDPOINT
value: s3:9000
- name: S3_BUCKET
value: {{ .Values.s3.bucket }}
- name: S3_TLS
value: "false"
- name: S3_ACCESS_KEY
valueFrom:
secretKeyRef: {name: {{ .Values.s3.secret }}, key: access-key}
- name: S3_SECRET_KEY
valueFrom:
secretKeyRef: {name: {{ .Values.s3.secret }}, key: secret-key}
- name: INSTANCE_ID
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: CURSOR_SIGNING_KEY
valueFrom:
secretKeyRef:
name: {{ .Values.databaseSecret }}
key: cursor-key
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: {{ .Values.databaseSecret }}
key: database-url
resources:
{{- toYaml .Values.api.resources | nindent 12 }}
lifecycle:
preStop:
sleep:
seconds: 3
startupProbe:
httpGet:
path: /health/ready
port: 8080
periodSeconds: 2
failureThreshold: 30
readinessProbe:
timeoutSeconds: {{ .Values.api.readiness.timeoutSeconds }}
failureThreshold: {{ .Values.api.readiness.failureThreshold }}
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 -}}
+33
View File
@@ -0,0 +1,33 @@
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api
minReplicas: {{ .Values.autoscaling.minReplicas }}
maxReplicas: {{ .Values.autoscaling.maxReplicas }}
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.cpuPercent }}
behavior:
scaleUp:
stabilizationWindowSeconds: 15
policies:
- type: Pods
value: 1
periodSeconds: 30
scaleDown:
stabilizationWindowSeconds: 120
policies:
- type: Pods
value: 1
periodSeconds: 60
{{- end }}
+23
View File
@@ -0,0 +1,23 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: messenger
annotations:
cert-manager.io/cluster-issuer: {{ .Values.ingress.clusterIssuer | quote }}
spec:
ingressClassName: {{ .Values.ingress.className }}
tls:
- hosts:
- {{ .Values.ingress.host | quote }}
secretName: messenger-tls
rules:
- host: {{ .Values.ingress.host | quote }}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: api
port:
number: 8080
+39
View File
@@ -0,0 +1,39 @@
{{- if .Values.load.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
name: load-{{ .Values.load.run }}
spec:
backoffLimit: 0
activeDeadlineSeconds: 300
ttlSecondsAfterFinished: 86400
template:
metadata:
labels:
app: load
spec:
restartPolicy: Never
containers:
- name: k6
image: grafana/k6:1.3.0
args: [run, --quiet, /scripts/{{ .Values.load.script }}]
env:
- name: BASE_URL
value: "https://{{ .Values.ingress.host }}"
- name: TARGET_INSTANCE_ID
value: {{ .Values.load.target | default "" | quote }}
- name: DURATION
value: {{ .Values.load.duration | quote }}
- name: VUS
value: {{ .Values.load.vus | quote }}
resources:
requests: {cpu: 250m, memory: 128Mi}
limits: {cpu: '2', memory: 256Mi}
volumeMounts:
- name: scripts
mountPath: /scripts
volumes:
- name: scripts
configMap:
name: load-scripts
{{- end }}
+32
View File
@@ -0,0 +1,32 @@
apiVersion: batch/v1
kind: Job
metadata:
name: migrate-{{ .Release.Revision }}
spec:
activeDeadlineSeconds: 180
backoffLimit: 3
ttlSecondsAfterFinished: 86400
template:
metadata:
labels:
app: migrate
spec:
restartPolicy: OnFailure
imagePullSecrets:
- name: {{ .Values.imagePullSecret }}
containers:
- name: migrate
image: "{{ .Values.image.repository }}@{{ .Values.image.digest }}"
args: [migrate]
envFrom:
- configMapRef:
name: messenger-config
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: {{ .Values.databaseSecret }}
key: database-url
resources:
requests: {cpu: 50m, memory: 32Mi}
limits: {cpu: 500m, memory: 128Mi}
@@ -0,0 +1,19 @@
{{- if .Values.monitoring.serviceMonitor }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: api
labels:
app: api
spec:
namespaceSelector:
matchNames: [{{ .Release.Namespace }}]
selector:
matchLabels:
app: api
endpoints:
- port: http
path: /metrics
interval: 15s
scrapeTimeout: 3s
{{- end }}
@@ -0,0 +1,54 @@
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
- from:
- podSelector:
matchLabels:
app: migrate
ports:
- protocol: TCP
port: 5432
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: private-api
spec:
podSelector:
matchLabels:
app: api
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: traefik
ports:
- protocol: TCP
port: 8080
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
ports:
- protocol: TCP
port: 8080
+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 }}
+97
View File
@@ -0,0 +1,97 @@
apiVersion: v1
kind: Service
metadata:
name: s3
spec:
selector: {app: s3}
ports:
- {name: s3, port: 9000, targetPort: 9000}
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: s3
spec:
serviceName: s3
replicas: 1
selector:
matchLabels: {app: s3}
template:
metadata:
labels: {app: s3}
spec:
securityContext:
runAsUser: 1000
runAsNonRoot: true
fsGroup: 1000
containers:
- name: s3
image: {{ .Values.s3.image }}
args: [server, -dir=/data, -s3, -s3.port=9000, -s3.config=/identity/identities.json, -master.volumeSizeLimitMB=100, -volume.max=32]
ports: [{containerPort: 9000}]
readinessProbe:
tcpSocket: {port: 9000}
resources:
requests: {cpu: 100m, memory: 256Mi}
limits: {cpu: '1', memory: 512Mi}
securityContext:
allowPrivilegeEscalation: false
capabilities: {drop: [ALL]}
volumeMounts:
- {name: objects, mountPath: /data}
- {name: identity, mountPath: /identity, readOnly: true}
volumes:
- name: identity
secret: {secretName: {{ .Values.s3.secret }}, items: [{key: identities.json, path: identities.json}]}
volumeClaimTemplates:
- metadata: {name: objects}
spec:
accessModes: [ReadWriteOnce]
resources:
requests: {storage: {{ .Values.s3.storage }}}
---
apiVersion: batch/v1
kind: Job
metadata:
name: s3-bootstrap-{{ .Release.Revision }}
spec:
ttlSecondsAfterFinished: 3600
backoffLimit: 4
template:
metadata:
labels: {app: s3-bootstrap}
spec:
restartPolicy: OnFailure
imagePullSecrets: [{name: {{ .Values.imagePullSecret }}}]
containers:
- name: bootstrap
image: "{{ .Values.image.repository }}@{{ .Values.image.digest }}"
args: [s3-bootstrap]
env:
- {name: S3_ENDPOINT, value: 's3:9000'}
- {name: S3_TLS, value: 'false'}
- {name: S3_BUCKET, value: {{ .Values.s3.bucket }}}
- name: S3_ACCESS_KEY
valueFrom:
secretKeyRef: {name: {{ .Values.s3.secret }}, key: root-user}
- name: S3_SECRET_KEY
valueFrom:
secretKeyRef: {name: {{ .Values.s3.secret }}, key: root-password}
resources:
requests: {cpu: 50m, memory: 64Mi}
limits: {cpu: 200m, memory: 128Mi}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: private-s3
spec:
podSelector:
matchLabels: {app: s3}
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchExpressions:
- {key: app, operator: In, values: [api, s3-bootstrap, reconcile]}
ports: [{protocol: TCP, port: 9000}]
+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}$"}}}
}
}
+64
View File
@@ -0,0 +1,64 @@
# Existing lab2 release; shared persistent stores and credentials.
image:
repository: asisti.registry.twcstorage.ru/mtusi2026lab4
digest: sha256:36d4ccb6d3c44e7a2540187a628d148e8c1601cdc3215eb81fc37edf48f5c2ce
imagePullSecret: registry-pull
databaseSecret: messenger-secrets
api:
readiness:
timeoutSeconds: 2
failureThreshold: 2
replicas: 2
resources:
requests: {cpu: 250m, memory: 128Mi}
limits: {cpu: '1', memory: 768Mi}
env:
SESSION_TTL_SECONDS: '3600'
DEPENDENCY_TIMEOUT_MS: '2000'
DEPENDENCY_POOL_SIZE: '8'
REQUEST_TIMEOUT_SECONDS: '4'
SHUTDOWN_TIMEOUT_SECONDS: '5'
GOMEMLIMIT: 640MiB
MAX_CONNECTIONS: '16'
MAX_BODY_BYTES: '10485760'
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: ''
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 4
cpuPercent: 60
monitoring:
serviceMonitor: false
load:
enabled: false
run: manual
script: scaling.js
duration: 30
vus: 32
ingress:
host: hl.agapov.space
className: traefik
clusterIssuer: letsencrypt-prod
s3:
image: chrislusf/seaweedfs:3.85@sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a
secret: messenger-s3
bucket: attachments
storage: 5Gi
+105
View File
@@ -0,0 +1,105 @@
package main
import (
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller"
fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller/http/fiber"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/password"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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,
config.NewObjectStore,
newObjects,
newMedia,
newDatabase,
newValkey,
newAuthentication,
fx.Annotate(newMediaReadiness, 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(newCursor, fx.As(new(service.CursorCodec))),
fx.Annotate(production.NewCached, fx.As(new(service.Service))),
fx.Annotate(newHTTPController, 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
}
// newCursor binds the shared signing secret at the composition root.
func newCursor(cfg *config.Persistence) (*cursor.Codec, error) {
return cursor.NewShared(cfg.CursorKey)
}
+108
View File
@@ -0,0 +1,108 @@
package main
import (
"context"
"net"
"os"
"testing"
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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")
}
t.Setenv("CURSOR_SIGNING_KEY", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
if err := migrate(); err != nil {
t.Fatal(err)
}
}
+50
View File
@@ -0,0 +1,50 @@
package main
import (
"context"
"fmt"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres"
"go.uber.org/fx"
)
// run dispatches the server command or the container healthcheck.
func run(args []string) error {
if len(args) == 1 && args[0] == "s3-bootstrap" {
return bootstrapS3()
}
if len(args) == 0 {
fx.New(CreateApp()).Run()
return nil
}
if len(args) == 1 && args[0] == "reconcile" {
return reconcile(false)
}
if len(args) == 2 && args[0] == "reconcile" && args[1] == "--apply" {
return reconcile(true)
}
if len(args) == 1 && args[0] == "migrate" {
return migrate()
}
if len(args) == 1 && args[0] == "healthcheck" {
return healthcheck()
}
return fmt.Errorf("usage: server [healthcheck|migrate]")
}
// migrate applies versioned DDL once from an operator job, independently of the API.
func migrate() error {
cfg, err := config.NewPersistence()
if err != nil {
return err
}
database, err := postgres.New(postgres.Options{URL: cfg.DatabaseURL, MaxConnections: 1, Timeout: 30 * time.Second})
if err != nil {
return err
}
defer database.Close()
return database.Start(context.Background())
}
+46
View File
@@ -0,0 +1,46 @@
package main
import (
"fmt"
"net"
"net/http"
"strconv"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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/mtusi2026lab4/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/mtusi2026lab4/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)
}
}
+39
View File
@@ -0,0 +1,39 @@
package main
import (
"go.lab260.ru/fielderr"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller/http/fiber"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/media"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/objectstore"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/valkey"
)
// newObjects binds the S3 adapter at the composition root.
func newObjects(cfg *config.ObjectStore) (*objectstore.Client, error) {
return objectstore.New(cfg)
}
// newMedia injects infrastructure through the media service's consumer interfaces.
func newMedia(database *postgres.Store, objects *objectstore.Client, chats service.Service) (*media.Service, error) {
return media.New(database, objects, chats)
}
// newHTTPController connects the independently tested transport and attachment service.
func newHTTPController(log *zap.Logger, cfg *config.Controller, svc service.Service, registry *fielderr.Registry, limiter admission.Distributed, auth service.Authentication, readiness fiberctrl.Readiness, attachments *media.Service) (*fiberctrl.Controller, error) {
ctrl, err := fiberctrl.New(log, cfg, svc, registry, limiter, auth, readiness)
if err != nil {
return nil, err
}
return ctrl.WithAttachments(attachments), nil
}
// newMediaReadiness includes private originals in the mandatory synchronous dependency path.
func newMediaReadiness(database *postgres.Store, cache *valkey.Client, objects *objectstore.Client) *dependencyReadiness {
return &dependencyReadiness{database: database, cache: cache, objects: objects}
}
+88
View File
@@ -0,0 +1,88 @@
package main
import (
"os"
"testing"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
)
// TestMediaHTTPConfigurationFailure rejects invalid listener settings before serving files.
func TestMediaHTTPConfigurationFailure(t *testing.T) {
if _, err := newHTTPController(nil, &config.Controller{}, nil, nil, nil, nil, nil, nil); err == nil {
t.Fatal("invalid HTTP composition accepted")
}
}
// TestReconcileConfigurationFailures checks operator commands fail closed before side effects.
func TestReconcileConfigurationFailures(t *testing.T) {
cases := []struct {
name string
key string
value string
}{
{"database missing", "DATABASE_URL", ""},
{"s3 missing", "S3_ENDPOINT", ""},
{"database malformed", "DATABASE_URL", "://invalid"},
{"s3 malformed", "S3_ENDPOINT", "http://invalid/path"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DATABASE_URL", "postgres://localhost/test")
t.Setenv("VALKEY_SHARDS", "shard0=localhost:6379")
t.Setenv("S3_ENDPOINT", "localhost:9000")
t.Setenv("S3_BUCKET", "attachments")
t.Setenv("S3_ACCESS_KEY", "test")
t.Setenv("S3_SECRET_KEY", "synthetic")
t.Setenv(tc.key, tc.value)
if err := run([]string{"reconcile"}); err == nil {
t.Fatal("invalid reconciliation configuration accepted")
}
})
}
}
// TestReconcileRealInventory verifies the operator command can scan both real dependencies.
func TestReconcileRealInventory(t *testing.T) {
requirePersistence(t)
if os.Getenv("S3_ENDPOINT") == "" {
t.Skip("isolated S3 required")
}
if err := run([]string{"reconcile"}); err != nil {
t.Fatal(err)
}
if err := run([]string{"reconcile", "--apply"}); err != nil {
t.Fatal(err)
}
}
// TestBootstrapConfigurationFailures rejects missing credentials and malformed endpoints.
func TestBootstrapConfigurationFailures(t *testing.T) {
t.Run("missing", func(t *testing.T) {
t.Setenv("S3_ENDPOINT", "")
if err := run([]string{"s3-bootstrap"}); err == nil {
t.Fatal("missing config accepted")
}
})
t.Run("malformed", func(t *testing.T) {
t.Setenv("S3_ENDPOINT", "http://invalid/path")
t.Setenv("S3_BUCKET", "attachments")
t.Setenv("S3_ACCESS_KEY", "test")
t.Setenv("S3_SECRET_KEY", "synthetic")
if err := run([]string{"s3-bootstrap"}); err == nil {
t.Fatal("malformed endpoint accepted")
}
})
}
// TestBootstrapExistingBucket verifies repeatable operator execution against the isolated bucket.
func TestBootstrapExistingBucket(t *testing.T) {
if os.Getenv("S3_ENDPOINT") == "" || os.Getenv("S3_ADMIN_SECRET") == "" {
t.Skip("isolated S3 operator credentials required")
}
t.Setenv("S3_ACCESS_KEY", "operator")
t.Setenv("S3_SECRET_KEY", os.Getenv("S3_ADMIN_SECRET"))
if err := run([]string{"s3-bootstrap"}); err != nil {
t.Fatal(err)
}
}
+85
View File
@@ -0,0 +1,85 @@
package main
import (
"context"
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller/http/fiber"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/authentication"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/valkey"
)
type dependencyReadiness struct {
database fiberctrl.Readiness
cache fiberctrl.Readiness
objects fiberctrl.Readiness
}
// 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
}
if err := d.cache.Ping(ctx); err != nil {
return err
}
if d.objects != nil {
return d.objects.Ping(ctx)
}
return nil
}
// 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.CheckSchema,
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}
}
+66
View File
@@ -0,0 +1,66 @@
package main
import (
"testing"
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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")
}
}
// TestMigrationCommandRejectsMissingConfiguration fails before opening a database.
func TestMigrationCommandRejectsMissingConfiguration(t *testing.T) {
t.Setenv("DATABASE_URL", "")
t.Setenv("VALKEY_SHARDS", "shard0=localhost:6379")
if err := run([]string{"migrate"}); err == nil {
t.Fatal("missing database configuration accepted")
}
}
// TestMigrationCommandRejectsMalformedDatabaseURL fails without logging credentials.
func TestMigrationCommandRejectsMalformedDatabaseURL(t *testing.T) {
t.Setenv("DATABASE_URL", "://invalid")
t.Setenv("VALKEY_SHARDS", "shard0=localhost:6379")
if err := run([]string{"migrate"}); err == nil {
t.Fatal("malformed database configuration accepted")
}
}
+37
View File
@@ -0,0 +1,37 @@
package main
import (
"context"
"os"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/media"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/objectstore"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres"
)
// reconcile runs a bounded dry-run scan unless the operator explicitly supplies apply.
func reconcile(apply bool) error {
cfg, err := config.NewPersistence()
if err != nil {
return err
}
s3, err := config.NewObjectStore()
if err != nil {
return err
}
database, err := postgres.New(postgres.Options{URL: cfg.DatabaseURL, MaxConnections: 1, Timeout: 5 * time.Second})
if err != nil {
return err
}
defer database.Close()
objects, err := objectstore.New(s3)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
return media.RunReconciliation(ctx, database, objects, os.Stdout, apply)
}
+24
View File
@@ -0,0 +1,24 @@
package main
import (
"context"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/objectstore"
)
// bootstrapS3 creates the private bucket using separate operator credentials.
func bootstrapS3() error {
cfg, err := config.NewObjectStore()
if err != nil {
return err
}
objects, err := objectstore.New(cfg)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
return objects.Bootstrap(ctx)
}
+7
View File
@@ -0,0 +1,7 @@
# Сверка контракта lab4
README, COURSE, contracts/README.md и OpenAPI сохранены. Проверены обязательный HTTP/auth/idempotency контракт, byte/pixel limits, MIME/filename, ACL и chat attachment scope. Источники: controller/media/production/postgres tests и публичные smoke/failover/persistence на двух настоящих процессах API.
Уровень4: negative attachment tests; компенсация и reconciliation при разрывах SQL/S3;10VU эксперимент с RSS; повторный bootstrap и private-bucket/scoped-credential tests. Трек5.2: dry-run/apply/repeated apply, fresh/used protection, missing/orphan, стоимость100/1000 объектов. Измерения и границы fault injection приведены в REPORT; это не заявление об отказоустойчивости при потере диска.
Формальное открытое расхождение: вместо требуемого Compose/Swarm реализован Kubernetes. Его принятие преподавателем не подтверждено. Отдельного dev-deploy именно версии lab4 не заявлено; локальные результаты не подменяются развёртыванием cumulative lab6.
+8
View File
@@ -0,0 +1,8 @@
# План lab4
- L4-01–04: перенос основы, S3, метаданные и HTTP — выполнено; публичный smoke и regression tests прошли.
- L4-05: reconciler, защита ссылок/свежих данных, fault injection — выполнено; измерен обход 100/1000 записей. Ограничения в REPORT.
- L4-06: race, per-file coverage ≥90%, lint, память 10 VU, реальные persistence/failover — выполнено локально.
- Образ опубликован, digest закреплён. Применение этой версии в dev не подтверждено.
- CI автоматически проверяет порог каждого файла; выполнение удалённого workflow пока не подтверждено.
- Репозиторий готов к отдельному коммиту и публикации. Описание PR — в родительском каталоге рабочего пространства.
+14
View File
@@ -0,0 +1,14 @@
# Спецификация lab4
Цель: весь уровень 3/4, трек 5 «Согласованность двух хранилищ». Основание: README, COURSE, contracts/openapi.json и contracts/README.md. Kubernetes/Helm сохраняется основным стендом; принятие замены Compose преподавателем отдельно не подтверждено.
| ID | Требование | Приёмка |
| --- | --- | --- |
| L4-01 | Приватный S3, отдельные ограниченные credentials, повторяемый bootstrap | Повтор bootstrap, anonymous GET denied |
| L4-02 | Авторизованный PNG/JPEG upload 201 и byte-exact download | Публичный smoke, SHA256, failover/persistence |
| L4-03 | 10MiB/40M pixels, filename/MIME/полная декодируемость | Негативные тесты; ограниченная concurrency/RAM |
| L4-04 | До 10 уникальных вложений чата в сообщении, idempotency учитывает IDs | Чужое/другой чат 404, повтор/конфликт |
| L4-05 | Безопасная сверка orphan/missing, grace, dry-run, повтор | Fault injection S3/DB, fresh/referenced сохранены, стоимость обхода |
| L4-06 | Изолированные интеграционные тесты и ≥10 concurrent upload | Raw результаты с ревизией; coverage ≥90% каждого Go файла |
Решение: резервирование метаданных uploading до PUT; публикация ready после PUT. Неопределённый результат записи БД не вызывает слепой DELETE объекта. Reconciler проверяет возраст и состояние под блокировкой; используемые записи/объекты не удаляет. Объекты имеют UUID key, не filename. Не переносить старые измерения как результаты lab4.
+4
View File
@@ -0,0 +1,4 @@
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/media 0.399s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/objectstore 0.359s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres 1.626s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller/http/fiber 0.298s
+6
View File
@@ -0,0 +1,6 @@
helm lint charts/messenger
==> Linting charts/messenger
[INFO] Chart.yaml: icon is recommended
1 chart(s) linted, 0 chart(s) failed
helm template lab2 charts/messenger >/dev/null
+4
View File
@@ -0,0 +1,4 @@
/private/tmp/lab-contract-validation/bin/python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
/private/tmp/lab-contract-validation/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
+91
View File
@@ -0,0 +1,91 @@
{"threshold_per_file":90,"files":[
{"file":"internal/store/memory/store.go","statements":3,"covered":3,"percent":100.00000000,"sha256":"23fa65457a7b5a3d456fc4b518b76eeed8d4063b3e5090f62ae8c57d276f018d"},
{"file":"internal/service/production/members.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"99a25f75b1289d812c125a2a68640869a2b879abd205c81155fae7bd96174935"},
{"file":"internal/config/controller.go","statements":23,"covered":22,"percent":95.65217391,"sha256":"1c853c0f771e2c75958db8158797f2287e06c8d9efe8856365b7b9c71b1747b0"},
{"file":"internal/controller/interface.go","statements":0,"covered":0,"percent":null,"sha256":"24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68"},
{"file":"internal/config/logger.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988"},
{"file":"internal/valkey/admission.go","statements":42,"covered":42,"percent":100.00000000,"sha256":"f729a0c695ad01f80e7450d0e802c07cfb3f35340b6ea22a20e00348a9b64371"},
{"file":"internal/service/production/service.go","statements":10,"covered":10,"percent":100.00000000,"sha256":"6f0cf8ab6c0e07bbb82e6b289e3d734c84ead5b82932db2007ef0c54f159f4cb"},
{"file":"internal/password/password.go","statements":18,"covered":17,"percent":94.44444444,"sha256":"fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76"},
{"file":"internal/strictjson/decode.go","statements":47,"covered":47,"percent":100.00000000,"sha256":"d99595e1f74406c5aa617c0ec062afb7f12f116bd86776e87cc9c9a436ff7eea"},
{"file":"internal/store/postgres/messages.go","statements":31,"covered":29,"percent":93.54838710,"sha256":"3b9f6cc9906f3007cf416bbfc01046794c652a8589c3ea43e57a03b1c8c26bc2"},
{"file":"internal/service/cursor.go","statements":0,"covered":0,"percent":null,"sha256":"430996f921d5dab91b47a6f796e19c2b7cb31d386572b326adec581b8be9f6b7"},
{"file":"internal/media/reconcile.go","statements":38,"covered":38,"percent":100.00000000,"sha256":"278dc4c8720348df752801adf04a30d1b7508a730665122693ce1dd7b90c376a"},
{"file":"cmd/server/reconcile.go","statements":16,"covered":16,"percent":100.00000000,"sha256":"a88c8f29f9482564248bc43d7a6386baca64710932877e5fa7008a31a2ae4c42"},
{"file":"internal/store/memory/users.go","statements":22,"covered":21,"percent":95.45454545,"sha256":"946a1a7a72badf6a80b9ff9a5c850914f46cf5ebde13a5f9f945514f0e188f88"},
{"file":"internal/store/memory/capacity.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"da46630a8a5a3625e40677cd4d5e268e2c320a8f1ed272c2f6c05f45cb0f458b"},
{"file":"internal/service/production/access.go","statements":27,"covered":27,"percent":100.00000000,"sha256":"550ab142c922a201f72595ce0774a1b07062a06e5b728119ccb6d31cac5c59e6"},
{"file":"internal/controller/http/fiber/handlers.go","statements":37,"covered":36,"percent":97.29729730,"sha256":"cfa54cff49e70a0f7c2354e60ff84d50b5a19f0d3c3ddd931cdf7872ed1c0e19"},
{"file":"internal/controller/http/fiber/routes.go","statements":18,"covered":18,"percent":100.00000000,"sha256":"e248223517102e1eecdeba9a5e2d844c0afc14116a56e9a1d76c6afb755e63d1"},
{"file":"internal/controller/http/fiber/mapping.go","statements":16,"covered":16,"percent":100.00000000,"sha256":"2db9a0329f722d2ec1cefc529df17875dbc7eb3e50d58319934891c1da3bc7ed"},
{"file":"internal/controller/http/fiber/health.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"1b7628b0f313089891e9bfa44fd6e0cdb753375ffd2cf22caf5abdab61f9c102"},
{"file":"internal/media/validation.go","statements":17,"covered":17,"percent":100.00000000,"sha256":"16a99b15901009e4861cdd30a24a433d8d36782745af1212e3dffa8b0d50906a"},
{"file":"internal/cursor/codec.go","statements":36,"covered":34,"percent":94.44444444,"sha256":"678e197744fb2fc4b51715f51593b98761125bbaddbe4cb1b7032bd6b173ef04"},
{"file":"internal/controller/fx.go","statements":1,"covered":1,"percent":100.00000000,"sha256":"af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a"},
{"file":"internal/service/production/pages.go","statements":17,"covered":16,"percent":94.11764706,"sha256":"0eb30c852f178768e11457a29aa978127d22c4c6f0019aea004123265da5e789"},
{"file":"internal/service/errors.go","statements":0,"covered":0,"percent":null,"sha256":"1c36cfef90643276e1c83aede658af6b9e2eb0152b7ae68c2c8abd0e7bf655cd"},
{"file":"internal/config/objectstore.go","statements":4,"covered":4,"percent":100.00000000,"sha256":"c6283fe310747e8297850b48c0a119c1d62db4903dd2c779c6296678563df188"},
{"file":"internal/media/service.go","statements":46,"covered":46,"percent":100.00000000,"sha256":"77f45226996a1d83f3f4ca2ac6980967d4f7cc1f17f3fd2d324ef267237523c0"},
{"file":"internal/service/production/errors.go","statements":5,"covered":5,"percent":100.00000000,"sha256":"27abf6ee6231c9e89643b512bd5694f32872e357831ec0d6bd1302d754a5d4dd"},
{"file":"internal/controller/http/fiber/headers.go","statements":0,"covered":0,"percent":null,"sha256":"d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd"},
{"file":"cmd/server/commands.go","statements":22,"covered":22,"percent":100.00000000,"sha256":"1d16d1df1e0b0d59e7084e78d2e6caa0d30c3240e0bc040a7963f7f6b862c311"},
{"file":"internal/store/memory/messages.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"ca4526c55af46dc8f4205aa8402d6819e05a46840d704d8caea0a477014f70ab"},
{"file":"internal/objectstore/client.go","statements":39,"covered":36,"percent":92.30769231,"sha256":"0e42d39cc3ca70d440fc49dddf614af8a33801ac23a954ac613d6397631a9c3c"},
{"file":"internal/model/dto/models.go","statements":0,"covered":0,"percent":null,"sha256":"5e2536b8eba6bb92b751a7b817b6338755008857e3b53920d8da6fb67adeebdb"},
{"file":"internal/store/postgres/idempotency.go","statements":21,"covered":19,"percent":90.47619048,"sha256":"448da4c0755f16184d9bbe6cdef35b9ea4ffcb04b7da832ff82f5c1c34ad0966"},
{"file":"internal/store/postgres/chats.go","statements":26,"covered":24,"percent":92.30769231,"sha256":"cbd4e074fa631b4e2e6a746f01e2d634391cddfd1d4e60d58ca0182524b97eaa"},
{"file":"internal/service/production/chats.go","statements":22,"covered":22,"percent":100.00000000,"sha256":"46f4d77cc32838c28abb57e49ebdc0d30cf36ffe49079b2f84d03c405969a346"},
{"file":"internal/media/run_reconcile.go","statements":21,"covered":21,"percent":100.00000000,"sha256":"3255403afcb9486d33c5bb45b5afa9c3c9b85596ce97f86ac2f224011cd8a860"},
{"file":"internal/controller/http/fiber/error_registry.go","statements":2,"covered":2,"percent":100.00000000,"sha256":"9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a"},
{"file":"internal/controller/http/fiber/public_errors.go","statements":15,"covered":15,"percent":100.00000000,"sha256":"1fbe98b2de99a794a0f2726ad350f258004bd2890660d28b2982c72e5579f3f5"},
{"file":"internal/controller/http/fiber/metrics.go","statements":17,"covered":17,"percent":100.00000000,"sha256":"54db82201697bdfcc65712afe61b650f8f0885fc65222dc4cc6d1c3bb07d82dd"},
{"file":"internal/controller/http/fiber/dependencies.go","statements":0,"covered":0,"percent":null,"sha256":"6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d"},
{"file":"internal/hashring/ring.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c"},
{"file":"cmd/server/logger.go","statements":10,"covered":9,"percent":90.00000000,"sha256":"934f5f3cac0307dbb26b38ec232270a1100b83fe54990e16f98a1277126feb14"},
{"file":"internal/store/memory/ordering.go","statements":6,"covered":6,"percent":100.00000000,"sha256":"4ed267c6ecd734687e5af3645d18a1a6b2608ca9bda19de3e2e0676f4fa8c416"},
{"file":"internal/media/orphans.go","statements":23,"covered":23,"percent":100.00000000,"sha256":"327ee894c8c9afa5bcf8236ed4c91befd66699c0ca33178e9690705764faf002"},
{"file":"internal/controller/http/fiber/decode.go","statements":12,"covered":11,"percent":91.66666667,"sha256":"0f8ac98d5ec9b606f661985515d9a13047ebd262b2c4e99f1a9d61bf8a591dfa"},
{"file":"internal/controller/http/fiber/auth.go","statements":29,"covered":29,"percent":100.00000000,"sha256":"330913d86e6b3f1bedf14f770df7012426f86f4ae2a1cb1fddb2b4f6294a98f8"},
{"file":"internal/service/production/messages.go","statements":18,"covered":18,"percent":100.00000000,"sha256":"76b7c6ee33d98debda99df1ab8272deed64b80aadfec3e079d9d550e0facb4a4"},
{"file":"internal/config/environment.go","statements":14,"covered":14,"percent":100.00000000,"sha256":"027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3"},
{"file":"cmd/server/persistence.go","statements":22,"covered":20,"percent":90.90909091,"sha256":"3302faabb63a43c83a646e3c2217af28f55707198206c80aae5f18787cb8e627"},
{"file":"internal/service/production/validation.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"423d4be24ae5ea70d47d2da5b781296e8bb3cebdea90abf31c2117056bd17bbd"},
{"file":"internal/service/production/creation.go","statements":24,"covered":23,"percent":95.83333333,"sha256":"6de190a75ed12c6b07bcf2889a085fd8fe1025bc13981f771e0a84627c377d0d"},
{"file":"internal/objectstore/list.go","statements":10,"covered":9,"percent":90.00000000,"sha256":"e347b48cde4d4292505dc3f2834ada4d6c8c2dd133600e281741a13f9f13b104"},
{"file":"internal/model/http/models.go","statements":0,"covered":0,"percent":null,"sha256":"d68827b0bd3e6df4037621b6941298d3923dc348bda5bf314a34861e7c34f04e"},
{"file":"internal/model/dto/attachment.go","statements":0,"covered":0,"percent":null,"sha256":"4a7790ef7a3cfc2d9c6f35d42873e04ea48e72a95af2dd173a6f4d2e29c51b46"},
{"file":"cmd/server/app.go","statements":9,"covered":9,"percent":100.00000000,"sha256":"b5a69912970b440c09e1d3db9a8dcbbe21077ecf848acd389d83cc98ad5189dd"},
{"file":"internal/valkey/cache.go","statements":17,"covered":16,"percent":94.11764706,"sha256":"99e7ffe68dd6405fd9495d1bce7ec8c495859023335aa92c0520fcab48ad913a"},
{"file":"internal/store/postgres/reconcile.go","statements":32,"covered":31,"percent":96.87500000,"sha256":"ab6d8b2018f910a0ef4fafc3d203dd4efcf63a64f7bef613739f656f89b69670"},
{"file":"internal/service/production/pagination.go","statements":21,"covered":21,"percent":100.00000000,"sha256":"a0935444ad82e2b92fd975826e91e25cb53bbafbebe352be887571359264d62e"},
{"file":"internal/service/auth.go","statements":0,"covered":0,"percent":null,"sha256":"3e6f99e5239d8fa5de5d406acb6f95485bd6d4fc23f1080b8eb6fd8834fbd722"},
{"file":"internal/model/dto/session.go","statements":0,"covered":0,"percent":null,"sha256":"896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb"},
{"file":"internal/config/memory.go","statements":9,"covered":9,"percent":100.00000000,"sha256":"86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0"},
{"file":"internal/controller/http/fiber/middleware.go","statements":41,"covered":40,"percent":97.56097561,"sha256":"3905cbc45b0637da007d5e556900d74e3a9d5575de358f8f4584c2327214324c"},
{"file":"internal/controller/http/fiber/controller.go","statements":10,"covered":10,"percent":100.00000000,"sha256":"ba7fa956feeeb7426ab183438b019588569a5a1212ad9b1a212423211f136d30"},
{"file":"internal/controller/http/fiber/configure.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd"},
{"file":"internal/admission/distributed.go","statements":0,"covered":0,"percent":null,"sha256":"41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d"},
{"file":"internal/controller/http/fiber/errors.go","statements":29,"covered":29,"percent":100.00000000,"sha256":"a4a40a11689541409fb804f4a285cbe5c0dc9e620073a8257d410e3db3c882d6"},
{"file":"cmd/server/s3_bootstrap.go","statements":9,"covered":9,"percent":100.00000000,"sha256":"b45f7b28965346df23dcbeeeaf4cd446f9dd5f9c0446558298f96246f1b725d3"},
{"file":"internal/store/memory/chats.go","statements":31,"covered":31,"percent":100.00000000,"sha256":"69652b5c7b3834503efe29ae3847db6b0000b9fb0a15774cd7cb20bc8a003e8e"},
{"file":"internal/store/interface.go","statements":0,"covered":0,"percent":null,"sha256":"a91695ddbf0162fad728643e5d33002bbd382d03d950c433ca9c1f44cdbdc2ba"},
{"file":"internal/controller/http/fiber/lifecycle.go","statements":24,"covered":22,"percent":91.66666667,"sha256":"f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08"},
{"file":"internal/valkey/client.go","statements":35,"covered":34,"percent":97.14285714,"sha256":"2db9603f21ceef6a2d245385fbf0977666f4bdb842adbe216c0e294be8d3c02f"},
{"file":"internal/store/postgres/store.go","statements":57,"covered":53,"percent":92.98245614,"sha256":"c82ce119e5bf06a701df762ded6398886781962581148b9204ab37f108f07360"},
{"file":"cmd/server/main.go","statements":3,"covered":3,"percent":100.00000000,"sha256":"c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495"},
{"file":"internal/controller/http/fiber/stream.go","statements":14,"covered":14,"percent":100.00000000,"sha256":"6bc72fdc23332e08e4dee8a5ed3f9110952208af86b529d5d4847ebcf00dd4c3"},
{"file":"internal/config/config.go","statements":17,"covered":17,"percent":100.00000000,"sha256":"8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa"},
{"file":"internal/service/interface.go","statements":0,"covered":0,"percent":null,"sha256":"2e5597cdc59a0e6b8f587ece7c42d9c790617c8f462baf02c16ca851790a1ded"},
{"file":"internal/controller/http/fiber/attachments.go","statements":23,"covered":23,"percent":100.00000000,"sha256":"179cc4b26b87991f4f5876c726c775ec0b8ce22a1ac28c3a5e5a13413301a224"},
{"file":"internal/admission/limiter.go","statements":16,"covered":16,"percent":100.00000000,"sha256":"a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4"},
{"file":"internal/store/postgres/sessions.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"889a63b51b29012f4ae5499d1c0577fe29f2f2959b05629f8e123715cfc1f75f"},
{"file":"internal/store/postgres/users.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"d6adb976909a211aa195ef3ac752cc02f5422944bbc6aff5ea25227214415b1c"},
{"file":"internal/service/production/users.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"30d3299b63ab49163c3654ad22e0b9f74094181ee13e3931775eab4df6fc38ce"},
{"file":"internal/controller/http/fiber/error_codes.go","statements":0,"covered":0,"percent":null,"sha256":"3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41"},
{"file":"cmd/server/media.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"6b4274e5eb7530f2ea80dc663d80312e6d2ba93f1fe1b68204ebc37ca66c54a5"},
{"file":"cmd/server/healthcheck.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"5ba854fae2321ed9e57f8776fe1503d567ffe2c88a2d4c4abb9bf74d84cc9fce"},
{"file":"internal/service/authentication/service.go","statements":48,"covered":47,"percent":97.91666667,"sha256":"295ac01d910f0b6eb94098c3808e7af5d878dc5e401c85094db86598b786cc93"},
{"file":"internal/service/cache.go","statements":0,"covered":0,"percent":null,"sha256":"033986bd1fb166564c0cd5fafea74699d22c4fe4a6143e69fbd72c89f5eafdb0"},
{"file":"internal/store/postgres/attachments.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"d2af1aa998f902640c17e913dd9b591fc6612c8b4410786080b6023ee13a6a9c"},
{"file":"internal/config/persistence.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"28c61d23db4ca2ef7ed952451f465318865076d2393eaa94ff5d7bb339c4c06b"}
],"passed":true}
+112
View File
@@ -0,0 +1,112 @@
warning: GOCOVERDIR not set, no coverage data emitted
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/cmd/server 3.503s coverage: 31.1% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission 2.633s coverage: 1.1% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config 2.641s coverage: 5.5% of statements in ./...
gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller coverage: 0.0% of statements
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller/http/fiber 2.794s coverage: 43.5% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor 2.647s coverage: 2.3% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/hashring 3.107s coverage: 1.3% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/media 2.687s coverage: 9.8% of statements in ./...
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto [no test files]
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/http [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/objectstore 2.769s coverage: 3.2% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/password 3.586s coverage: 1.1% of statements in ./...
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/authentication 2.638s coverage: 3.6% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/production 2.542s coverage: 14.5% of statements in ./...
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/memory 2.171s coverage: 6.1% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres 4.483s coverage: 16.1% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/strictjson 2.163s coverage: 3.2% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/valkey 2.229s coverage: 7.5% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/student-tests 2.186s coverage: 0.0% of statements in ./...
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
100.00% internal/store/memory/store.go
100.00% internal/service/production/members.go
95.65% internal/config/controller.go
N/A internal/controller/interface.go
100.00% internal/config/logger.go
100.00% internal/valkey/admission.go
100.00% internal/service/production/service.go
94.44% internal/password/password.go
100.00% internal/strictjson/decode.go
93.55% internal/store/postgres/messages.go
N/A internal/service/cursor.go
100.00% internal/media/reconcile.go
100.00% cmd/server/reconcile.go
95.45% internal/store/memory/users.go
100.00% internal/store/memory/capacity.go
100.00% internal/service/production/access.go
97.30% internal/controller/http/fiber/handlers.go
100.00% internal/controller/http/fiber/routes.go
100.00% internal/controller/http/fiber/mapping.go
100.00% internal/controller/http/fiber/health.go
100.00% internal/media/validation.go
94.44% internal/cursor/codec.go
100.00% internal/controller/fx.go
94.12% internal/service/production/pages.go
N/A internal/service/errors.go
100.00% internal/config/objectstore.go
100.00% internal/media/service.go
100.00% internal/service/production/errors.go
N/A internal/controller/http/fiber/headers.go
100.00% cmd/server/commands.go
94.74% internal/store/memory/messages.go
92.31% internal/objectstore/client.go
N/A internal/model/dto/models.go
90.48% internal/store/postgres/idempotency.go
92.31% internal/store/postgres/chats.go
100.00% internal/service/production/chats.go
100.00% internal/media/run_reconcile.go
100.00% internal/controller/http/fiber/error_registry.go
100.00% internal/controller/http/fiber/public_errors.go
100.00% internal/controller/http/fiber/metrics.go
N/A internal/controller/http/fiber/dependencies.go
95.24% internal/hashring/ring.go
90.00% cmd/server/logger.go
100.00% internal/store/memory/ordering.go
100.00% internal/media/orphans.go
91.67% internal/controller/http/fiber/decode.go
100.00% internal/controller/http/fiber/auth.go
100.00% internal/service/production/messages.go
100.00% internal/config/environment.go
90.91% cmd/server/persistence.go
100.00% internal/service/production/validation.go
95.83% internal/service/production/creation.go
90.00% internal/objectstore/list.go
N/A internal/model/http/models.go
N/A internal/model/dto/attachment.go
100.00% cmd/server/app.go
94.12% internal/valkey/cache.go
96.88% internal/store/postgres/reconcile.go
100.00% internal/service/production/pagination.go
N/A internal/service/auth.go
N/A internal/model/dto/session.go
100.00% internal/config/memory.go
97.56% internal/controller/http/fiber/middleware.go
100.00% internal/controller/http/fiber/controller.go
100.00% internal/controller/http/fiber/configure.go
N/A internal/admission/distributed.go
100.00% internal/controller/http/fiber/errors.go
100.00% cmd/server/s3_bootstrap.go
100.00% internal/store/memory/chats.go
N/A internal/store/interface.go
91.67% internal/controller/http/fiber/lifecycle.go
97.14% internal/valkey/client.go
92.98% internal/store/postgres/store.go
100.00% cmd/server/main.go
100.00% internal/controller/http/fiber/stream.go
100.00% internal/config/config.go
N/A internal/service/interface.go
100.00% internal/controller/http/fiber/attachments.go
100.00% internal/admission/limiter.go
100.00% internal/store/postgres/sessions.go
95.24% internal/store/postgres/users.go
100.00% internal/service/production/users.go
N/A internal/controller/http/fiber/error_codes.go
100.00% cmd/server/media.go
94.74% cmd/server/healthcheck.go
97.92% internal/service/authentication/service.go
N/A internal/service/cache.go
95.24% internal/store/postgres/attachments.go
100.00% internal/config/persistence.go
+3
View File
@@ -0,0 +1,3 @@
go version go1.26.1 darwin/arm64
Darwin arm64
2026-10-29T13:27:20Z
+65
View File
@@ -0,0 +1,65 @@
#0 building with "asisti-builder" instance using docker-container driver
#1 [internal] load build definition from Dockerfile
#1 transferring dockerfile: 583B done
#1 DONE 0.0s
#2 [internal] load metadata for docker.io/library/golang:1.26.1-alpine3.23
#2 DONE 2.0s
#3 [internal] load .dockerignore
#3 transferring context: 145B done
#3 DONE 0.0s
#4 [build 1/7] FROM docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039
#4 resolve docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 done
#4 DONE 0.0s
#5 [internal] load build context
#5 transferring context: 413.07kB 0.0s done
#5 DONE 0.0s
#6 [build 2/7] WORKDIR /src
#6 CACHED
#7 [build 3/7] COPY go.mod go.sum ./
#7 DONE 0.0s
#8 [build 4/7] RUN go mod download
#8 DONE 66.3s
#9 [build 5/7] COPY cmd/ ./cmd/
#9 DONE 0.0s
#10 [build 6/7] COPY internal/ ./internal/
#10 DONE 0.0s
#11 [build 7/7] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
#11 DONE 62.9s
#12 [runtime 1/1] COPY --from=build /out/server /server
#12 DONE 0.0s
#13 exporting to image
#13 exporting layers
#13 exporting layers 0.6s done
#13 exporting manifest sha256:3a10e818a9f128428d08a8c5546e259943077ef339a90d5f74952597a2185453 done
#13 exporting config sha256:c0c16b388693366ca11526b37426a3f3256591b18df33276647a5e96fd674bdd done
#13 exporting attestation manifest sha256:5457631740a3ffa079de9c58509922fd53b1b0f6abcde0459a1c121f8e3ee031 done
#13 exporting manifest list sha256:36d4ccb6d3c44e7a2540187a628d148e8c1601cdc3215eb81fc37edf48f5c2ce done
#13 pushing layers
#13 ...
#14 [auth] mtusi2026lab4:pull,push token for asisti.registry.twcstorage.ru
#14 DONE 0.0s
#13 exporting to image
#13 pushing layers 28.2s done
#13 pushing manifest for asisti.registry.twcstorage.ru/mtusi2026lab4:solution-20261029@sha256:36d4ccb6d3c44e7a2540187a628d148e8c1601cdc3215eb81fc37edf48f5c2ce
#13 pushing manifest for asisti.registry.twcstorage.ru/mtusi2026lab4:solution-20261029@sha256:36d4ccb6d3c44e7a2540187a628d148e8c1601cdc3215eb81fc37edf48f5c2ce 3.8s done
#13 DONE 32.6s
#15 resolving provenance for metadata file
#15 DONE 0.0s
View build details: docker-desktop://dashboard/build/asisti-builder/asisti-builder0/3sb0okjofqie2jze3vr1rhanl
+20
View File
@@ -0,0 +1,20 @@
#0 building with "asisti-builder" instance using docker-container driver
#1 [internal] load build definition from Dockerfile
#1 transferring dockerfile: 583B done
#1 DONE 0.0s
#2 [internal] load metadata for docker.io/library/golang:1.26.1-alpine3.23
#2 ERROR: failed to authorize: failed to fetch anonymous token: Get "https://auth.docker.io/token?scope=repository%3Alibrary%2Fgolang%3Apull&service=registry.docker.io": EOF
------
> [internal] load metadata for docker.io/library/golang:1.26.1-alpine3.23:
------
Dockerfile:1
--------------------
1 | >>> FROM golang:1.26.1-alpine3.23 AS build
2 | WORKDIR /src
3 | COPY go.mod go.sum ./
--------------------
ERROR: failed to solve: failed to fetch anonymous token: Get "https://auth.docker.io/token?scope=repository%3Alibrary%2Fgolang%3Apull&service=registry.docker.io": EOF
View build details: docker-desktop://dashboard/build/asisti-builder/asisti-builder0/5ql060od551yb87e96hnuvzf8
+20
View File
@@ -0,0 +1,20 @@
{
"buildx.build.provenance": {
"buildType": "",
"invocation": {
"configSource": {},
"parameters": {},
"environment": {
"platform": ""
}
}
},
"buildx.build.ref": "asisti-builder/asisti-builder0/3sb0okjofqie2jze3vr1rhanl",
"containerimage.descriptor": {
"mediaType": "application/vnd.oci.image.index.v1+json",
"digest": "sha256:36d4ccb6d3c44e7a2540187a628d148e8c1601cdc3215eb81fc37edf48f5c2ce",
"size": 855
},
"containerimage.digest": "sha256:36d4ccb6d3c44e7a2540187a628d148e8c1601cdc3215eb81fc37edf48f5c2ce",
"image.name": "asisti.registry.twcstorage.ru/mtusi2026lab4:solution-20261029"
}
+1
View File
@@ -0,0 +1 @@
0 issues.
+16
View File
@@ -0,0 +1,16 @@
=== RUN TestReclaimExcludesPublication
--- PASS: TestReclaimExcludesPublication (0.05s)
=== RUN TestReclaimProtectsFreshReservation
--- PASS: TestReclaimProtectsFreshReservation (0.03s)
=== RUN TestMetadataReconciliation
--- PASS: TestMetadataReconciliation (0.03s)
=== RUN TestMeasuredMissingInventory
=== RUN TestMeasuredMissingInventory/100_records
research_test.go:49: records=100 missing=100 elapsed_ms=45.622 apply=false
=== RUN TestMeasuredMissingInventory/1000_records
research_test.go:49: records=1000 missing=1000 elapsed_ms=457.760 apply=false
--- PASS: TestMeasuredMissingInventory (0.58s)
--- PASS: TestMeasuredMissingInventory/100_records (0.08s)
--- PASS: TestMeasuredMissingInventory/1000_records (0.50s)
PASS
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres 1.117s
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://127.0.0.1:18084"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+183
View File
@@ -0,0 +1,183 @@
b063cc345976028b590d616f56581254269503e6ab190ca0380cb75ecb7e5111 cmd/server/app_test.go
3302faabb63a43c83a646e3c2217af28f55707198206c80aae5f18787cb8e627 cmd/server/persistence.go
6b4274e5eb7530f2ea80dc663d80312e6d2ba93f1fe1b68204ebc37ca66c54a5 cmd/server/media.go
5ba854fae2321ed9e57f8776fe1503d567ffe2c88a2d4c4abb9bf74d84cc9fce cmd/server/healthcheck.go
aaa809bfdef5c19eec725d754c6934d45dfb491c2d97b5a135c0bc351d61beaf cmd/server/persistence_test.go
934f5f3cac0307dbb26b38ec232270a1100b83fe54990e16f98a1277126feb14 cmd/server/logger.go
b45f7b28965346df23dcbeeeaf4cd446f9dd5f9c0446558298f96246f1b725d3 cmd/server/s3_bootstrap.go
b5a69912970b440c09e1d3db9a8dcbbe21077ecf848acd389d83cc98ad5189dd cmd/server/app.go
deb6af7778dd9882215785e951784756832df64dafca8d52cb47fa632d07596c cmd/server/healthcheck_test.go
a88c8f29f9482564248bc43d7a6386baca64710932877e5fa7008a31a2ae4c42 cmd/server/reconcile.go
1d16d1df1e0b0d59e7084e78d2e6caa0d30c3240e0bc040a7963f7f6b862c311 cmd/server/commands.go
ed550fa2b8e74b2d8a77264f141516a5a949a01dc681d43e38cf43fc1af8c9c9 cmd/server/media_test.go
c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495 cmd/server/main.go
1ad8dcb7d055fcb8da56d10e1089b47fe1b9cbf848381ded1a4048f8fd41278a internal/password/password_test.go
fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76 internal/password/password.go
6041f376a0f69a66ebf0ecacbd20d03d5d57590ae67585613256b0713e106fdf internal/cursor/codec_test.go
678e197744fb2fc4b51715f51593b98761125bbaddbe4cb1b7032bd6b173ef04 internal/cursor/codec.go
86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0 internal/config/memory.go
8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa internal/config/config.go
28c61d23db4ca2ef7ed952451f465318865076d2393eaa94ff5d7bb339c4c06b internal/config/persistence.go
1c853c0f771e2c75958db8158797f2287e06c8d9efe8856365b7b9c71b1747b0 internal/config/controller.go
7377c7fc286e04292b7c82e4e286cadf409ce833079f794a501456024e73434a internal/config/persistence_test.go
3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988 internal/config/logger.go
c6283fe310747e8297850b48c0a119c1d62db4903dd2c779c6296678563df188 internal/config/objectstore.go
027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3 internal/config/environment.go
4e57110e53843506d1dd7336feaa603538b425a6127988590fdfc9fe3e878323 internal/config/objectstore_test.go
0181673dcc4db2557783941aa8c5b3f61bc0ca6b5196d87e69df000346c40391 internal/config/config_test.go
99e7ffe68dd6405fd9495d1bce7ec8c495859023335aa92c0520fcab48ad913a internal/valkey/cache.go
2db9603f21ceef6a2d245385fbf0977666f4bdb842adbe216c0e294be8d3c02f internal/valkey/client.go
e4931f0a6c5ead7d4a7c14aee1862b9a7d5a6dff9e938ac3a3819034435af28e internal/valkey/client_test.go
f729a0c695ad01f80e7450d0e802c07cfb3f35340b6ea22a20e00348a9b64371 internal/valkey/admission.go
d52fb501e76ddb23c645c1aaa599e32da9d01e50064c9ca97ac0e320ffc7f0c8 internal/admission/limiter_test.go
41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d internal/admission/distributed.go
a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4 internal/admission/limiter.go
ea6273526572b4bfcf681ef2659ea2c1ec74bfedeb5e9bdbd83ebfabe0647bf9 internal/strictjson/decode_test.go
3830b93225ff8056993643fd404ab990ddb752fd80fb8ece6410e834b6023f5f internal/strictjson/optional_test.go
d99595e1f74406c5aa617c0ec062afb7f12f116bd86776e87cc9c9a436ff7eea internal/strictjson/decode.go
24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68 internal/controller/interface.go
0b3fad8fc87f561573bf4ee906a48a8fb317385ecc7600bdca3cc61992fa9253 internal/controller/http/fiber/users_test.go
435c87ffd05adbd06cbfe9bd2cfbf1f4ca6a01d185e29c165d46b0da20f8abb3 internal/controller/http/fiber/body_limit_test.go
52dc454454e455f1df3b63a7f7958986fefb850dbdacb2d96dbc9ead153fdb74 internal/controller/http/fiber/public_errors_test.go
be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd internal/controller/http/fiber/configure.go
c810dbed23d3587c50f80aec92843d01158d153e4e3f8bbe03fe9674b18447ee internal/controller/http/fiber/attachments_test.go
ba7fa956feeeb7426ab183438b019588569a5a1212ad9b1a212423211f136d30 internal/controller/http/fiber/controller.go
468f8d5b964d07a63c7900613bc6b84b2bbdaf925e9f549c1970e392de324caf internal/controller/http/fiber/errors_test.go
400914b0bed80b41eb890fb8439c4169dd855fa6f98879fcdc570eceba495be6 internal/controller/http/fiber/auth_test.go
a46a8429feb8c8761fde4d20d431ebd875b9c0e2a3deb71750ff6a666cb913b6 internal/controller/http/fiber/messages_test.go
54db82201697bdfcc65712afe61b650f8f0885fc65222dc4cc6d1c3bb07d82dd internal/controller/http/fiber/metrics.go
330913d86e6b3f1bedf14f770df7012426f86f4ae2a1cb1fddb2b4f6294a98f8 internal/controller/http/fiber/auth.go
6bc72fdc23332e08e4dee8a5ed3f9110952208af86b529d5d4847ebcf00dd4c3 internal/controller/http/fiber/stream.go
ba1e6f4d2aedb003e9818d33625f74fd1e8ae03e987f0c20d7e4c1d8c9e727ce internal/controller/http/fiber/middleware_test.go
4b2316357f3bdcb74281fd63a11b88aaebeac89a048a152fed6ddd9069793fa9 internal/controller/http/fiber/metrics_test.go
cfa54cff49e70a0f7c2354e60ff84d50b5a19f0d3c3ddd931cdf7872ed1c0e19 internal/controller/http/fiber/handlers.go
41dfd12d3d2a6f518376e2125f4f818c92eff786f061bea89e924cdfcd0aa8db internal/controller/http/fiber/controller_test.go
1b7628b0f313089891e9bfa44fd6e0cdb753375ffd2cf22caf5abdab61f9c102 internal/controller/http/fiber/health.go
f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08 internal/controller/http/fiber/lifecycle.go
fe59de68ad07ae56c061b01a7946e848b3ee41a3005a3ae9fee1843d31aba5ab internal/controller/http/fiber/metrics_labels_test.go
1fbe98b2de99a794a0f2726ad350f258004bd2890660d28b2982c72e5579f3f5 internal/controller/http/fiber/public_errors.go
179cc4b26b87991f4f5876c726c775ec0b8ce22a1ac28c3a5e5a13413301a224 internal/controller/http/fiber/attachments.go
e248223517102e1eecdeba9a5e2d844c0afc14116a56e9a1d76c6afb755e63d1 internal/controller/http/fiber/routes.go
6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d internal/controller/http/fiber/dependencies.go
3905cbc45b0637da007d5e556900d74e3a9d5575de358f8f4584c2327214324c internal/controller/http/fiber/middleware.go
3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41 internal/controller/http/fiber/error_codes.go
a33db3d6e1b01d62c65a28935e7f8890f66c8e60413a079f6ee3d042f814592d internal/controller/http/fiber/fixtures_auth_test.go
9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a internal/controller/http/fiber/error_registry.go
496f50e5693456574614b8a47086a550018884adb37919ce82abf8c4e7e5254d internal/controller/http/fiber/lifecycle_test.go
2db9a0329f722d2ec1cefc529df17875dbc7eb3e50d58319934891c1da3bc7ed internal/controller/http/fiber/mapping.go
9c092ba7bca191f25c3ba9c9a5d1ca844126bee740a4c0262b776e947263ac68 internal/controller/http/fiber/chats_test.go
0f8ac98d5ec9b606f661985515d9a13047ebd262b2c4e99f1a9d61bf8a591dfa internal/controller/http/fiber/decode.go
d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd internal/controller/http/fiber/headers.go
a4a40a11689541409fb804f4a285cbe5c0dc9e620073a8257d410e3db3c882d6 internal/controller/http/fiber/errors.go
af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a internal/controller/fx.go
e347b48cde4d4292505dc3f2834ada4d6c8c2dd133600e281741a13f9f13b104 internal/objectstore/list.go
0e42d39cc3ca70d440fc49dddf614af8a33801ac23a954ac613d6397631a9c3c internal/objectstore/client.go
94732ce0cfd579c4e1bc7a7911aca1d6851b86fbc7665f0101b328d9333e66cc internal/objectstore/client_test.go
e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c internal/hashring/ring.go
606cdf84342b97a63eedfb9cd37aa7c99a489eee54641d8645be930a9ce6be0d internal/hashring/ring_test.go
5e2536b8eba6bb92b751a7b817b6338755008857e3b53920d8da6fb67adeebdb internal/model/dto/models.go
896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb internal/model/dto/session.go
4a7790ef7a3cfc2d9c6f35d42873e04ea48e72a95af2dd173a6f4d2e29c51b46 internal/model/dto/attachment.go
d68827b0bd3e6df4037621b6941298d3923dc348bda5bf314a34861e7c34f04e internal/model/http/models.go
3e6f99e5239d8fa5de5d406acb6f95485bd6d4fc23f1080b8eb6fd8834fbd722 internal/service/auth.go
033986bd1fb166564c0cd5fafea74699d22c4fe4a6143e69fbd72c89f5eafdb0 internal/service/cache.go
2e5597cdc59a0e6b8f587ece7c42d9c790617c8f462baf02c16ca851790a1ded internal/service/interface.go
99a25f75b1289d812c125a2a68640869a2b879abd205c81155fae7bd96174935 internal/service/production/members.go
30d3299b63ab49163c3654ad22e0b9f74094181ee13e3931775eab4df6fc38ce internal/service/production/users.go
5d66b4430605634a484a1ecd0113f7bce45f0a470dcbf04383a0b124f4717901 internal/service/production/messages_page_test.go
3a3141621df8380873cbd1d4ec7e46c42179862f2e0cfb075e430ce428c8587f internal/service/production/users_test.go
6de190a75ed12c6b07bcf2889a085fd8fe1025bc13981f771e0a84627c377d0d internal/service/production/creation.go
2bba77cbf35f7da04d31c6e6c729b06e077f184478dcdd75529d9359ff8081b8 internal/service/production/chats_page_test.go
6f0cf8ab6c0e07bbb82e6b289e3d734c84ead5b82932db2007ef0c54f159f4cb internal/service/production/service.go
cab4f160ebdb0fc833be84452beda326cf42de4e838914850bd5beb3ad0840c1 internal/service/production/messages_test.go
c14ab6f325015a46dea8ed845f271df0a6ddf610bbcf1312eaf14d557a8c2752 internal/service/production/cache_test.go
cc635314dc6d21ad328a6c6ec60fc4cf199ba95d2c3aa7f229fa312050fe0b4a internal/service/production/service_test.go
550ab142c922a201f72595ce0774a1b07062a06e5b728119ccb6d31cac5c59e6 internal/service/production/access.go
879b0a877f8a4a80ca29aaa18ededc5febbccc6dd8dbcb170be0ac4022bdaeec internal/service/production/pagination_test.go
2b7603e5a4b9796eb722281c4dd32b762facadbb97e0006f407bba0267875c67 internal/service/production/fixture_test.go
46f4d77cc32838c28abb57e49ebdc0d30cf36ffe49079b2f84d03c405969a346 internal/service/production/chats.go
76b7c6ee33d98debda99df1ab8272deed64b80aadfec3e079d9d550e0facb4a4 internal/service/production/messages.go
064847cd4f6b9d4cd50913823e20d3538b78aadf056660dafd720d79c0ecf5ca internal/service/production/pages_test.go
0eb30c852f178768e11457a29aa978127d22c4c6f0019aea004123265da5e789 internal/service/production/pages.go
423d4be24ae5ea70d47d2da5b781296e8bb3cebdea90abf31c2117056bd17bbd internal/service/production/validation.go
45e9c94fa662b855608def8830e7eafd05707f5a96b33fdddf640ac87085bcd1 internal/service/production/chats_test.go
a0935444ad82e2b92fd975826e91e25cb53bbafbebe352be887571359264d62e internal/service/production/pagination.go
27abf6ee6231c9e89643b512bd5694f32872e357831ec0d6bd1302d754a5d4dd internal/service/production/errors.go
430996f921d5dab91b47a6f796e19c2b7cb31d386572b326adec581b8be9f6b7 internal/service/cursor.go
295ac01d910f0b6eb94098c3808e7af5d878dc5e401c85094db86598b786cc93 internal/service/authentication/service.go
484d1f64a400a58b27bc9542486626fac2c70e26bd7a48236560118b2c9a8a7d internal/service/authentication/service_test.go
1c36cfef90643276e1c83aede658af6b9e2eb0152b7ae68c2c8abd0e7bf655cd internal/service/errors.go
946a1a7a72badf6a80b9ff9a5c850914f46cf5ebde13a5f9f945514f0e188f88 internal/store/memory/users.go
b797c0b13989ec3de92402414d8d82c2a6570abb130edb5ec3b9318368995a53 internal/store/memory/users_test.go
7b836b76e7681ab5ab78a2a30017f5e9a8cb38cbe5c8c94ec1ad65a606c9f2e7 internal/store/memory/store_test.go
da46630a8a5a3625e40677cd4d5e268e2c320a8f1ed272c2f6c05f45cb0f458b internal/store/memory/capacity.go
da8ff00199151be0462c5a27951fa7b7061a42a1ec9cabce9ed8f46d99820480 internal/store/memory/messages_test.go
23fa65457a7b5a3d456fc4b518b76eeed8d4063b3e5090f62ae8c57d276f018d internal/store/memory/store.go
69652b5c7b3834503efe29ae3847db6b0000b9fb0a15774cd7cb20bc8a003e8e internal/store/memory/chats.go
ca4526c55af46dc8f4205aa8402d6819e05a46840d704d8caea0a477014f70ab internal/store/memory/messages.go
4ed267c6ecd734687e5af3645d18a1a6b2608ca9bda19de3e2e0676f4fa8c416 internal/store/memory/ordering.go
38187635fd996dba52ddf3da216ba6143cb552d1e6375c4b19ba98eb8b8bf26a internal/store/memory/chats_test.go
a91695ddbf0162fad728643e5d33002bbd382d03d950c433ca9c1f44cdbdc2ba internal/store/interface.go
d6adb976909a211aa195ef3ac752cc02f5422944bbc6aff5ea25227214415b1c internal/store/postgres/users.go
448f0287ddd1e68914edcda4b39cc90daaac952a8e19a9e938ad78d27601b590 internal/store/postgres/migrations/003_attachments.sql
3678bb935ed8006d4bdc3e928231cfc5e8ba29e397d6b70122675933acd2a6f4 internal/store/postgres/migrations/002_idempotency.sql
8b8bf6a255cc48cee4b3e4adc94c23cf6955ecf5dfba689bba973dfccbd1b1cb internal/store/postgres/migrations/001_initial.sql
3f40c0225530edb325550cd380c643e2da530bce3b18c93c10093d9a7b4559ee internal/store/postgres/attachments_test.go
be0d432f8c9db7f7d8c44f7c230bddeb1d94509fe22669efd8ca7ac990787b27 internal/store/postgres/store_test.go
faedbc4f7bd15fa6aa14479c9285beac14063529bd2d1a200b1128b894b22363 internal/store/postgres/errors_test.go
889a63b51b29012f4ae5499d1c0577fe29f2f2959b05629f8e123715cfc1f75f internal/store/postgres/sessions.go
c82ce119e5bf06a701df762ded6398886781962581148b9204ab37f108f07360 internal/store/postgres/store.go
b22da29bf82729f76307247476b828f294aaf8ea4fe9285cb1cd7a8d0636dc01 internal/store/postgres/idempotency_test.go
733c121222dc75448c363874aa131e1b9ce89b957a5d45b667c08e33ebb3867a internal/store/postgres/research_test.go
448da4c0755f16184d9bbe6cdef35b9ea4ffcb04b7da832ff82f5c1c34ad0966 internal/store/postgres/idempotency.go
cbd4e074fa631b4e2e6a746f01e2d634391cddfd1d4e60d58ca0182524b97eaa internal/store/postgres/chats.go
3b9f6cc9906f3007cf416bbfc01046794c652a8589c3ea43e57a03b1c8c26bc2 internal/store/postgres/messages.go
375914d765b4ae8e1ba25767bb6e96d6de8ce29a8787055f4242971cb0b5900d internal/store/postgres/reconcile_fixture_test.go
d2af1aa998f902640c17e913dd9b591fc6612c8b4410786080b6023ee13a6a9c internal/store/postgres/attachments.go
ab6d8b2018f910a0ef4fafc3d203dd4efcf63a64f7bef613739f656f89b69670 internal/store/postgres/reconcile.go
77f45226996a1d83f3f4ca2ac6980967d4f7cc1f17f3fd2d324ef267237523c0 internal/media/service.go
2de8c90b6fbc1f680ff34f17a3ad2dead27b27d0ba99e18ba7f1f44175d2e07a internal/media/run_reconcile_test.go
f61e243e07e9260f3d497a8d807e670368575a30842c2c9324e3af9f45c2894f internal/media/service_test.go
327ee894c8c9afa5bcf8236ed4c91befd66699c0ca33178e9690705764faf002 internal/media/orphans.go
16a99b15901009e4861cdd30a24a433d8d36782745af1212e3dffa8b0d50906a internal/media/validation.go
ca279564fe8b3ed9ecba34f071577ef22726f34ca41981f83b985b3bf3e620e3 internal/media/reconcile_test.go
278dc4c8720348df752801adf04a30d1b7508a730665122693ce1dd7b90c376a internal/media/reconcile.go
3255403afcb9486d33c5bb45b5afa9c3c9b85596ce97f86ac2f224011cd8a860 internal/media/run_reconcile.go
fc6e5dfde6eba735601d7087f94b3dbf8905fab7ecbaff0d5c09e11769a19944 internal/media/validation_test.go
df6202fba7566de0489aabc5e7f3d31ad1515673eea106b0332355a8bbc6b1fe charts/messenger/Chart.yaml
d0e0b2382082f0c52dc3c55b53334743680224d0f8cbc4c5ee9b623ff1299e92 charts/messenger/values.schema.json
2c65bf5e0025ff487370acf5039d33ad8308dabee2dccebbc14743c74aeacdb7 charts/messenger/templates/api.yaml
30fa7bc17d161ba63e3713b5b986d90197c0fc54d6eab25bbfad683190162982 charts/messenger/templates/guard.yaml
a5aba49edfb383bd892865349bbc9749769a61b0cc703374948b923a85fc650c charts/messenger/templates/ingress.yaml
7937ef25fb5d23a231cceedfbf79ed36244e9c27ce409db938745dec43e5272e charts/messenger/templates/migrate.yaml
68cd59c6f4d7a24e384509fc920b996031bb949c76c60fe051e4be19882d5616 charts/messenger/templates/network-policy.yaml
a4fa258f575e01fba40dd0616d37e3defb43b84b5c83949420543621ac70af74 charts/messenger/templates/hpa.yaml
0fc92783f1a210eb5af8cf55ee531a8a474429e65fb37033d17b16f45f515658 charts/messenger/templates/postgres.yaml
852c4d2ce18a1c4be914ea613c12bb033a2fd55143cd2f9a04eb9080b1343838 charts/messenger/templates/s3.yaml
3ae360e746fba7cc0f17d8c64972cc5ba1caf4b747cc0805515c0ea660bdfabf charts/messenger/templates/_helpers.tpl
9e64fabb33291e5bfc55cc4f40e4e3ee3651e7d3151ca69b7c05e93165b63545 charts/messenger/templates/valkey.yaml
3b917fc87b39bab6d15a5e9d7877bb0771e2c052cb2b90409ed38010f2739814 charts/messenger/templates/load.yaml
9d95b4a1b729cb04f3ba0cdcb1fc79c662c1dcd74acc334e6deac74a0dfd3e8a charts/messenger/templates/monitoring.yaml
6e83a4e41e4b765cb9c651df4b45779ede0c70313f5d6a3c6ca1b7c8e82a8a73 charts/messenger/values.yaml
aada77ad42debd425cec516e33668a640fc0257f30d1a9aa2f15534ed042bf01 scripts/restart.sh
7c4402c2a6ab80d3b4676e1866d6ecc87b6daea14c080bcb9be9a7e8b959d671 scripts/check_contract.py
08f7633fd1e133ce2c83d15d6921b1f9a9a2d3458df711592a169fb262855a98 scripts/local-action.sh
1bcf34394520b89d95b7605ec56675be799eea920e83cfbba306d5dc0a6d9811 scripts/stop-one.example.sh
d1b09abb1447c9cbfbd17edc12491f0985dcd5652b16cb71a93651d289b46ce8 scripts/stop-one.sh
f7a70569c1fe573ad4fedc5680b77d6d6215c78a4b8bbcd666fefd07f1a8818e scripts/measure-upload.sh
b231016d1e6be9735a6a8925031c6b0e7bf2be9f48be8e7b7aaa2ed5db8b2fbc scripts/port-forward.sh
32a5510e87db858abced249b7ebc23024b41c327170e0f0ff6549bbd444a1fd2 scripts/test-local.sh
e70fd589b93cf610e7f18ecd741be9cebeea4320bb152d58438259cead557a84 scripts/init-secrets.sh
ad9562009b57fa9438740988a6bc9e77758f7e242f781129a8375ed674b99dbf scripts/coverage.sh
4e981acbfc10dac58817bf922d5896e996798551fedc1b2385130e1cddb13d54 scripts/validate_openapi.py
0328246ba75defbced992104e986fde973f63e3830d83251eced5953263e944b scripts/restart.example.sh
0587e6b6d9387fb0179b23d283694121300732c898aad95eabe0376f744fe94c scripts/coverage.awk
a7f93eedc694e099e2b609d04bee5e0920e0c4b06b0692a5688d4ba5913d7259 student-tests/quality_test.go
280f6eaf50aaea25fda4ce6f5829c49403c396d9104f972b5157b954276fc355 student-tests/README.md
817e6702852fc7d168e22cef15daafd3bd13c1ad52036f4533eecc3b2324b3ed student-tests/load/idempotency.js
2ca01d154f2ba1e6f72f036e02061967a8ba149f5b18131eb5760e2692bd76c2 student-tests/load/failover.js
0a58dff9ad7acf8f228e0fd1c2a670bbe7e18a11360715b47659104832e34892 student-tests/load/scaling.js
b370b7793f5c8fc66f250b9e4776b4edbaaa5646eb4425bb5b6e4fe2d242c6b3 student-tests/load/attachments.js
e83331ee1c444bc35898d295a23b767f9c7eca77ae81d2a8a218fa44b976eb27 student-tests/load/hpa.js
f47019141be4ac06d912cbd4281d94d181625a08637801627e897633bb20a124 student-tests/plans.sql
f7ca02dfce0db42f72594d794eda5821a9125e7a2b6966df731f32869a5f0b43 student-tests/research.sql
+8
View File
@@ -0,0 +1,8 @@
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
helm lint charts/messenger
==> Linting charts/messenger
[INFO] Chart.yaml: icon is recommended
1 chart(s) linted, 0 chart(s) failed
helm template lab2 charts/messenger >/dev/null
+21
View File
@@ -0,0 +1,21 @@
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/cmd/server 2.214s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission 1.483s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config 1.306s
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller/http/fiber 1.671s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor 1.512s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/hashring 1.627s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/media 1.312s
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto [no test files]
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/http [no test files]
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/objectstore [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/password 2.280s
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/authentication 1.520s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/production 1.492s
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/memory 1.517s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/postgres 2.514s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/strictjson 1.234s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/valkey 1.328s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/student-tests 1.329s
+1
View File
@@ -0,0 +1 @@
peak_rss_kib=80032
+24
View File
@@ -0,0 +1,24 @@
8288
8288
8288
8288
8288
8288
34672
75600
75856
75952
75952
75984
79472
79712
79776
79824
79968
80032
80032
80032
80032
80032
80032
80048
+218
View File
@@ -0,0 +1,218 @@
{
"metrics": {
"vus": {
"value": 10,
"min": 10,
"max": 10
},
"http_req_waiting": {
"avg": 9.315203045685283,
"min": 1.592,
"med": 7.114,
"max": 74.707,
"p(90)": 21.329800000000002,
"p(95)": 23.296
},
"attachment_upload_ms": {
"p(90)": 18.738200000000003,
"p(95)": 19.585549999999998,
"avg": 9.961129999999999,
"min": 2.953,
"med": 8.788,
"max": 26.254
},
"iterations": {
"count": 100,
"rate": 79.42408011030416
},
"http_req_sending": {
"avg": 0.028802030456852767,
"min": 0.002,
"med": 0.033,
"max": 0.184,
"p(90)": 0.056,
"p(95)": 0.06779999999999997
},
"data_received": {
"count": 7575266,
"rate": 6016585.336408634
},
"iteration_duration": {
"min": 53.103833,
"med": 63.8951045,
"max": 82.034333,
"p(90)": 72.3499792,
"p(95)": 75.46148929999998,
"avg": 63.88111499000001
},
"http_req_duration": {
"avg": 9.824152284263961,
"min": 2.345,
"med": 7.622,
"max": 74.903,
"p(90)": 21.3578,
"p(95)": 23.354999999999997
},
"http_req_receiving": {
"min": 0.007,
"med": 0.027,
"max": 3.207,
"p(90)": 1.4660000000000002,
"p(95)": 1.9305999999999999,
"avg": 0.4801472081218276
},
"attachments_rejected": {
"count": 33,
"rate": 26.209946436400376
},
"attachments_ready": {
"count": 67,
"rate": 53.21413367390379,
"thresholds": {
"count>0": false
}
},
"http_req_blocked": {
"avg": 0.021106598984771616,
"min": 0,
"med": 0.002,
"max": 0.538,
"p(90)": 0.002,
"p(95)": 0.2417999999999998
},
"http_req_connecting": {
"avg": 0.01655329949238579,
"min": 0,
"med": 0,
"max": 0.345,
"p(90)": 0,
"p(95)": 0.223
},
"http_req_failed": {
"passes": 33,
"fails": 164,
"value": 0.16751269035532995
},
"data_sent": {
"count": 11229337,
"rate": 8918797.614736026
},
"http_req_duration{expected_response:true}": {
"avg": 10.176689024390244,
"min": 2.345,
"med": 7.8205,
"max": 74.903,
"p(90)": 22.5853,
"p(95)": 23.63235
},
"http_req_tls_handshaking": {
"avg": 0,
"min": 0,
"med": 0,
"max": 0,
"p(90)": 0,
"p(95)": 0
},
"vus_max": {
"value": 10,
"min": 10,
"max": 10
},
"checks": {
"passes": 100,
"fails": 0,
"thresholds": {
"rate==1": false
},
"value": 1
},
"http_reqs": {
"count": 197,
"rate": 156.4654378172992
}
},
"setup_data": [
{
"chat": "92b45da6-9c02-443b-82a9-3634b9639297",
"headers": {
"Authorization": "Bearer gG5LxLp2-l_3BaVgaY7cvALh3UrC-DmIuUKpWzs8k2k"
}
},
{
"chat": "378534fc-c899-4654-ab95-c7a3cad98974",
"headers": {
"Authorization": "Bearer XntfANbWk2OXHzE79bLzKapkhBQoFTwX3IeHMdzMtEo"
}
},
{
"chat": "b72c4972-4d62-47fd-adda-1f6e75748141",
"headers": {
"Authorization": "Bearer ah5FxhFVT3wzblpoVdLUJZRGQO4HLuu_PT3tWBTFI1k"
}
},
{
"chat": "77ad720e-ea48-4efc-a114-902d55c7d751",
"headers": {
"Authorization": "Bearer zbl3HvoYSTJNfJ7oTpKjaEzlwZw-9qao9jWk6GalRd8"
}
},
{
"chat": "ecd393ce-d8ce-48a2-85b0-673182b1a7d4",
"headers": {
"Authorization": "Bearer OHL_jNEfTJFARw6Cyxae5KhVhXK-P17ZzLQZ5uL9MIM"
}
},
{
"chat": "28134e88-c4ae-4c07-b080-ee722e4c8bbd",
"headers": {
"Authorization": "Bearer dcvmA_MGREYsI65JKDeMF06xPVTdCt0kwIftQoHSoXk"
}
},
{
"chat": "3da11cb6-af5f-4c82-b0ca-5e0bb2117582",
"headers": {
"Authorization": "Bearer SLkmTQsYV1LRptZmVHuc5bK_FMHSXjLF-gA6Q8pByuk"
}
},
{
"chat": "81b08113-80c0-4b48-905a-327a76cd9ab8",
"headers": {
"Authorization": "Bearer ByzqqUPpkAPpUS3JY1o-joitFg0t5aSjHLB4X1U3iv0"
}
},
{
"chat": "1d08c8a5-348e-4754-90ba-ec473306fc6a",
"headers": {
"Authorization": "Bearer jGhMP_A92jtjrTygdmWE-7vMlArSdAc5ZPmCJtJAz9g"
}
},
{
"chat": "ba310d60-ac80-40a3-bda4-fcc947c121d1",
"headers": {
"Authorization": "Bearer e3Aaez_P-595tPb7BnFGMq0oMVsCT4fpkTaWRR0ru4g"
}
}
],
"root_group": {
"name": "",
"path": "",
"id": "d41d8cd98f00b204e9800998ecf8427e",
"groups": {},
"checks": {
"bounded overload": {
"id": "c635697b57e40e018ab59d4990b7dfec",
"passes": 33,
"fails": 0,
"name": "bounded overload",
"path": "::bounded overload"
},
"download complete": {
"name": "download complete",
"path": "::download complete",
"id": "b059a8458a190cb232f32a0831d24c02",
"passes": 67,
"fails": 0
}
}
}
}
+64
View File
@@ -0,0 +1,64 @@
/\ Grafana /‾‾/
/\ / \ |\ __ / /
/ \/ \ | |/ / / ‾‾\
/ \ | ( | (‾) |
/ __________ \ |_|\_\ \_____/
execution: local
script: student-tests/load/attachments.js
output: -
scenarios: (100.00%) 1 scenario, 10 max VUs, 10m30s max duration (incl. graceful stop):
* default: 100 iterations shared among 10 VUs (maxDuration: 10m0s, gracefulStop: 30s)
running (00m01.0s), 10/10 VUs, 59 complete and 0 interrupted iterations
default [ 59% ] 10 VUs 00m00.4s/10m0s 059/100 shared iters
█ THRESHOLDS
attachments_ready
✓ 'count>0' count=67
checks
✓ 'rate==1' rate=100.00%
█ TOTAL RESULTS
checks_total.......: 100 79.42408/s
checks_succeeded...: 100.00% 100 out of 100
checks_failed......: 0.00% 0 out of 100
✓ bounded overload
✓ download complete
CUSTOM
attachment_upload_ms...........: avg=9.96ms min=2.95ms med=8.78ms max=26.25ms p(90)=18.73ms p(95)=19.58ms
attachments_ready..............: 67 53.214134/s
attachments_rejected...........: 33 26.209946/s
HTTP
http_req_duration..............: avg=9.82ms min=2.34ms med=7.62ms max=74.9ms p(90)=21.35ms p(95)=23.35ms
{ expected_response:true }...: avg=10.17ms min=2.34ms med=7.82ms max=74.9ms p(90)=22.58ms p(95)=23.63ms
http_req_failed................: 16.75% 33 out of 197
http_reqs......................: 197 156.465438/s
EXECUTION
iteration_duration.............: avg=63.88ms min=53.1ms med=63.89ms max=82.03ms p(90)=72.34ms p(95)=75.46ms
iterations.....................: 100 79.42408/s
vus............................: 10 min=10 max=10
vus_max........................: 10 min=10 max=10
NETWORK
data_received..................: 7.6 MB 6.0 MB/s
data_sent......................: 11 MB 8.9 MB/s
running (00m01.3s), 00/10 VUs, 100 complete and 0 interrupted iterations
default ✓ [ 100% ] 10 VUs 00m00.7s/10m0s 100/100 shared iters
View File
+4
View File
@@ -0,0 +1,4 @@
2026-10-29T13:13:36Z target=local-b action=stop
2026-10-29T13:13:51Z action=restart-api-postgres-valkey-s3 retained-container-filesystems
2026-10-29T13:23:13Z target=local-b action=stop
2026-10-29T13:23:28Z action=restart-api-postgres-valkey-s3 retained-container-filesystems
+1
View File
@@ -0,0 +1 @@
1ec59037d8730a8a00e7fce27716d1925a29dc291e6c504e02cb427de2aebf51 /var/folders/j2/q072k5hn69lbhbzd5sbzrzbm0000gp/T/tmp.ZnJzHrjm5f/server
+4
View File
@@ -0,0 +1,4 @@
python3 tests/resilience.py --mode failover --action-script "/Users/marlo/go/src/gitflick.ru/vlad_marlo/gitea/mtusi2026lab4/scripts/local-action.sh" --base-url "http://127.0.0.1:62881"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 115, "failed_attempts": 0, "first_recovery_seconds": 0.148}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
+1
View File
@@ -0,0 +1 @@
go version go1.26.1 darwin/arm64
View File
View File
+3
View File
@@ -0,0 +1,3 @@
python3 tests/resilience.py --mode persistence --action-script "/Users/marlo/go/src/gitflick.ru/vlad_marlo/gitea/mtusi2026lab4/scripts/local-action.sh" --base-url "http://127.0.0.1:62881"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://127.0.0.1:62881"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://127.0.0.1:62881"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+55
View File
@@ -0,0 +1,55 @@
module gitea.privcloud.tech/vlad_marlo/mtusi2026lab4
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/prometheus/client_golang v1.23.2
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/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/goccy/go-json v0.10.5 // 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.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.11 // 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/minio/crc64nvme v1.0.2 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/minio-go/v7 v7.0.95 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/tinylib/msgp v1.3.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
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.51.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
google.golang.org/protobuf v1.36.8 // indirect
)
+128
View File
@@ -0,0 +1,128 @@
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
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/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
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.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU=
github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
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/minio/crc64nvme v1.0.2 h1:6uO1UxGAD+kwqWWp7mBFsi5gAse66C4NXO8cmcVculg=
github.com/minio/crc64nvme v1.0.2/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.95 h1:ywOUPg+PebTMTzn9VDsoFJy32ZuARN9zhB+K3IYEvYU=
github.com/minio/minio-go/v7 v7.0.95/go.mod h1:wOOX3uxS334vImCNRVyIDdXX9OsXDm89ToynKgqUKlo=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
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/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
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/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
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/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
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=
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
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/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
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=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
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")
}
}
+160
View File
@@ -0,0 +1,160 @@
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 {
// InstanceID identifies this API process to the load balancer diagnostics.
InstanceID string
// 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: 10 << 20,
MaxConnections: 16,
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 {
cfg.InstanceID = os.Getenv("INSTANCE_ID")
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
}
+35
View File
@@ -0,0 +1,35 @@
package config
import (
"fmt"
"os"
)
// ObjectStore contains only the S3 adapter's connection settings.
type ObjectStore struct {
// Endpoint is host:port, without a URL scheme.
Endpoint string
// Bucket is the private application bucket.
Bucket string
// AccessKey is the restricted service identity.
AccessKey string
// SecretKey is supplied by the runtime secret provider.
SecretKey string
// Secure enables certificate-verified TLS.
Secure bool
}
// NewObjectStore validates S3 settings independently of their use.
func NewObjectStore() (*ObjectStore, error) {
cfg := &ObjectStore{
Endpoint: os.Getenv("S3_ENDPOINT"),
Bucket: os.Getenv("S3_BUCKET"),
AccessKey: os.Getenv("S3_ACCESS_KEY"),
SecretKey: os.Getenv("S3_SECRET_KEY"),
Secure: os.Getenv("S3_TLS") != "false",
}
if cfg.Endpoint == "" || cfg.Bucket == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
return nil, fmt.Errorf("S3 endpoint, bucket and scoped credentials required")
}
return cfg, nil
}
+24
View File
@@ -0,0 +1,24 @@
package config
import "testing"
// TestObjectStoreConfiguration verifies mandatory credentials and opt-in local plaintext.
func TestObjectStoreConfiguration(t *testing.T) {
t.Run("missing credentials", func(t *testing.T) {
t.Setenv("S3_ENDPOINT", "")
if _, err := NewObjectStore(); err == nil {
t.Fatal("missing endpoint accepted")
}
})
t.Run("local configuration", func(t *testing.T) {
t.Setenv("S3_ENDPOINT", "localhost:9000")
t.Setenv("S3_BUCKET", "attachments")
t.Setenv("S3_ACCESS_KEY", "test")
t.Setenv("S3_SECRET_KEY", "synthetic-only")
t.Setenv("S3_TLS", "false")
cfg, err := NewObjectStore()
if err != nil || cfg.Secure || cfg.Bucket != "attachments" {
t.Fatalf("invalid result: %v", err)
}
})
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"fmt"
"os"
"strings"
)
// Persistence contains database, cache and session settings.
type Persistence struct {
// CursorKey is the shared base64 signing key supplied through a secret.
CursorKey string
// 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{
CursorKey: os.Getenv("CURSOR_SIGNING_KEY"),
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})
}
@@ -0,0 +1,112 @@
package fiber
import (
"context"
"io"
"net/http"
"time"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// Attachments defines file operations required by the HTTP boundary.
type Attachments interface {
// Upload validates and publishes an original.
Upload(context.Context, string, string, string, string, []byte) (dto.Attachment, error)
// Get authorizes access to attachment metadata.
Get(context.Context, string, string) (dto.Attachment, error)
// Download returns an authorized original stream.
Download(context.Context, string, string, string) (dto.Attachment, io.ReadCloser, error)
}
// WithAttachments binds the file service during composition before server startup.
func (ctrl *Controller) WithAttachments(attachments Attachments) *Controller {
ctrl.attachments = attachments
return ctrl
}
type attachmentResponse struct {
// ID identifies the uploaded file.
ID string `json:"id"`
// ChatID defines the chat authorization scope.
ChatID string `json:"chat_id"`
// OwnerID identifies the original uploader.
OwnerID string `json:"owner_id"`
// Filename is the validated display name.
Filename string `json:"filename"`
// ContentType describes the verified original format.
ContentType string `json:"content_type"`
// SizeBytes is the encoded original length.
SizeBytes int64 `json:"size_bytes"`
// SHA256 is the original lowercase checksum.
SHA256 string `json:"sha256"`
// Status is the durable publication state.
Status string `json:"status"`
// Variants lists generated variants, empty in lab4.
Variants []string `json:"variants"`
// ErrorCode is null for a ready original.
ErrorCode *string `json:"error_code"`
// CreatedAt is the reservation time.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is the publication time.
UpdatedAt time.Time `json:"updated_at"`
}
// attachmentResponseOf deliberately omits private S3 coordinates.
func attachmentResponseOf(a dto.Attachment) attachmentResponse {
return attachmentResponse{
ID: a.ID.String(),
ChatID: a.ChatID.String(),
OwnerID: a.OwnerID.String(),
Filename: a.Filename,
ContentType: a.ContentType,
SizeBytes: a.SizeBytes,
SHA256: a.SHA256,
Status: a.Status,
Variants: []string{},
CreatedAt: a.CreatedAt,
UpdatedAt: a.UpdatedAt,
}
}
// handleUpload passes raw bounded bytes to application validation.
func (ctrl *Controller) handleUpload(ctx *fiber.Ctx) error {
if ctrl.attachments == nil {
return service.ErrUnavailable
}
a, err := ctrl.attachments.Upload(ctx.UserContext(), identity(ctx), ctx.Params("chat_id"), ctx.Query("filename"), ctx.Get("Content-Type"), ctx.Body())
if err != nil {
return err
}
return ctx.Status(http.StatusCreated).JSON(attachmentResponseOf(a))
}
// handleAttachment returns only the public metadata of an accessible file.
func (ctrl *Controller) handleAttachment(ctx *fiber.Ctx) error {
if ctrl.attachments == nil {
return service.ErrUnavailable
}
a, err := ctrl.attachments.Get(ctx.UserContext(), identity(ctx), ctx.Params("id"))
if err != nil {
return err
}
return ctx.JSON(attachmentResponseOf(a))
}
// handleContent streams original bytes without redirecting around authorization.
func (ctrl *Controller) handleContent(ctx *fiber.Ctx) error {
if ctrl.attachments == nil {
return service.ErrUnavailable
}
a, reader, err := ctrl.attachments.Download(ctx.UserContext(), identity(ctx), ctx.Params("id"), ctx.Query("variant"))
if err != nil {
return err
}
ctx.Set("Content-Type", a.ContentType)
ctx.Set("X-Content-Type-Options", "nosniff")
return ctx.SendStream(&responseStream{Reader: reader, cleanup: func() {
}}, int(a.SizeBytes))
}
@@ -0,0 +1,102 @@
package fiber
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
type attachmentFixture struct {
attachment dto.Attachment
body []byte
err error
}
// Upload returns the configured application outcome for an HTTP mapping scenario.
func (f attachmentFixture) Upload(context.Context, string, string, string, string, []byte) (dto.Attachment, error) {
return f.attachment, f.err
}
// Get returns the configured metadata outcome for an HTTP mapping scenario.
func (f attachmentFixture) Get(context.Context, string, string) (dto.Attachment, error) {
return f.attachment, f.err
}
// Download returns a stream that fails if the request context is canceled before transmission.
func (f attachmentFixture) Download(ctx context.Context, _, _, _ string) (dto.Attachment, io.ReadCloser, error) {
return f.attachment, &contextReader{Reader: bytes.NewReader(f.body), ctx: ctx}, f.err
}
type contextReader struct {
*bytes.Reader
ctx context.Context
}
// Read verifies the admission context survives until the response is actually read.
func (r *contextReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
return r.Reader.Read(p)
}
// Close makes the synthetic response stream an owned closer.
func (r *contextReader) Close() error {
return nil
}
// TestAttachmentHTTPMapping exercises early errors, successful metadata and byte-exact streaming.
func TestAttachmentHTTPMapping(t *testing.T) {
cases := []struct {
name string
method string
path string
fixture *attachmentFixture
status int
}{
{"upload unavailable", "POST", "/api/v1/chats/test/attachments", nil, http.StatusServiceUnavailable},
{"metadata unavailable", "GET", "/api/v1/attachments/test", nil, http.StatusServiceUnavailable},
{"download unavailable", "GET", "/api/v1/attachments/test/content", nil, http.StatusServiceUnavailable},
{"upload too large", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{err: service.ErrTooLarge}, http.StatusRequestEntityTooLarge},
{"upload unsupported", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{err: service.ErrMedia}, http.StatusUnsupportedMediaType},
{"metadata missing", "GET", "/api/v1/attachments/test", &attachmentFixture{err: service.ErrNotFound}, http.StatusNotFound},
{"download missing", "GET", "/api/v1/attachments/test/content", &attachmentFixture{err: service.ErrNotFound}, http.StatusNotFound},
{"upload ready", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{attachment: dto.Attachment{ID: uuid.New(), Status: "ready"}}, http.StatusCreated},
{"metadata ready", "GET", "/api/v1/attachments/test", &attachmentFixture{attachment: dto.Attachment{ID: uuid.New(), Status: "ready"}}, http.StatusOK},
{"download stream", "GET", "/api/v1/attachments/test/content", &attachmentFixture{attachment: dto.Attachment{SizeBytes: 4, ContentType: "image/png"}, body: []byte{0, 1, 2, 3}}, http.StatusOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctrl := testController(t, nil)
user := call(t, ctrl, http.MethodPost, "/api/v1/users", "", map[string]any{"username": "test_user", "display_name": "Test", "password": "synthetic-password"}, http.StatusCreated)
if tc.fixture != nil {
ctrl.WithAttachments(*tc.fixture)
}
req := httptest.NewRequest(tc.method, tc.path, bytes.NewReader([]byte("fixture")))
req.Header.Set("Authorization", "Bearer "+user["id"].(string))
req.Header.Set("Content-Type", "image/png")
response, err := ctrl.server.Test(req, 10000)
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(response.Body)
if closeErr := response.Body.Close(); closeErr != nil {
t.Fatal(closeErr)
}
if err != nil || response.StatusCode != tc.status {
t.Fatalf("response status=%d err=%v", response.StatusCode, err)
}
if tc.fixture != nil && tc.fixture.body != nil && !bytes.Equal(body, tc.fixture.body) {
t.Fatalf("stream changed: %v", body)
}
})
}
}
+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/mtusi2026lab4/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/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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,69 @@
package fiber
import (
"context"
"encoding/json"
"net"
"net/http"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/http"
)
// TestBodyLimitInstanceHeader verifies parser-generated 413 responses over a real TCP listener.
func TestBodyLimitInstanceHeader(t *testing.T) {
// Arrange.
ctrl := testController(t, func(cfg *config.Config) {
cfg.HTTP.MaxBodyBytes = 64 << 10
cfg.HTTP.InstanceID = "body-limit-test-instance"
})
ctrl.cfg.Host = "127.0.0.1"
ctrl.cfg.Port = 0
address := make(chan string, 1)
ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error {
address <- net.JoinHostPort(data.Host, data.Port)
return nil
})
if err := ctrl.Start(t.Context()); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := ctrl.Stop(ctx); err != nil {
t.Error(err)
}
})
client := &http.Client{Timeout: 3 * time.Second}
// Act.
response, err := client.Post("http://"+<-address+"/api/v1/users", "application/json", strings.NewReader(strings.Repeat("x", ctrl.cfg.MaxBodyBytes+1)))
if err != nil {
t.Fatal(err)
}
defer func() {
if err := response.Body.Close(); err != nil {
t.Error(err)
}
}()
// Assert.
if response.StatusCode != http.StatusRequestEntityTooLarge {
t.Fatalf("status=%d", response.StatusCode)
}
if instance := response.Header.Get("X-Instance-Id"); instance != ctrl.instanceID {
t.Fatalf("instance=%q, want %q", instance, ctrl.instanceID)
}
var body httpmodel.ErrorResponse
if err := json.NewDecoder(response.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if body.Error.Code != "payload_too_large" || body.Error.RequestID == "" || body.Error.RequestID != response.Header.Get(headerRequestID) {
t.Fatalf("invalid error envelope: %+v", body)
}
}
@@ -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,66 @@
// Package fiber implements the messenger HTTP transport using Fiber.
package fiber
import (
"fmt"
"sync/atomic"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"go.lab260.ru/fielderr"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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 {
attachments Attachments
metrics *httpMetrics
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
instanceID string
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{
metrics: newHTTPMetrics(),
log: log.Named("controller.http.fiber"),
cfg: *cfg,
service: svc,
errorRegistry: registry,
admission: limiter,
auth: auth,
readiness: readiness,
serveDone: make(chan error, 1),
}
ctrl.instanceID = cfg.InstanceID
if ctrl.instanceID == "" {
ctrl.instanceID = uuid.NewString()
}
ctrl.configure()
return ctrl, nil
}
@@ -0,0 +1,321 @@
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/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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.MaxConnections = 256
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))
req.Header.Set("Idempotency-Key", uuid.NewString())
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
}
+34
View File
@@ -0,0 +1,34 @@
package fiber
import (
"mime"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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
}
// decodeMessage accepts the optional attachment list without weakening strict JSON validation.
func decodeMessage(ctx *fiber.Ctx, target any) error {
mediaType, _, err := mime.ParseMediaType(ctx.Get(fiber.HeaderContentType))
if err != nil || mediaType != fiber.MIMEApplicationJSON {
return errMedia
}
if err := strictjson.DecodeOptional(ctx.Body(), target, []string{"text"}, []string{"attachment_ids"}); 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,
}
}
+73
View File
@@ -0,0 +1,73 @@
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/mtusi2026lab4/internal/model/http"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// handleErr normalizes a failure and writes the public error envelope.
func (ctrl *Controller) handleErr(ctx *fiber.Ctx, err error) error {
// Parser failures such as BodyLimit rejection bypass request middleware.
ctx.Set("X-Instance-Id", ctrl.instanceID)
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/mtusi2026lab4/internal/model/http"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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,98 @@
package fiber
import (
"net/http"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/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 := decodeMessage(ctx, &request); err != nil {
return err
}
message, err := ctrl.service.MessagesCreate(ctx.UserContext(), dto.MessagesCreateRequestDTO{
AttachmentIDs: request.AttachmentIDs,
IdempotencyKey: ctx.Get("Idempotency-Key"),
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))
}

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