Compare commits

3 Commits
243 changed files with 17099 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 webp
- 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
+9
View File
@@ -0,0 +1,9 @@
# Асинхронная обработка вложений
API авторизует и проверяет изображение, сохраняет private staging и одной SQL-транзакцией публикует queued + durable job. Ответ содержит снимок queued независимо от скорости worker.
Отдельный worker публикует SQL outbox в Valkey Streams и принимает уведомления consumer group. SQL остаётся источником истины: незавершённые работы повторно уведомляются после ограниченного интервала. AOF брокера не заменяет outbox. Любая повторная доставка проверяет актуальный pipeline_version и lease.
Worker арендует задание на ограниченное время, читает доверенный staging key из SQL, создаёт оригинал/thumbnail/crop/WebP в prefix результата с версией и уникальным fencing token. SQL CAS публикует только результат текущей аренды. Устаревшая попытка не перезаписывает даже байты новой попытки. Неопубликованные объекты удаляются отдельной сверкой после grace period; staging сохраняется для replay/version upgrade.
Попытки ограничены пятью. Временная ошибка фиксирует next-attempt с exponential backoff и jitter; постоянная ошибка переводит в failed. Replay — отдельная операторская команда, которая не повторяет ready без явного повышения версии. Интерфейсы queue/store/processor принадлежат pipeline, инфраструктура связывается через Fx. Worker имеет владельца context и bounded shutdown.
+17
View File
@@ -0,0 +1,17 @@
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 alpine:3.23 AS runtime
RUN apk add --no-cache ca-certificates libwebp-tools
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/mtusi2026lab5
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
+79 -24
View File
@@ -1,37 +1,92 @@
# Отчёт — лабораторная 5
# Лабораторная 5: асинхронная обработка
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
Агапов, БПИ2303. Целевой уровень: 5, трек 2 — versioned pipeline и доказанная идемпотентность. Оценка не выставлена.
## Запуск из чистого clone
## Запуск
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Go 1.26.1, Docker, Helm, kubectl, jq, openssl, Ruby, Python 3.9+ для публичных тестов. Локальному worker нужен `cwebp` (macOS: пакет webp, Ubuntu: пакет webp); контейнер включает libwebp-tools из Alpine 3.23. Image pipeline использует imaging v1.6.2 и WebP quality 80; JPEG quality 85.
## Архитектура и решения
```sh
export GOTOOLCHAIN=go1.26.1
make check chart-check
make test-local
LOCAL_COVERAGE=true scripts/test-local.sh
make init-secrets
make deploy
make test BASE_URL=https://hl.agapov.space
```
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Helm использует один release `lab2` в `highload-applications`, context `dev`. Добавлены worker и отдельный Valkey Streams broker; существующие PostgreSQL, S3, limiter shards, credentials и PVC сохраняются. Migration Jobs применяют 004/005 поверх предыдущих версий. Broker: AOF, appendfsync always, noeviction, persistent volume. При нехватке памяти брокер отклоняет publish; SQL outbox остаётся источником восстановления.
## Доказательства критериев
Образ собирается `make build-push TAG=<revision>`; перед `make deploy` его digest нужно перенести из image-build.json в values. Registry-токен — локальный файл `~/.secrets/twc-registry-token`; секреты не коммитятся. Bootstrap описан в scripts/init-secrets.sh. Остановка worker: масштабировать deployment worker в ноль. PVC при остановке не удаляются; namespace общий, удалять его нельзя.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
## Протокол
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
[Требования](docs/SPEC.md), [устройство](ARCHITECTURE.md), [проверки](student-tests/README.md).
## Эксперименты и отказы
API валидирует MIME/bytes/пиксели, создаёт reservation, сохраняет приватный staging, атомарно фиксирует queued + SQL job. Только после этого возвращается 202 со снимком queued. Состояния queued/processing/failed видны через metadata; content до ready возвращает 409. Queued/processing разрешено прикреплять к сообщению. ACL сохранён.
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Worker отдельно публикует outbox в Streams, получает одну доставку и арендует работу в PostgreSQL. Неподтверждённое уведомление публикуется повторно через 30 секунд; abandoned broker delivery забирается XAUTOCLAIM после двух минут. Один worker обрабатывает одну job, lease — 120 секунд, deadline обработки/I/O — 45 секунд, максимум пять управляемых попыток. Backoff — 2^attempt секунд (до 32) плюс случайные 0–999 ms. Broker redelivery не меняет job_id. SQL attempt увеличивается только при получении новой аренды.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
Оригинал копируется без изменений в конечный prefix. Thumbnail JPEG вписывается в 256×256 без увеличения с округлением вниз; crop — центральные 128×128; optimized — WebP fit1280 без увеличения. EXIF orientation применяется, alpha компонуется на белый, метаданные не переносятся. Готовность публикуется одной SQL-транзакцией после записи всех четырёх объектов.
## Ограничения и следующие шаги
Ключ объекта включает attachment, pipeline_version и lease token. Поэтому истёкшая попытка не перезапишет ни новые метаданные, ни сами байты. CAS проверяет версию и действующую аренду. Ack — после durable completion/retry/failure; потерянный ack приводит к безопасному повтору. Это at-least-once доставка с идемпотентной публикацией, а не exactly-once транспорт.
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
## Failed registry, replay и очистка
`attachment_jobs` хранит status, attempt, error_code, deadline и версию. `attachment_job_audit` фиксирует операторский replay. Временные ошибки повторяются; invalid_image сразу terminal, исчерпание попыток — retry_exhausted.
```sh
# В контейнере с конфигурацией worker:
/server replay <attachment-uuid> 1
# Явная новая версия, старые deliveries больше не могут публиковаться:
/server replay <attachment-uuid> 2
/server reconcile
/server reconcile --apply
```
Та же версия повторяется только из failed; ready не исполняется снова без явного повышения версии. Reconcile по умолчанию dry-run. Unpublished objects очищаются после часа; опубликованные original/variants и все текущие staging защищены ссылками в SQL. Terminal staging хранится семь дней после изменения вложения. Apply сначала атомарно помечает источник expired, запрещая replay, затем удаляет S3 и фиксирует удаление. Незавершённое удаление повторяется. После retention replay отклоняется, требуется новый upload. За одно обращение обрабатываются не более 100 terminal источников; для полного накопленного объёма команду повторяют.
## Доказательства
Дата: 29.10.2026, локальный Apple Silicon, Docker Desktop; native API/worker. Kubernetes resource limits в этих измерениях не применялись.
| Проверка | Доказательство |
| --- | --- |
| 202, polling ready, checksum, настоящий thumbnail, ACL | [smoke](evidence/local/smoke.txt) |
| Остановка обслужившего API | [failover](evidence/local/failover.txt), [действия](evidence/local/actions.txt) |
| Restart PostgreSQL/Valkey/S3/API/worker/broker | [persistence](evidence/local/persistence.txt), [действия](evidence/local/actions.txt) |
| Worker остановлен, upload принят и прикреплён, всё перезапущено, три варианта готовы | [durable](evidence/local/durable.txt) |
| MIME, dimensions, white alpha, JPEG/WebP decode, отсутствие upscale | internal/imageprocessor tests, [coverage log](evidence/current/coverage.txt) |
| At-least-once broker, pending reclaim, malformed envelope | internal/streamqueue tests, тот же log |
| Все Go-файлы ≥90%, race detector | [машинный отчёт](evidence/current/coverage-per-file.json) |
| Lint и структура/Helm | [lint](evidence/current/lint.txt), [static](evidence/current/static.txt) |
Локальный restart сохраняет файловые системы контейнеров. Он не доказывает восстановление с нового Kubernetes-узла или потерянного диска.
## Трек 2: fault matrix
Гипотеза: durable SQL intent, версионирование и fencing обеспечивают отсутствие потери подтверждённой работы и перезаписи более нового результата при повторной доставке.
| Окно/воздействие | Инвариант и наблюдение |
| --- | --- |
| COMMIT intent до publish | Due повторно возвращает тот же job_id; queued-вложение можно прикрепить к сообщению |
| Повтор доставки во время lease | Второй claim не выдаётся |
| Worker потерян после side effect | После expiry новая аренда получает другой token; старый Complete отвергнут |
| Потеря связи до COMMIT результата | Настоящие объекты уже записаны; retry приводит к ready, прежние объекты не опубликованы |
| Потеря подтверждения после COMMIT | Повтор видит ready и не создаёт новый опубликованный эффект |
| Новая версия завершилась раньше старой | Старые Claim/Complete/Fail не изменяют version 2 |
| Пять ошибок/повторные смерти worker | Terminal failed, явный replay сохраняет логический job_id |
| Cleanup конкурирует с replay | Expired source исключает replay до удаления bytes |
Повторяемые сценарии — `jobs_test.go`, `pipeline_integration_test.go`, `streamqueue/queue_test.go`. [Вывод fault matrix](evidence/current/fault-matrix.txt). В fault tests потеря соединения моделируется на границе реальных операций, а не kill процесса в каждой инструкции. Отдельный shell-сценарий действительно останавливает worker и перезапускает стенд. Все данные синтетические. Один проход матрицы проверяет перечисленные инварианты, но не является доказательством для произвольного распределённого расписания.
## Ограничения и источники
Нет HA broker/PostgreSQL/S3. CPU-декодирование ограничено пикселями и числом worker, но Go decode не поддерживает прерывание посреди каждой операции; внешнему процессу WebP передан deadline, Pod имеет memory limit. Потеря диска требует backup, а не retry. В dev применён release lab2 revision 43; публичный HTTPS smoke прошёл после исправления лимита SeaweedFS volumes. [Вывод](evidence/current/dev-smoke-volumes.txt). Первые попытки выявили сохранение старых Helm values (исправлено --reset-values) и занятие всех пяти volumes стандартной коллекцией SeaweedFS (лимит увеличен до 32, по 100 MiB, в пределах PVC 5 GiB). [Upgrade](evidence/current/dev-deploy-volumes.txt). Кратковременные ошибки DNS при rollout сохранены в диагностике; успешный smoke не доказывает отсутствие будущих сетевых отказов. Kubernetes вместо Compose/Swarm требует подтверждения преподавателя.
Официальные источники: [imaging](https://pkg.go.dev/github.com/disintegration/imaging), [cwebp](https://developers.google.com/speed/webp/docs/cwebp), [Valkey XAUTOCLAIM](https://valkey.io/commands/xautoclaim/). При разработке использовалась помощь ИИ; проверки и ограничения перечислены явно.
## Итоговая сверка
Обязательные HTTP/attachment/job контракты сопоставлены с реализацией и текущими Go/реальными process checks. Kubernetes restart hook дополнен остановкой worker и перезапуском broker с сохранением PVC; его shell syntax проверен. Сам этот hook в dev после изменения не запускался: доказательство полного restart относится к изолированному local-action сценарию, а не к нему.
+6
View File
@@ -0,0 +1,6 @@
apiVersion: v2
name: messenger
description: Учебный мессенджер с PostgreSQL и шардированным Valkey
version: 0.1.0
appVersion: lab5
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,59 @@
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: worker}
ports:
- {protocol: TCP, port: 5432}
- 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, worker, 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 }}
+111
View File
@@ -0,0 +1,111 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: worker
spec:
replicas: {{ .Values.worker.replicas }}
selector:
matchLabels: {app: worker}
template:
metadata:
labels: {app: worker}
spec:
imagePullSecrets:
- name: {{ .Values.imagePullSecret }}
terminationGracePeriodSeconds: 60
securityContext:
runAsNonRoot: true
runAsUser: 65532
seccompProfile: {type: RuntimeDefault}
containers:
- name: worker
image: "{{ .Values.image.repository }}@{{ .Values.image.digest }}"
args: [worker]
resources:
requests: {cpu: 250m, memory: 256Mi}
limits: {cpu: '1', memory: 1Gi}
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: {drop: [ALL]}
envFrom:
- configMapRef: {name: messenger-config}
env:
- {name: GOMEMLIMIT, value: 768MiB}
- {name: BROKER_ADDRESS, value: 'broker:6379'}
- {name: S3_ENDPOINT, value: 's3:9000'}
- {name: S3_TLS, value: 'false'}
- name: S3_BUCKET
value: {{ .Values.s3.bucket }}
- name: DATABASE_URL
valueFrom:
secretKeyRef: {name: {{ .Values.databaseSecret }}, key: database-url}
- name: CURSOR_SIGNING_KEY
valueFrom:
secretKeyRef: {name: {{ .Values.databaseSecret }}, key: cursor-key}
- 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}
---
apiVersion: v1
kind: Service
metadata:
name: broker
spec:
selector: {app: broker}
ports:
- {name: streams, port: 6379}
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: broker
spec:
serviceName: broker
replicas: 1
selector:
matchLabels: {app: broker}
template:
metadata:
labels: {app: broker}
spec:
containers:
- name: broker
image: {{ .Values.valkey.image }}
args: [valkey-server, --appendonly, 'yes', --appendfsync, always, --maxmemory, 128mb, --maxmemory-policy, noeviction]
resources:
requests: {cpu: 100m, memory: 160Mi}
limits: {cpu: '1', memory: 256Mi}
ports:
- {containerPort: 6379}
readinessProbe:
exec: {command: [valkey-cli, ping]}
volumeMounts:
- {name: data, mountPath: /data}
volumeClaimTemplates:
- metadata: {name: data}
spec:
accessModes: [ReadWriteOnce]
{{- if .Values.storageClass }}
storageClassName: {{ .Values.storageClass | quote }}
{{- end }}
resources:
requests: {storage: 1Gi}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: private-broker
spec:
podSelector:
matchLabels: {app: broker}
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchLabels: {app: worker}
ports:
- {protocol: TCP, port: 6379}
+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}$"}}}
}
}
+67
View File
@@ -0,0 +1,67 @@
# Existing lab2 release; shared persistent stores and credentials.
image:
repository: asisti.registry.twcstorage.ru/mtusi2026lab5
digest: sha256:8da7c54c754acda38c8c2eca6b0c901515fb58f14bf5af9efed939f71ac81d6f
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
worker:
replicas: 1
+105
View File
@@ -0,0 +1,105 @@
package main
import (
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/controller"
fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/controller/http/fiber"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/password"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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/mtusi2026lab5/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)
}
}
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"context"
"fmt"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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] == "worker" {
fx.New(workerApp()).Run()
return nil
}
if len(args) == 3 && args[0] == "replay" {
return replayJob(args[1], args[2])
}
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/mtusi2026lab5/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/mtusi2026lab5/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/mtusi2026lab5/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/mtusi2026lab5/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config"
fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/controller/http/fiber"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/media"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/objectstore"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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/mtusi2026lab5/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/mtusi2026lab5/internal/config"
fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/controller/http/fiber"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service/authentication"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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/mtusi2026lab5/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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")
}
}
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"context"
"os"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/media"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/objectstore"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/pipeline"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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()
if apply {
if _, err := pipeline.Cleanup(ctx, database, objects); err != nil {
return err
}
}
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/mtusi2026lab5/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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)
}
+84
View File
@@ -0,0 +1,84 @@
package main
import (
"context"
"fmt"
"strconv"
"time"
"github.com/google/uuid"
"go.uber.org/fx"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/imageprocessor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/objectstore"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/pipeline"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/streamqueue"
)
// workerApp composes an independently deployable worker with owned Fx lifecycle.
func workerApp() fx.Option {
return fx.Options(fx.StopTimeout(55*time.Second), fx.Provide(config.New, config.NewPersistence, config.NewObjectStore, config.NewWorker, loggerConfig, newLogger, newDatabase, newObjects, newQueue, imageprocessor.New, newWorker), fx.WithLogger(newFxLogger), fx.Invoke(startWorker))
}
// newQueue closes the queue after the worker has relinquished its processing loop.
func newQueue(lc fx.Lifecycle, cfg *config.Worker) (*streamqueue.Queue, error) {
queue, err := streamqueue.New(cfg.BrokerAddress, cfg.Consumer)
if err != nil {
return nil, err
}
lc.Append(fx.Hook{OnStop: func(context.Context) error {
return queue.Close()
}})
return queue, nil
}
// newWorker binds concrete adapters only at the composition root.
func newWorker(database *postgres.Store, queue *streamqueue.Queue, objects *objectstore.Client, processor *imageprocessor.Processor, log *zap.Logger) (*pipeline.Worker, error) {
return pipeline.New(database, queue, objects, processor, log)
}
// startWorker owns the background context and joins its goroutine during shutdown.
func startWorker(lc fx.Lifecycle, worker *pipeline.Worker) {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
lc.Append(fx.Hook{OnStart: func(context.Context) error {
go func() {
defer close(done)
worker.Run(ctx)
}()
return nil
}, OnStop: func(stop context.Context) error {
cancel()
select {
case <-done:
return nil
case <-stop.Done():
return stop.Err()
}
}})
}
// replayJob explicitly retries a failed version or advances a pipeline version.
func replayJob(rawID, rawVersion string) error {
id, err := uuid.Parse(rawID)
if err != nil {
return fmt.Errorf("invalid attachment ID")
}
version, err := strconv.Atoi(rawVersion)
if err != nil || version < 1 {
return fmt.Errorf("positive pipeline version required")
}
cfg, err := config.NewPersistence()
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()
return database.Replay(context.Background(), id, version)
}
+80
View File
@@ -0,0 +1,80 @@
package main
import (
"os"
"testing"
"time"
"github.com/google/uuid"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config"
)
// TestWorkerLifecycle starts and joins the real worker without exposing an HTTP listener.
func TestWorkerLifecycle(t *testing.T) {
requirePersistence(t)
if os.Getenv("BROKER_ADDRESS") == "" || os.Getenv("S3_ENDPOINT") == "" {
t.Skip("isolated broker and S3 required")
}
app := fx.New(workerApp())
if err := app.Start(t.Context()); err != nil {
t.Fatal(err)
}
time.Sleep(30 * time.Millisecond)
if err := app.Stop(t.Context()); err != nil {
t.Fatal(err)
}
}
// TestQueueProviderRejectsMissingAddress propagates configuration failure before startup.
func TestQueueProviderRejectsMissingAddress(t *testing.T) {
var lc fx.Lifecycle
app := fx.New(fx.NopLogger, fx.Populate(&lc))
if err := app.Err(); err != nil {
t.Fatal(err)
}
if _, err := newQueue(lc, &config.Worker{}); err == nil {
t.Fatal("missing broker accepted")
}
}
// TestReplayCommandRejectsInvalidInput prevents unintended operator transitions.
func TestReplayCommandRejectsInvalidInput(t *testing.T) {
for _, tc := range []struct {
name string
id string
version string
}{{"invalid ID", "invalid", "1"}, {"invalid version", uuid.NewString(), "x"}, {"negative version", uuid.NewString(), "-1"}} {
t.Run(tc.name, func(t *testing.T) {
if err := run([]string{"replay", tc.id, tc.version}); err == nil {
t.Fatal("invalid operator input accepted")
}
})
}
}
// TestReplayCommandConfiguration checks failure before database access.
func TestReplayCommandConfiguration(t *testing.T) {
t.Run("missing", func(t *testing.T) {
t.Setenv("DATABASE_URL", "")
if err := replayJob(uuid.NewString(), "1"); err == nil {
t.Fatal("missing database accepted")
}
})
t.Run("malformed", func(t *testing.T) {
t.Setenv("DATABASE_URL", "://invalid")
t.Setenv("VALKEY_SHARDS", "shard0=localhost:6379")
if err := replayJob(uuid.NewString(), "1"); err == nil {
t.Fatal("malformed database accepted")
}
})
}
// TestReplayUnknownAttachment verifies safe operator failure against the actual schema.
func TestReplayUnknownAttachment(t *testing.T) {
requirePersistence(t)
if err := replayJob(uuid.NewString(), "1"); err == nil {
t.Fatal("unknown attachment replayed")
}
}
+11
View File
@@ -0,0 +1,11 @@
# Сверка контракта lab5
README, COURSE, обязательные contracts и публичные tests сохранены. Проверены унаследованные auth/HTTP/idempotency/attachment ACL и новые состояния queued/processing/ready/failed.
202 возвращается после durable staging и SQL outbox; content до ready409; queued attachment можно прикрепить к message. Реальный сценарий остановки worker и полного restart доводит принятую работу до ready. Исходные bytes/checksum не меняются; thumbnail fit256, EXIF/white alpha/no upscale, crop128 и WebP fit1280 проверены imageprocessor tests и smoke.
Уровень4/трек5.2: outbox, backoff/jitter, finite retry, expired lease, version fencing, failed registry/replay/audit, safe staging retention. Автоматическая fault matrix работает с настоящими SQL/S3; часть точек отказа моделирует ошибку между операциями, а не kill в каждой машинной инструкции. Подробности и реальные process tests отдельно перечислены в REPORT.
Kubernetes restart hook включает API/worker/PG/Valkey/S3/broker, сохраняет PVC и восстанавливает число процессов при ошибке. После его расширения проверен shell syntax; фактическое доказательство restart относится к local-action.sh. Dev HTTPS smoke успешен для этой версии до cumulative обновления lab6.
Формальный открытый вопрос: Kubernetes вместо требуемого Compose/Swarm; принятие замены преподавателем не подтверждено.
+8
View File
@@ -0,0 +1,8 @@
# План lab5
1. L5-01/02: additive migrations 004/005, SQL outbox, durable Valkey Streams — выполнено.
2. L5-03/04: отдельный worker, три варианта, bounded retry/replay/retention — выполнено.
3. L5-05: versioning/fencing и автоматическая fault matrix — выполнено; типы инъекций и ограничения в REPORT.
4. L5-06: HTTP, Helm, публичные smoke/failover/persistence, остановленный worker + полный restart, race, lint, покрытие каждого файла ≥90% — проверено локально.
5. Образ опубликован; dev release lab2 revision 43 применён, HTTPS smoke прошёл. Удалённый CI не проверен.
6. Commit/push main и описание PR — завершающий шаг; оценка зависит от проверки преподавателем.
+12
View File
@@ -0,0 +1,12 @@
# Спецификация lab5
Нормативные источники: README, COURSE, contracts/README.md, attachment-states.md, jobs.schema.json. Цель — уровни 3/4 и трек 5.2.
- L5-01: только после durable staging и SQL outbox возвращается 202 со снимком queued; worker/broker могут быть остановлены. Принятые задания сохраняются после рестарта.
- L5-02: отдельный worker, Valkey Streams с AOF; подтверждение доставки после устойчивого результата или устойчивого retry. Broker содержит только ID/служебные поля.
- L5-03: оригинал неизменен; thumbnail JPEG fit256 без upscale, floor, orientation и white alpha; crop128; optimized WebP fit1280. ready только после публикации всех объектов.
- L5-04: пять попыток, backoff+jitter, lease, ограниченный concurrency, failed registry и replay. Worker I/O/обработка ограничены deadline; staging не удаляется раньше публикации.
- L5-05: pipeline_version, стабильный job_id, fencing lease; дубли/reorder/устаревшие задачи не меняют новый результат. Повторяемая fault matrix на реальных SQL/S3/Streams с сохранением данных.
- L5-06: безопасные статусы и ACL, возможность прикрепить queued/processing; regression/race/per-file coverage, воспроизводимый Helm bootstrap и отчёт.
Ограничения: тот же release lab2 и namespace highload-applications. Kubernetes вместо Compose требует подтверждения преподавателя. Состояние задания и outbox в SQL — источник истины; при потере уведомления оно публикуется снова. Не заявляется exactly-once доставка.
+4
View File
@@ -0,0 +1,4 @@
==> Linting charts/messenger
[INFO] Chart.yaml: icon is recommended
1 chart(s) linted, 0 chart(s) failed
+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.
+100
View File
@@ -0,0 +1,100 @@
{"threshold_per_file":90,"files":[
{"file":"internal/store/postgres/attachments.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"6ef89edb102f3d8c677a5312abb5ecc3730caf96ef1a416ee3dffad0a357b695"},
{"file":"internal/controller/interface.go","statements":0,"covered":0,"percent":null,"sha256":"24b6b06d6fab919cd2130697b44fd0d358265184dca0ca8362e0b4fcc2ae5a68"},
{"file":"internal/valkey/client.go","statements":35,"covered":34,"percent":97.14285714,"sha256":"21801ca5f8ddfa5a2e0b54ec8bea94b74f0bad5d8406b2721c6de4c19cfb01a9"},
{"file":"internal/service/production/members.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"80dad2c7c823946f20aeecb362284d61acdfe9b7777797e513954280aca3a69e"},
{"file":"internal/controller/http/fiber/configure.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd"},
{"file":"internal/controller/http/fiber/error_codes.go","statements":0,"covered":0,"percent":null,"sha256":"3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41"},
{"file":"internal/objectstore/list.go","statements":10,"covered":9,"percent":90.00000000,"sha256":"db32692e7fd00b352cf94a0aecce1d552378f17f43f14bcd4c65d5ad9c46c859"},
{"file":"internal/controller/http/fiber/lifecycle.go","statements":24,"covered":22,"percent":91.66666667,"sha256":"f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08"},
{"file":"internal/store/memory/capacity.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"5f3a9fc819b350be1396aa7871004a56ad725c72a0bfe2c30a29d02478cebd12"},
{"file":"internal/config/persistence.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"28c61d23db4ca2ef7ed952451f465318865076d2393eaa94ff5d7bb339c4c06b"},
{"file":"internal/store/postgres/sessions.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"889a63b51b29012f4ae5499d1c0577fe29f2f2959b05629f8e123715cfc1f75f"},
{"file":"internal/service/production/service.go","statements":10,"covered":10,"percent":100.00000000,"sha256":"115ae85418856016094834d87d18ea5b8e69d0a07ce94dc57693f9cf2e07125e"},
{"file":"internal/media/reconcile.go","statements":38,"covered":38,"percent":100.00000000,"sha256":"0c268c2db1a82be8e4da16bbbd3d1ecc3d4cf86fed03cc290884eb13cb2f1fd9"},
{"file":"internal/controller/http/fiber/routes.go","statements":18,"covered":18,"percent":100.00000000,"sha256":"e248223517102e1eecdeba9a5e2d844c0afc14116a56e9a1d76c6afb755e63d1"},
{"file":"internal/controller/http/fiber/health.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"20c9f1d2d225e8ec7c7f112f6a0484daf91144ff05d597bc4bfa36d33ec422a6"},
{"file":"cmd/server/media.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"77468e1c019d7d48d942e2e0aea2e36aaff2b7ebeb15a79a891bd5ba5e6a45ef"},
{"file":"cmd/server/app.go","statements":9,"covered":9,"percent":100.00000000,"sha256":"3a4839a83d7d540f1aa2d6f12f4c131d1fad91f3b24d671e2eb25ba94f34ac37"},
{"file":"internal/store/memory/store.go","statements":3,"covered":3,"percent":100.00000000,"sha256":"70ed551d8fa8ad1642b649f0d1b297dd1575500adf111543da40a0dab7d632fb"},
{"file":"internal/config/config.go","statements":17,"covered":17,"percent":100.00000000,"sha256":"8cb675a0bef8b1645071e4cb85b79a467620e99b375db5d8d3e16a54b4c5b5fa"},
{"file":"cmd/server/reconcile.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"8be9ea2c0cfe858a0535bfdbb7c3869e7e9671d51f96ec0bd7607a31890e85ac"},
{"file":"internal/service/cursor.go","statements":0,"covered":0,"percent":null,"sha256":"211ccca8211ef97f5a0fac8233eb30f8177b668c9c791e4b7e32ba2b0ad757ff"},
{"file":"internal/store/memory/users.go","statements":22,"covered":21,"percent":95.45454545,"sha256":"b00028003597503642cb724d51742e9b0d31ec895de65617e306d85728d3758f"},
{"file":"internal/service/cache.go","statements":0,"covered":0,"percent":null,"sha256":"80b4ac4c0485587944738db2a9fcef7ce2c93752e1ede3cdbf5d3ae4e68af1b8"},
{"file":"internal/controller/http/fiber/public_errors.go","statements":15,"covered":15,"percent":100.00000000,"sha256":"213db04eda343aa99f0012e397a7682818d373468ea4cc86f667b5ea49c67056"},
{"file":"cmd/server/main.go","statements":3,"covered":3,"percent":100.00000000,"sha256":"c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495"},
{"file":"internal/config/worker.go","statements":4,"covered":4,"percent":100.00000000,"sha256":"eb502257c4badca1e8a2d4eb17701937edcc2c45dd6d697d70abb1624f457e14"},
{"file":"internal/service/production/pages.go","statements":17,"covered":16,"percent":94.11764706,"sha256":"6b1e69ee07b150a9eaa9455a5e2a4713e6d75ff84826f8e412b557d2cde069fe"},
{"file":"internal/pipeline/types.go","statements":0,"covered":0,"percent":null,"sha256":"ecfe10f64a859a5b09390b237bf1413013fb2e9df4c46f0249b90b78585a2651"},
{"file":"internal/model/http/models.go","statements":0,"covered":0,"percent":null,"sha256":"d68827b0bd3e6df4037621b6941298d3923dc348bda5bf314a34861e7c34f04e"},
{"file":"cmd/server/healthcheck.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"cc5ed5ec97333d68f57123b86a1c1d81e902e92f39c4a4e51a3f994dd5977291"},
{"file":"cmd/server/commands.go","statements":27,"covered":27,"percent":100.00000000,"sha256":"3f757a21a5413d9b0a60da170330053ce6205c6dfec15bb0a80686cc45e1e2ea"},
{"file":"internal/store/postgres/retention.go","statements":11,"covered":11,"percent":100.00000000,"sha256":"6ca456767aec350fe81af74deb82a04fcb8689896d11ed547d3855a01f1b57e7"},
{"file":"internal/store/postgres/messages.go","statements":31,"covered":29,"percent":93.54838710,"sha256":"f201438f8910a9ac0a5d59e2ffa249b54856b6c55c89034b4742e233c9407ee1"},
{"file":"internal/store/memory/messages.go","statements":19,"covered":18,"percent":94.73684211,"sha256":"babf91f353e7a921732509502618c6eb15eaf50e0337eabeea3c24961337dfb2"},
{"file":"internal/model/dto/session.go","statements":0,"covered":0,"percent":null,"sha256":"896a694b0c217240343077d4287f4a6e447338c38571abbebcb3d16a519137fb"},
{"file":"internal/store/postgres/chats.go","statements":26,"covered":24,"percent":92.30769231,"sha256":"ba7a0e545181613b72bde03d14ca60cea8483dff383b79ba8f196fd7edc860b0"},
{"file":"internal/config/logger.go","statements":7,"covered":7,"percent":100.00000000,"sha256":"3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988"},
{"file":"internal/service/errors.go","statements":0,"covered":0,"percent":null,"sha256":"cb9c48d4645606804e36899f7d7e92515dbd639d208e78e77132da2e914a5236"},
{"file":"internal/cursor/codec.go","statements":36,"covered":34,"percent":94.44444444,"sha256":"678e197744fb2fc4b51715f51593b98761125bbaddbe4cb1b7032bd6b173ef04"},
{"file":"internal/controller/http/fiber/mapping.go","statements":16,"covered":16,"percent":100.00000000,"sha256":"a4977c8fa919e24f6166e5f63049f17580bd931e82fbeb998d8c46b16085261f"},
{"file":"internal/config/objectstore.go","statements":4,"covered":4,"percent":100.00000000,"sha256":"c6283fe310747e8297850b48c0a119c1d62db4903dd2c779c6296678563df188"},
{"file":"internal/store/postgres/idempotency.go","statements":21,"covered":19,"percent":90.47619048,"sha256":"45775eaff303da4e1aee28c0ab572347f596058084a9fecbc208fef560401686"},
{"file":"internal/service/production/chats.go","statements":22,"covered":22,"percent":100.00000000,"sha256":"7cff211475ee6674f046bdd266be77f570bc2a6bf8bac7500f87ce0a34732e55"},
{"file":"internal/controller/http/fiber/decode.go","statements":12,"covered":11,"percent":91.66666667,"sha256":"268b06298f54aedeac396c8edd4803db6bce99beb88a1fe9ae70c5745d5d5930"},
{"file":"internal/service/authentication/service.go","statements":48,"covered":47,"percent":97.91666667,"sha256":"36352c672ceae93d31c45f8d3e1cc87e3258d2a29f68b133e9a320670d3fa3fe"},
{"file":"internal/objectstore/client.go","statements":39,"covered":36,"percent":92.30769231,"sha256":"11e3e0612b675587f8c5a3ae1a6d677681c6a02db9c70ef299f2c7c56538a7d7"},
{"file":"internal/controller/http/fiber/auth.go","statements":29,"covered":29,"percent":100.00000000,"sha256":"e1be1678e02a0ea08c1075ca2b6802f6c66a4ebe8a9212ba26ce9a73f6fe0b8c"},
{"file":"cmd/server/worker.go","statements":33,"covered":32,"percent":96.96969697,"sha256":"f54ef2eeac6befcc420b8f901bd0aa642f03e9be7262c78a19b561dfe4a13aae"},
{"file":"internal/store/memory/ordering.go","statements":6,"covered":6,"percent":100.00000000,"sha256":"1fb740f80f21ca1fb80563d4b8c090eddf8f0641cbbe36b33363e4d5b6d941c7"},
{"file":"internal/service/production/access.go","statements":27,"covered":27,"percent":100.00000000,"sha256":"cea224f805326af5bc4c592e44ad196eae786c3da77f5fce7b5cc1585a6a34d0"},
{"file":"internal/service/interface.go","statements":0,"covered":0,"percent":null,"sha256":"5b6980fcdeee31406a055fa2168c8390bfb572b87ba8c4638f945242a94b3e25"},
{"file":"internal/model/dto/attachment.go","statements":0,"covered":0,"percent":null,"sha256":"801a6290037459a1f9d28669b4f3cdce5191317da8a48189027b7a507139fdc7"},
{"file":"internal/admission/limiter.go","statements":16,"covered":16,"percent":100.00000000,"sha256":"a373c9539167a4b7c35d45334d35ffd4e9d124c1740c88c12094fededd9643b4"},
{"file":"internal/controller/http/fiber/headers.go","statements":0,"covered":0,"percent":null,"sha256":"d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd"},
{"file":"internal/admission/distributed.go","statements":0,"covered":0,"percent":null,"sha256":"41ef40897886c0878cbfe52f6716bdcb8433fb7eaddcfff298e1d54c55db423d"},
{"file":"internal/valkey/admission.go","statements":42,"covered":42,"percent":100.00000000,"sha256":"2ff6ea983401d03d9306ccf6db2cdbc8133584f8c8076d653d3e42c5387205ae"},
{"file":"internal/controller/http/fiber/errors.go","statements":29,"covered":29,"percent":100.00000000,"sha256":"9a12f72cf7755c2f9f5dd3b789da9289ea8fe3d0f86768696511636b3b430997"},
{"file":"internal/streamqueue/queue.go","statements":33,"covered":30,"percent":90.90909091,"sha256":"2754b5026e327a9dd81574fee91c13206cd16bc6ec70be0e6348b9cb00fe7b54"},
{"file":"internal/store/interface.go","statements":0,"covered":0,"percent":null,"sha256":"ee284df14fbbc6c13dbdb746145ea4274ce6fe7453bce0d6a74424d4934416ed"},
{"file":"internal/controller/http/fiber/controller.go","statements":10,"covered":10,"percent":100.00000000,"sha256":"9eecf0eb9cb7d00f9555e4ecdca907f819dad5565bf6eb81fdf14cb85626b85e"},
{"file":"internal/controller/fx.go","statements":1,"covered":1,"percent":100.00000000,"sha256":"af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a"},
{"file":"internal/controller/http/fiber/metrics.go","statements":17,"covered":17,"percent":100.00000000,"sha256":"54db82201697bdfcc65712afe61b650f8f0885fc65222dc4cc6d1c3bb07d82dd"},
{"file":"internal/store/postgres/reconcile.go","statements":32,"covered":31,"percent":96.87500000,"sha256":"0d2f5e4b8d98869c20d4b7daffe4ba005b8170deeba9d9af2702a7271d8b5b30"},
{"file":"internal/media/service.go","statements":55,"covered":54,"percent":98.18181818,"sha256":"ee47dd3b163cc867c298b106cdcd5fcc22f65c714d21eac3ee7b87cc7613fc16"},
{"file":"cmd/server/s3_bootstrap.go","statements":9,"covered":9,"percent":100.00000000,"sha256":"dded0bcff571a0e067d3d8b6b41749eaa118ff71f3a2b5ee36e222ad4c3a7eae"},
{"file":"internal/store/postgres/store.go","statements":57,"covered":53,"percent":92.98245614,"sha256":"de4efc201bd7675fd7e59f84f63db36595eba57994a8bcafba99bf6865170583"},
{"file":"internal/service/production/errors.go","statements":5,"covered":5,"percent":100.00000000,"sha256":"ad61a1d9a8c24529bf740830145cc2321356b4f28755feb76482a54e5e92d1c4"},
{"file":"internal/pipeline/cleanup.go","statements":11,"covered":11,"percent":100.00000000,"sha256":"eb4a71e1d2cbc93d539770b425305b4826b98dd7770741c6677a50c0ec43b4f8"},
{"file":"internal/controller/http/fiber/stream.go","statements":14,"covered":14,"percent":100.00000000,"sha256":"6bc72fdc23332e08e4dee8a5ed3f9110952208af86b529d5d4847ebcf00dd4c3"},
{"file":"internal/controller/http/fiber/middleware.go","statements":41,"covered":40,"percent":97.56097561,"sha256":"964475bec144153d75808e424a36e369de184178aa74ec203ab39fa3ef44df65"},
{"file":"cmd/server/logger.go","statements":10,"covered":9,"percent":90.00000000,"sha256":"d9bef80b4cad8a0d3633ed31128167ba03d93c9d4f46a99019c5875b5340bb64"},
{"file":"internal/store/postgres/jobs.go","statements":114,"covered":108,"percent":94.73684211,"sha256":"91d59bbd30fa4630228c30132956eaf7c2e0ac910f612ee78448ee1bf9f5fcb0"},
{"file":"internal/config/environment.go","statements":14,"covered":14,"percent":100.00000000,"sha256":"027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3"},
{"file":"internal/valkey/cache.go","statements":17,"covered":16,"percent":94.11764706,"sha256":"109c9c0762ef70860c46e3296051ee8833b6d9fd400ec1172bd1685945e39a68"},
{"file":"internal/service/production/creation.go","statements":24,"covered":23,"percent":95.83333333,"sha256":"a8283a9e57476f58d0641b0ba9c53e97a5cb8f3f0999aa4c9054846368272bcc"},
{"file":"internal/config/controller.go","statements":23,"covered":22,"percent":95.65217391,"sha256":"1c853c0f771e2c75958db8158797f2287e06c8d9efe8856365b7b9c71b1747b0"},
{"file":"internal/service/auth.go","statements":0,"covered":0,"percent":null,"sha256":"3356ae59675b6fec351c9f8e330e7b57f0421b4a3c56826b83579901d3d952dc"},
{"file":"internal/media/validation.go","statements":17,"covered":17,"percent":100.00000000,"sha256":"079795a111ff64f80d2219aa4483cd77030b715d581aa9becff1d48b9bcda299"},
{"file":"internal/controller/http/fiber/handlers.go","statements":37,"covered":36,"percent":97.29729730,"sha256":"698b30c81d0aff9c9e572f28dd923c12509f8195b10ca90b231489417b04cad0"},
{"file":"internal/service/production/validation.go","statements":13,"covered":13,"percent":100.00000000,"sha256":"ef26856b09c27cb28f4ac7da574381f35238ecb63ac343e42328d3a6857bf479"},
{"file":"internal/pipeline/worker.go","statements":72,"covered":70,"percent":97.22222222,"sha256":"e03e49c270fd91ad544739bd99229f7f855d31b6b1e20179cb247b1bf52116a9"},
{"file":"internal/hashring/ring.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"e205901cec2e66011ec764b70879b0eb0d28a78c4dea8913a9fb30c2d778fa8c"},
{"file":"internal/service/production/messages.go","statements":18,"covered":18,"percent":100.00000000,"sha256":"b015718afbba0fe5ff07026d24671d7d64f2371d9bb9aab71d0b32c148485c68"},
{"file":"internal/password/password.go","statements":18,"covered":17,"percent":94.44444444,"sha256":"fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76"},
{"file":"internal/controller/http/fiber/error_registry.go","statements":2,"covered":2,"percent":100.00000000,"sha256":"9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a"},
{"file":"internal/strictjson/decode.go","statements":47,"covered":47,"percent":100.00000000,"sha256":"d99595e1f74406c5aa617c0ec062afb7f12f116bd86776e87cc9c9a436ff7eea"},
{"file":"internal/store/postgres/users.go","statements":21,"covered":20,"percent":95.23809524,"sha256":"fa7f5ae93796d19ab652c5f6f9c6fc691ac4963b33d9dbb114c766912a8fd7f2"},
{"file":"internal/service/production/users.go","statements":19,"covered":19,"percent":100.00000000,"sha256":"ce7ef3afbebd5be41e5c007ac4c791974cbb7a90cae44b6580d3b979f572eb76"},
{"file":"internal/service/production/pagination.go","statements":21,"covered":21,"percent":100.00000000,"sha256":"9c8caa8d16212873a45fe41ccb1099909719a48037b9bfdfa887920b03b905b1"},
{"file":"internal/media/orphans.go","statements":23,"covered":23,"percent":100.00000000,"sha256":"327ee894c8c9afa5bcf8236ed4c91befd66699c0ca33178e9690705764faf002"},
{"file":"internal/store/memory/chats.go","statements":31,"covered":31,"percent":100.00000000,"sha256":"0301a131a41f109e7ec14b9124c60919985039432e1760d276c3b122d0b1ab7b"},
{"file":"internal/media/run_reconcile.go","statements":21,"covered":21,"percent":100.00000000,"sha256":"3255403afcb9486d33c5bb45b5afa9c3c9b85596ce97f86ac2f224011cd8a860"},
{"file":"internal/controller/http/fiber/dependencies.go","statements":0,"covered":0,"percent":null,"sha256":"6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d"},
{"file":"cmd/server/persistence.go","statements":22,"covered":20,"percent":90.90909091,"sha256":"f6795d8dfd3f4de8a14f75b1c1975599bd17841f315b57c33927d6409347e532"},
{"file":"internal/model/dto/models.go","statements":0,"covered":0,"percent":null,"sha256":"5e2536b8eba6bb92b751a7b817b6338755008857e3b53920d8da6fb67adeebdb"},
{"file":"internal/imageprocessor/processor.go","statements":43,"covered":39,"percent":90.69767442,"sha256":"c49dfbfa30970b5dcfd007412f08bea9a8dde34123c383de4e162cebe549f479"},
{"file":"internal/controller/http/fiber/attachments.go","statements":28,"covered":28,"percent":100.00000000,"sha256":"9c6bd1e261696676d4a2595f5fd9b42e5767f7d88e8e182d23d54a4a1e5a240e"},
{"file":"internal/config/memory.go","statements":9,"covered":9,"percent":100.00000000,"sha256":"86cdf9e90b576f4484946bfd9605333fc52077f38d3a39c5d71ddca4cdeecda0"}
],"passed":true}
+124
View File
@@ -0,0 +1,124 @@
warning: GOCOVERDIR not set, no coverage data emitted
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/cmd/server 3.879s coverage: 30.4% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/admission 1.555s coverage: 0.9% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config 1.557s coverage: 4.7% of statements in ./...
gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/controller coverage: 0.0% of statements
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/controller/http/fiber 2.025s coverage: 35.5% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/cursor 1.556s coverage: 1.9% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/hashring 2.336s coverage: 1.1% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/imageprocessor 3.855s coverage: 2.1% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/media 1.804s coverage: 8.0% of statements in ./...
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/model/dto [no test files]
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/model/http [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/objectstore 2.013s coverage: 2.6% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/password 2.629s coverage: 0.9% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/pipeline 1.630s coverage: 4.4% of statements in ./...
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service/authentication 1.847s coverage: 3.0% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service/production 1.841s coverage: 11.8% of statements in ./...
? gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store [no test files]
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store/memory 1.839s coverage: 4.9% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store/postgres 6.613s coverage: 25.3% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/streamqueue 2.694s coverage: 1.6% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/strictjson 1.651s coverage: 2.6% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/valkey 1.721s coverage: 6.1% of statements in ./...
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/student-tests 1.710s coverage: 0.0% of statements in ./...
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
95.24% internal/store/postgres/attachments.go
N/A internal/controller/interface.go
97.14% internal/valkey/client.go
100.00% internal/service/production/members.go
100.00% internal/controller/http/fiber/configure.go
N/A internal/controller/http/fiber/error_codes.go
90.00% internal/objectstore/list.go
91.67% internal/controller/http/fiber/lifecycle.go
100.00% internal/store/memory/capacity.go
100.00% internal/config/persistence.go
100.00% internal/store/postgres/sessions.go
100.00% internal/service/production/service.go
100.00% internal/media/reconcile.go
100.00% internal/controller/http/fiber/routes.go
100.00% internal/controller/http/fiber/health.go
100.00% cmd/server/media.go
100.00% cmd/server/app.go
100.00% internal/store/memory/store.go
100.00% internal/config/config.go
94.74% cmd/server/reconcile.go
N/A internal/service/cursor.go
95.45% internal/store/memory/users.go
N/A internal/service/cache.go
100.00% internal/controller/http/fiber/public_errors.go
100.00% cmd/server/main.go
100.00% internal/config/worker.go
94.12% internal/service/production/pages.go
N/A internal/pipeline/types.go
N/A internal/model/http/models.go
94.74% cmd/server/healthcheck.go
100.00% cmd/server/commands.go
100.00% internal/store/postgres/retention.go
93.55% internal/store/postgres/messages.go
94.74% internal/store/memory/messages.go
N/A internal/model/dto/session.go
92.31% internal/store/postgres/chats.go
100.00% internal/config/logger.go
N/A internal/service/errors.go
94.44% internal/cursor/codec.go
100.00% internal/controller/http/fiber/mapping.go
100.00% internal/config/objectstore.go
90.48% internal/store/postgres/idempotency.go
100.00% internal/service/production/chats.go
91.67% internal/controller/http/fiber/decode.go
97.92% internal/service/authentication/service.go
92.31% internal/objectstore/client.go
100.00% internal/controller/http/fiber/auth.go
96.97% cmd/server/worker.go
100.00% internal/store/memory/ordering.go
100.00% internal/service/production/access.go
N/A internal/service/interface.go
N/A internal/model/dto/attachment.go
100.00% internal/admission/limiter.go
N/A internal/controller/http/fiber/headers.go
N/A internal/admission/distributed.go
100.00% internal/valkey/admission.go
100.00% internal/controller/http/fiber/errors.go
90.91% internal/streamqueue/queue.go
N/A internal/store/interface.go
100.00% internal/controller/http/fiber/controller.go
100.00% internal/controller/fx.go
100.00% internal/controller/http/fiber/metrics.go
96.88% internal/store/postgres/reconcile.go
98.18% internal/media/service.go
100.00% cmd/server/s3_bootstrap.go
92.98% internal/store/postgres/store.go
100.00% internal/service/production/errors.go
100.00% internal/pipeline/cleanup.go
100.00% internal/controller/http/fiber/stream.go
97.56% internal/controller/http/fiber/middleware.go
90.00% cmd/server/logger.go
94.74% internal/store/postgres/jobs.go
100.00% internal/config/environment.go
94.12% internal/valkey/cache.go
95.83% internal/service/production/creation.go
95.65% internal/config/controller.go
N/A internal/service/auth.go
100.00% internal/media/validation.go
97.30% internal/controller/http/fiber/handlers.go
100.00% internal/service/production/validation.go
97.22% internal/pipeline/worker.go
95.24% internal/hashring/ring.go
100.00% internal/service/production/messages.go
94.44% internal/password/password.go
100.00% internal/controller/http/fiber/error_registry.go
100.00% internal/strictjson/decode.go
95.24% internal/store/postgres/users.go
100.00% internal/service/production/users.go
100.00% internal/service/production/pagination.go
100.00% internal/media/orphans.go
100.00% internal/store/memory/chats.go
100.00% internal/media/run_reconcile.go
N/A internal/controller/http/fiber/dependencies.go
90.91% cmd/server/persistence.go
N/A internal/model/dto/models.go
90.70% internal/imageprocessor/processor.go
100.00% internal/controller/http/fiber/attachments.go
100.00% internal/config/memory.go
+15
View File
@@ -0,0 +1,15 @@
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
helm upgrade --install lab2 --reset-values charts/messenger --kube-context dev --namespace highload-applications --wait --wait-for-jobs --timeout 8m
Release "lab2" has been upgraded. Happy Helming!
NAME: lab2
LAST DEPLOYED: Thu Oct 29 16:59:12 2026
NAMESPACE: highload-applications
STATUS: deployed
REVISION: 42
DESCRIPTION: Upgrade complete
TEST SUITE: None
+15
View File
@@ -0,0 +1,15 @@
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
helm upgrade --install lab2 --reset-values charts/messenger --kube-context dev --namespace highload-applications --wait --wait-for-jobs --timeout 8m
Release "lab2" has been upgraded. Happy Helming!
NAME: lab2
LAST DEPLOYED: Thu Oct 29 17:15:29 2026
NAMESPACE: highload-applications
STATUS: deployed
REVISION: 43
DESCRIPTION: Upgrade complete
TEST SUITE: None
+11
View File
@@ -0,0 +1,11 @@
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
helm upgrade --install lab2 charts/messenger --kube-context dev --namespace highload-applications --wait --wait-for-jobs --timeout 8m
Release lab2 has been cancelled.
level=WARN msg="upgrade failed" name=lab2 error="context canceled"
Error: UPGRADE FAILED: context canceled
make: *** [deploy] Error 1
+4
View File
@@ -0,0 +1,4 @@
KUBE_CONTEXT=dev NAMESPACE=highload-applications scripts/init-secrets.sh
namespace/highload-applications unchanged
secret/registry-pull unchanged
secret/messenger-s3 created
+3
View File
@@ -0,0 +1,3 @@
python3 tests/smoke.py --base-url "https://hl.agapov.space"
FAIL: POST /api/v1/chats/668e71bb-cc33-44b8-950c-a5c758118172/attachments: expected [202], received 503
make: *** [test] Error 1
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "https://hl.agapov.space"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+3
View File
@@ -0,0 +1,3 @@
python3 tests/smoke.py --base-url "https://hl.agapov.space"
FAIL: POST /api/v1/chats/43ce1ae5-f9ae-42f1-9120-caa961a3f102/attachments: expected [202], received 503
make: *** [test] Error 1
+5
View File
@@ -0,0 +1,5 @@
go version go1.26.1 darwin/arm64
1.6.0
libsharpyuv: 0.4.2
Darwin arm64
2026-10-29T13:54:37Z
+28
View File
@@ -0,0 +1,28 @@
=== RUN TestOutboxSurvivesMissingPublication
--- PASS: TestOutboxSurvivesMissingPublication (0.11s)
=== RUN TestPipelineDuplicateAfterCommit
--- PASS: TestPipelineDuplicateAfterCommit (0.11s)
=== RUN TestExpiredLeaseFencesLateSideEffect
--- PASS: TestExpiredLeaseFencesLateSideEffect (0.12s)
=== RUN TestPipelineVersionReordering
--- PASS: TestPipelineVersionReordering (0.10s)
=== RUN TestPipelineRetryAndReplay
--- PASS: TestPipelineRetryAndReplay (0.12s)
=== RUN TestPipelinePermanentFailure
--- PASS: TestPipelinePermanentFailure (0.08s)
=== RUN TestPipelineCanceledDatabase
--- PASS: TestPipelineCanceledDatabase (0.08s)
=== RUN TestRepeatedCrashesExhaustLeaseBudget
--- PASS: TestRepeatedCrashesExhaustLeaseBudget (0.09s)
=== RUN TestRealPipelineFaultWindows
=== RUN TestRealPipelineFaultWindows/after_S3_before_commit
pipeline_integration_test.go:145: fault=after_S3_before_commit accepted=1 ready=1 variants=3 duplicate_effects=0
=== RUN TestRealPipelineFaultWindows/after_commit_before_ack
pipeline_integration_test.go:145: fault=after_commit_before_ack accepted=1 ready=1 variants=3 duplicate_effects=0
--- PASS: TestRealPipelineFaultWindows (0.75s)
--- PASS: TestRealPipelineFaultWindows/after_S3_before_commit (0.44s)
--- PASS: TestRealPipelineFaultWindows/after_commit_before_ack (0.31s)
=== RUN TestRetentionFencesReplay
--- PASS: TestRetentionFencesReplay (0.13s)
PASS
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store/postgres 3.825s
+106
View File
@@ -0,0 +1,106 @@
#0 building with "asisti-builder" instance using docker-container driver
#1 [internal] load build definition from Dockerfile
#1 transferring dockerfile: 640B done
#1 DONE 0.0s
#2 [internal] load metadata for docker.io/library/golang:1.26.1-alpine3.23
#2 DONE 3.8s
#3 [internal] load metadata for docker.io/library/alpine:3.23
#3 DONE 7.1s
#4 [internal] load .dockerignore
#4 transferring context: 145B done
#4 DONE 0.0s
#5 [build 1/7] FROM docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039
#5 resolve docker.io/library/golang:1.26.1-alpine3.23@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 done
#5 DONE 0.0s
#6 [internal] load build context
#6 transferring context: 486.31kB 0.0s done
#6 DONE 0.0s
#7 [build 2/7] WORKDIR /src
#7 CACHED
#8 [build 3/7] COPY go.mod go.sum ./
#8 DONE 0.0s
#9 [runtime 1/3] FROM docker.io/library/alpine:3.23@sha256:ff7f0c727dd796aa36787bfcd9a64bf35a6ce72a73451b3359fde849b6703d63
#9 resolve docker.io/library/alpine:3.23@sha256:ff7f0c727dd796aa36787bfcd9a64bf35a6ce72a73451b3359fde849b6703d63 done
#9 sha256:5e9b4a97f6395abf54a5c584be133078deb2295e280dd0b9e77638874d07b637 0B / 3.85MB 0.2s
#9 sha256:5e9b4a97f6395abf54a5c584be133078deb2295e280dd0b9e77638874d07b637 1.05MB / 3.85MB 2.6s
#9 sha256:5e9b4a97f6395abf54a5c584be133078deb2295e280dd0b9e77638874d07b637 2.10MB / 3.85MB 4.5s
#9 sha256:5e9b4a97f6395abf54a5c584be133078deb2295e280dd0b9e77638874d07b637 3.15MB / 3.85MB 6.2s
#9 sha256:5e9b4a97f6395abf54a5c584be133078deb2295e280dd0b9e77638874d07b637 3.85MB / 3.85MB 7.8s done
#9 extracting sha256:5e9b4a97f6395abf54a5c584be133078deb2295e280dd0b9e77638874d07b637 0.1s done
#9 DONE 7.9s
#10 [runtime 2/3] RUN apk add --no-cache ca-certificates libwebp-tools
#10 ...
#11 [build 4/7] RUN go mod download
#11 ...
#10 [runtime 2/3] RUN apk add --no-cache ca-certificates libwebp-tools
#10 5.659 (1/9) Installing ca-certificates (20261020-r0)
#10 5.997 (2/9) Installing giflib (5.2.2-r2)
#10 6.221 (3/9) Installing libjpeg-turbo (3.1.2-r0)
#10 6.829 (4/9) Installing libpng (1.6.59-r0)
#10 7.518 (5/9) Installing libsharpyuv (1.6.0-r0)
#10 7.927 (6/9) Installing libwebp (1.6.0-r0)
#10 8.545 (7/9) Installing libwebpdemux (1.6.0-r0)
#10 8.757 (8/9) Installing libwebpmux (1.6.0-r0)
#10 8.917 (9/9) Installing libwebp-tools (1.6.0-r0)
#10 9.215 Executing busybox-1.37.0-r30.trigger
#10 9.263 Executing ca-certificates-20261020-r0.trigger
#10 9.338 OK: 9.9 MiB in 25 packages
#10 DONE 9.4s
#11 [build 4/7] RUN go mod download
#11 DONE 199.0s
#12 [build 5/7] COPY cmd/ ./cmd/
#12 DONE 0.0s
#13 [build 6/7] COPY internal/ ./internal/
#13 DONE 0.0s
#14 [build 7/7] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
#14 DONE 63.8s
#15 [runtime 3/3] COPY --from=build /out/server /server
#15 DONE 0.1s
#16 exporting to image
#16 exporting layers
#16 exporting layers 0.6s done
#16 exporting manifest sha256:17c31e52207148864803f270cf85dd9410bb9681dbde49ff99a7de54ec073c56
#16 exporting manifest sha256:17c31e52207148864803f270cf85dd9410bb9681dbde49ff99a7de54ec073c56 done
#16 exporting config sha256:c2247f186e3c84f7a80a0df4c5f27313fcb35b46d4c86bd13b9e12b84e381c03 done
#16 exporting attestation manifest sha256:bbc2a5271568a2355912daa2347e67b3a2ec5f58685869d932eda91c5565e538 done
#16 exporting manifest list sha256:8da7c54c754acda38c8c2eca6b0c901515fb58f14bf5af9efed939f71ac81d6f done
#16 pushing layers
#16 ...
#17 [auth] mtusi2026lab5:pull,push token for asisti.registry.twcstorage.ru
#17 DONE 0.0s
#16 exporting to image
#16 pushing layers 76.4s done
#16 pushing manifest for asisti.registry.twcstorage.ru/mtusi2026lab5:solution-20261029@sha256:8da7c54c754acda38c8c2eca6b0c901515fb58f14bf5af9efed939f71ac81d6f
#16 ...
#18 [auth] mtusi2026lab5:pull,push token for asisti.registry.twcstorage.ru
#18 DONE 0.0s
#16 exporting to image
#16 pushing manifest for asisti.registry.twcstorage.ru/mtusi2026lab5:solution-20261029@sha256:8da7c54c754acda38c8c2eca6b0c901515fb58f14bf5af9efed939f71ac81d6f 3.4s done
#16 DONE 80.5s
#19 resolving provenance for metadata file
#19 DONE 0.2s
View build details: docker-desktop://dashboard/build/asisti-builder/asisti-builder0/6txtx75s74qee1ql7why62gn1
+20
View File
@@ -0,0 +1,20 @@
{
"buildx.build.provenance": {
"buildType": "",
"invocation": {
"configSource": {},
"parameters": {},
"environment": {
"platform": ""
}
}
},
"buildx.build.ref": "asisti-builder/asisti-builder0/6txtx75s74qee1ql7why62gn1",
"containerimage.descriptor": {
"mediaType": "application/vnd.oci.image.index.v1+json",
"digest": "sha256:8da7c54c754acda38c8c2eca6b0c901515fb58f14bf5af9efed939f71ac81d6f",
"size": 855
},
"containerimage.digest": "sha256:8da7c54c754acda38c8c2eca6b0c901515fb58f14bf5af9efed939f71ac81d6f",
"image.name": "asisti.registry.twcstorage.ru/mtusi2026lab5:solution-20261029"
}
+1
View File
@@ -0,0 +1 @@
0 issues.
+3
View File
@@ -0,0 +1,3 @@
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/pipeline 1.497s
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/streamqueue (cached)
ok gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store/postgres (cached)
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://127.0.0.1:18085"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+203
View File
@@ -0,0 +1,203 @@
2f779685d25242bca1fc07a36689b76922c4238922ec88a0358f9ce9ab3e4287 cmd/server/app_test.go
f6795d8dfd3f4de8a14f75b1c1975599bd17841f315b57c33927d6409347e532 cmd/server/persistence.go
77468e1c019d7d48d942e2e0aea2e36aaff2b7ebeb15a79a891bd5ba5e6a45ef cmd/server/media.go
f54ef2eeac6befcc420b8f901bd0aa642f03e9be7262c78a19b561dfe4a13aae cmd/server/worker.go
cc5ed5ec97333d68f57123b86a1c1d81e902e92f39c4a4e51a3f994dd5977291 cmd/server/healthcheck.go
66826896330a45b720e775b4d810d7c8b320513193a3ba377dfcf5a1fd1b0edb cmd/server/persistence_test.go
d9bef80b4cad8a0d3633ed31128167ba03d93c9d4f46a99019c5875b5340bb64 cmd/server/logger.go
dded0bcff571a0e067d3d8b6b41749eaa118ff71f3a2b5ee36e222ad4c3a7eae cmd/server/s3_bootstrap.go
3a4839a83d7d540f1aa2d6f12f4c131d1fad91f3b24d671e2eb25ba94f34ac37 cmd/server/app.go
fcf402cca71463c0e741b561eb25ee64c8666c047efd7eac966b2aea1fc10d57 cmd/server/worker_test.go
03a68839c96df49b75e3b3d3c64138b6fcc2de39df7bd86ea66774d8d0c2f9bd cmd/server/healthcheck_test.go
8be9ea2c0cfe858a0535bfdbb7c3869e7e9671d51f96ec0bd7607a31890e85ac cmd/server/reconcile.go
3f757a21a5413d9b0a60da170330053ce6205c6dfec15bb0a80686cc45e1e2ea cmd/server/commands.go
94e211398c98dde1db9b5965b54437872cfe81a748d37be97eb2e7647b265d53 cmd/server/media_test.go
c22d8cdf4ce31fde29945e967d3f025e280a7dc4d2022329d51be972d2a0f495 cmd/server/main.go
e03e49c270fd91ad544739bd99229f7f855d31b6b1e20179cb247b1bf52116a9 internal/pipeline/worker.go
eb4a71e1d2cbc93d539770b425305b4826b98dd7770741c6677a50c0ec43b4f8 internal/pipeline/cleanup.go
ecfe10f64a859a5b09390b237bf1413013fb2e9df4c46f0249b90b78585a2651 internal/pipeline/types.go
f958c842d94501a5e55331fae4968fd2acf10c8726ac7612d7cfdf48973deeb0 internal/pipeline/worker_test.go
e3e65b686b8ed366b548e0515535f1a3bde1ceadd70fcff22917bb3dd06cb6c5 internal/pipeline/cleanup_test.go
1ad8dcb7d055fcb8da56d10e1089b47fe1b9cbf848381ded1a4048f8fd41278a internal/password/password_test.go
fe2df6990331573bbf0202ebc81c58263a7c16a29b713eefa0f0e852e4ee4a76 internal/password/password.go
2754b5026e327a9dd81574fee91c13206cd16bc6ec70be0e6348b9cb00fe7b54 internal/streamqueue/queue.go
7c1218519c7afa3ebc90242a85928bf9e033bc7c3a6267b44573eee48d4d8f83 internal/streamqueue/queue_test.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
eb502257c4badca1e8a2d4eb17701937edcc2c45dd6d697d70abb1624f457e14 internal/config/worker.go
7377c7fc286e04292b7c82e4e286cadf409ce833079f794a501456024e73434a internal/config/persistence_test.go
3a69e20a00fa2ed816f344a990e9e0ef0077e1607d4207858b4b00e4ff5d1988 internal/config/logger.go
c6283fe310747e8297850b48c0a119c1d62db4903dd2c779c6296678563df188 internal/config/objectstore.go
027761b059b76898a84318ec1a8b43158d8bafd6e0b15b52efbe902b4d8c5ea3 internal/config/environment.go
6c68b5aa8cd0bce1f56b968555dff10f53e452f9d977bd8f21e29155b2cf8442 internal/config/worker_test.go
4e57110e53843506d1dd7336feaa603538b425a6127988590fdfc9fe3e878323 internal/config/objectstore_test.go
0181673dcc4db2557783941aa8c5b3f61bc0ca6b5196d87e69df000346c40391 internal/config/config_test.go
109c9c0762ef70860c46e3296051ee8833b6d9fd400ec1172bd1685945e39a68 internal/valkey/cache.go
21801ca5f8ddfa5a2e0b54ec8bea94b74f0bad5d8406b2721c6de4c19cfb01a9 internal/valkey/client.go
a4ad9f48e47f3ea3c8840de395240efc90e665963ef868060eafb64830820b84 internal/valkey/client_test.go
2ff6ea983401d03d9306ccf6db2cdbc8133584f8c8076d653d3e42c5387205ae 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
be0197d3b5d1efc45dd2333ad7913c958b5093ec1d5d48678031dcfeb13cc236 internal/controller/http/fiber/body_limit_test.go
80f3ed3acf294db47a63d4cb188ccf35ee89775663fef3b900179b3b58ff8488 internal/controller/http/fiber/public_errors_test.go
be356cf26c228958d51f5bafa4305d7325e81ab01065575acbc9b2d7a6ddd4bd internal/controller/http/fiber/configure.go
577749cf02bca969e7ad9776301cca3d837a9c8e16975322fd6b7804b0e4d437 internal/controller/http/fiber/attachments_test.go
9eecf0eb9cb7d00f9555e4ecdca907f819dad5565bf6eb81fdf14cb85626b85e internal/controller/http/fiber/controller.go
46e54e78bd180f7270364d5c6608d0760828083d7cf66a6d427e9c541e33b533 internal/controller/http/fiber/errors_test.go
710868cfb1b5ab3db73b55126c78132278badd760d0173c4612d54aa9e069862 internal/controller/http/fiber/auth_test.go
819bc5081693555fb7b93cd627aa456529d64692ce7d9bba33c9ca1cd8739e32 internal/controller/http/fiber/messages_test.go
54db82201697bdfcc65712afe61b650f8f0885fc65222dc4cc6d1c3bb07d82dd internal/controller/http/fiber/metrics.go
e1be1678e02a0ea08c1075ca2b6802f6c66a4ebe8a9212ba26ce9a73f6fe0b8c internal/controller/http/fiber/auth.go
6bc72fdc23332e08e4dee8a5ed3f9110952208af86b529d5d4847ebcf00dd4c3 internal/controller/http/fiber/stream.go
cefa6f9f5c2aeb9a7dd05ca0af2fad037cb0874880066af9f2b3c06a5ea8dd86 internal/controller/http/fiber/middleware_test.go
4b2316357f3bdcb74281fd63a11b88aaebeac89a048a152fed6ddd9069793fa9 internal/controller/http/fiber/metrics_test.go
698b30c81d0aff9c9e572f28dd923c12509f8195b10ca90b231489417b04cad0 internal/controller/http/fiber/handlers.go
17067fd19b22c5f0b0ee7c0aad998bcb079a89e1887c1112b554968c377163a0 internal/controller/http/fiber/controller_test.go
20c9f1d2d225e8ec7c7f112f6a0484daf91144ff05d597bc4bfa36d33ec422a6 internal/controller/http/fiber/health.go
f39cf7a0049a2ed39d6cc1fcc66b44656d9d6120914d0e973b032e12f3d0de08 internal/controller/http/fiber/lifecycle.go
fe59de68ad07ae56c061b01a7946e848b3ee41a3005a3ae9fee1843d31aba5ab internal/controller/http/fiber/metrics_labels_test.go
213db04eda343aa99f0012e397a7682818d373468ea4cc86f667b5ea49c67056 internal/controller/http/fiber/public_errors.go
9c6bd1e261696676d4a2595f5fd9b42e5767f7d88e8e182d23d54a4a1e5a240e internal/controller/http/fiber/attachments.go
e248223517102e1eecdeba9a5e2d844c0afc14116a56e9a1d76c6afb755e63d1 internal/controller/http/fiber/routes.go
6ee07f110bdb29d8d2191ab8889ba60474b33a5b225739875c8a57d8434be15d internal/controller/http/fiber/dependencies.go
964475bec144153d75808e424a36e369de184178aa74ec203ab39fa3ef44df65 internal/controller/http/fiber/middleware.go
3351a019c43d0360ee0fd68afabb5200422d065ae7bd908b1c0a5c02a0c1ad41 internal/controller/http/fiber/error_codes.go
c864c9bed9780e0426b1f8cee8148e8b68461235181bb3e12affa2f5c151749b internal/controller/http/fiber/fixtures_auth_test.go
9d5da8d98ece2706e324cb2deca915e0811b6ad98f7aaac5805ca0f3cc0a1f9a internal/controller/http/fiber/error_registry.go
496f50e5693456574614b8a47086a550018884adb37919ce82abf8c4e7e5254d internal/controller/http/fiber/lifecycle_test.go
a4977c8fa919e24f6166e5f63049f17580bd931e82fbeb998d8c46b16085261f internal/controller/http/fiber/mapping.go
9c092ba7bca191f25c3ba9c9a5d1ca844126bee740a4c0262b776e947263ac68 internal/controller/http/fiber/chats_test.go
268b06298f54aedeac396c8edd4803db6bce99beb88a1fe9ae70c5745d5d5930 internal/controller/http/fiber/decode.go
d32a9a01a8b391f4d986e14947a25a0504f4363335ea1524df05e0dd8e9e61bd internal/controller/http/fiber/headers.go
9a12f72cf7755c2f9f5dd3b789da9289ea8fe3d0f86768696511636b3b430997 internal/controller/http/fiber/errors.go
af72da25fea9811c13a50c8133e9e8b35e070c5295069c40c0ae89cdc0aff19a internal/controller/fx.go
db32692e7fd00b352cf94a0aecce1d552378f17f43f14bcd4c65d5ad9c46c859 internal/objectstore/list.go
11e3e0612b675587f8c5a3ae1a6d677681c6a02db9c70ef299f2c7c56538a7d7 internal/objectstore/client.go
e18f188c0682efd217dd86411d9558875a378c26e59d74baa176b1dbd644d49c 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
801a6290037459a1f9d28669b4f3cdce5191317da8a48189027b7a507139fdc7 internal/model/dto/attachment.go
d68827b0bd3e6df4037621b6941298d3923dc348bda5bf314a34861e7c34f04e internal/model/http/models.go
116f163dcd445952f9d8970474ad8902a54fe8dea5db9ffad3d8059af2b93f22 internal/imageprocessor/processor_test.go
c49dfbfa30970b5dcfd007412f08bea9a8dde34123c383de4e162cebe549f479 internal/imageprocessor/processor.go
3356ae59675b6fec351c9f8e330e7b57f0421b4a3c56826b83579901d3d952dc internal/service/auth.go
80b4ac4c0485587944738db2a9fcef7ce2c93752e1ede3cdbf5d3ae4e68af1b8 internal/service/cache.go
5b6980fcdeee31406a055fa2168c8390bfb572b87ba8c4638f945242a94b3e25 internal/service/interface.go
80dad2c7c823946f20aeecb362284d61acdfe9b7777797e513954280aca3a69e internal/service/production/members.go
ce7ef3afbebd5be41e5c007ac4c791974cbb7a90cae44b6580d3b979f572eb76 internal/service/production/users.go
07d47f11c4970db2a2e52ba5743cd97d2b3b544f321199d9668a456fe01793fa internal/service/production/messages_page_test.go
7d40079a3f39c5368e1196f5ad4eab1f8ff0ac4b76d820218fdb762a7940ebd2 internal/service/production/users_test.go
a8283a9e57476f58d0641b0ba9c53e97a5cb8f3f0999aa4c9054846368272bcc internal/service/production/creation.go
e0b05345fe4b27bc4342d9984790d9ff20ca2fb42dfdc8f7af16430d0c849cbb internal/service/production/chats_page_test.go
115ae85418856016094834d87d18ea5b8e69d0a07ce94dc57693f9cf2e07125e internal/service/production/service.go
e842671b1a1dca5c351a2f4c95cdc08286760ac7b166291c957e48b8c0023663 internal/service/production/messages_test.go
de9187e453981ef90f7b1fc4cba8cf85c1a966ee6ba06742896b9491f1a55fe9 internal/service/production/cache_test.go
0e7473462f2b84e59382fbeb50526cae27e21593812d61fadacec9f5e9b9ef1d internal/service/production/service_test.go
cea224f805326af5bc4c592e44ad196eae786c3da77f5fce7b5cc1585a6a34d0 internal/service/production/access.go
b827d1a5a7c0228d290a2c43fcdd699490bf46de9adfbe029fbfb2f1a7c0715d internal/service/production/pagination_test.go
f14ec3b004ddfdb53a91a969f5229aa61c8b2f4bdbf378f218bb30569061e736 internal/service/production/fixture_test.go
7cff211475ee6674f046bdd266be77f570bc2a6bf8bac7500f87ce0a34732e55 internal/service/production/chats.go
b015718afbba0fe5ff07026d24671d7d64f2371d9bb9aab71d0b32c148485c68 internal/service/production/messages.go
c79685d44f09a1415f01964044e93c5eb4d639d33483e01ed4fab1e779ae8fef internal/service/production/pages_test.go
6b1e69ee07b150a9eaa9455a5e2a4713e6d75ff84826f8e412b557d2cde069fe internal/service/production/pages.go
ef26856b09c27cb28f4ac7da574381f35238ecb63ac343e42328d3a6857bf479 internal/service/production/validation.go
1795adc6534444437b4506a1fe877ed84d4e467cf8dabfd4a3d62619b6b69d1c internal/service/production/chats_test.go
9c8caa8d16212873a45fe41ccb1099909719a48037b9bfdfa887920b03b905b1 internal/service/production/pagination.go
ad61a1d9a8c24529bf740830145cc2321356b4f28755feb76482a54e5e92d1c4 internal/service/production/errors.go
211ccca8211ef97f5a0fac8233eb30f8177b668c9c791e4b7e32ba2b0ad757ff internal/service/cursor.go
36352c672ceae93d31c45f8d3e1cc87e3258d2a29f68b133e9a320670d3fa3fe internal/service/authentication/service.go
eb01e64224ddd19ae5e38d4d07fb907c14734abfff0f0f82b8559869cc7a47d3 internal/service/authentication/service_test.go
cb9c48d4645606804e36899f7d7e92515dbd639d208e78e77132da2e914a5236 internal/service/errors.go
b00028003597503642cb724d51742e9b0d31ec895de65617e306d85728d3758f internal/store/memory/users.go
bad15ff32af251160e895c44865afe1d58ae00b0d634c753f8c64d989ac03226 internal/store/memory/users_test.go
5b4f4f709fa2d900c724fe8f06acf8d30ab2bde060ce0c699365e59034eb4751 internal/store/memory/store_test.go
5f3a9fc819b350be1396aa7871004a56ad725c72a0bfe2c30a29d02478cebd12 internal/store/memory/capacity.go
bcb926dfa0dd97aede21ceea5d1c2701ca1974a6d475d788e1249a590ba88e64 internal/store/memory/messages_test.go
70ed551d8fa8ad1642b649f0d1b297dd1575500adf111543da40a0dab7d632fb internal/store/memory/store.go
0301a131a41f109e7ec14b9124c60919985039432e1760d276c3b122d0b1ab7b internal/store/memory/chats.go
babf91f353e7a921732509502618c6eb15eaf50e0337eabeea3c24961337dfb2 internal/store/memory/messages.go
1fb740f80f21ca1fb80563d4b8c090eddf8f0641cbbe36b33363e4d5b6d941c7 internal/store/memory/ordering.go
af284cfb0fd5ab0b64919250d548894e77421b8dece4c536f1efef15959bc34a internal/store/memory/chats_test.go
ee284df14fbbc6c13dbdb746145ea4274ce6fe7453bce0d6a74424d4934416ed internal/store/interface.go
fa7f5ae93796d19ab652c5f6f9c6fc691ac4963b33d9dbb114c766912a8fd7f2 internal/store/postgres/users.go
1336ef711833e50342534b7186c37748fae187faccd94b8c5d06035a37925b16 internal/store/postgres/migrations/005_retention.sql
448f0287ddd1e68914edcda4b39cc90daaac952a8e19a9e938ad78d27601b590 internal/store/postgres/migrations/003_attachments.sql
3678bb935ed8006d4bdc3e928231cfc5e8ba29e397d6b70122675933acd2a6f4 internal/store/postgres/migrations/002_idempotency.sql
8b8bf6a255cc48cee4b3e4adc94c23cf6955ecf5dfba689bba973dfccbd1b1cb internal/store/postgres/migrations/001_initial.sql
8d5cdffcfadd99564821fa6f7adad8d8a2d70bfaa21b630ded6dd6d06fbf2b71 internal/store/postgres/migrations/004_pipeline.sql
734a1c244184f0fb0e5e944f1f66ac826768e566508c6a7d5e880a2b10494ef6 internal/store/postgres/attachments_test.go
086828379f4b133a63fd0035eb95f61f0ebb95dc73db185e49b9b9867dc7b7f7 internal/store/postgres/store_test.go
e94fac7f9faa88b770516e304abcb8c9fb55d4b7ae9e518f8770a68ad6490508 internal/store/postgres/errors_test.go
889a63b51b29012f4ae5499d1c0577fe29f2f2959b05629f8e123715cfc1f75f internal/store/postgres/sessions.go
6b867ec688b3d85a08686b4800a5d609eab738a14b2bc82c0aa6cae9bf651cdd internal/store/postgres/pipeline_integration_test.go
de4efc201bd7675fd7e59f84f63db36595eba57994a8bcafba99bf6865170583 internal/store/postgres/store.go
42ebffa0e5c1b0a3d510bd91a1c26f0e579c3ca8c5b3bb17fa5d29f6449879f8 internal/store/postgres/idempotency_test.go
97058e07beb5a69e3d31019eae8cb8adfeeef9b90c0ff5920ed0b5e33f977cce internal/store/postgres/research_test.go
d7b4b38642eb7e430c5ea0e5534ab4f7e9ea5e7064985a204226974afb553dc0 internal/store/postgres/jobs_test.go
45775eaff303da4e1aee28c0ab572347f596058084a9fecbc208fef560401686 internal/store/postgres/idempotency.go
ba7a0e545181613b72bde03d14ca60cea8483dff383b79ba8f196fd7edc860b0 internal/store/postgres/chats.go
f201438f8910a9ac0a5d59e2ffa249b54856b6c55c89034b4742e233c9407ee1 internal/store/postgres/messages.go
6ca456767aec350fe81af74deb82a04fcb8689896d11ed547d3855a01f1b57e7 internal/store/postgres/retention.go
375914d765b4ae8e1ba25767bb6e96d6de8ce29a8787055f4242971cb0b5900d internal/store/postgres/reconcile_fixture_test.go
91d59bbd30fa4630228c30132956eaf7c2e0ac910f612ee78448ee1bf9f5fcb0 internal/store/postgres/jobs.go
6ef89edb102f3d8c677a5312abb5ecc3730caf96ef1a416ee3dffad0a357b695 internal/store/postgres/attachments.go
0d2f5e4b8d98869c20d4b7daffe4ba005b8170deeba9d9af2702a7271d8b5b30 internal/store/postgres/reconcile.go
ee47dd3b163cc867c298b106cdcd5fcc22f65c714d21eac3ee7b87cc7613fc16 internal/media/service.go
2706c5a1a382716b5eb34e30d1f0c26142bc8d56bd61b24631d44a6b01fad095 internal/media/run_reconcile_test.go
dbcd539dd3a292ca37245f2b40fe4a232932be6e0f7d7cfa47ff631adbc5414f internal/media/service_test.go
327ee894c8c9afa5bcf8236ed4c91befd66699c0ca33178e9690705764faf002 internal/media/orphans.go
079795a111ff64f80d2219aa4483cd77030b715d581aa9becff1d48b9bcda299 internal/media/validation.go
414008a012afed6086b1bdce9b5ebcc13070a636b6e0948634ac22523c8c5e8e internal/media/reconcile_test.go
0c268c2db1a82be8e4da16bbbd3d1ecc3d4cf86fed03cc290884eb13cb2f1fd9 internal/media/reconcile.go
3255403afcb9486d33c5bb45b5afa9c3c9b85596ce97f86ac2f224011cd8a860 internal/media/run_reconcile.go
2b93b698dee0eb94a1b430af2a5d5036385a10a1934a7b445121fdabff7e11a2 internal/media/validation_test.go
5c43ce42374e4235a363a030e5204a705344e47b03dabd6853adbd571028c0be 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
434138046d43a480f9d8c07d6ef47f51eda699c5f10c4d7f849d4c17bf53de9e charts/messenger/templates/worker.yaml
7937ef25fb5d23a231cceedfbf79ed36244e9c27ce409db938745dec43e5272e charts/messenger/templates/migrate.yaml
7dc488f92544b0d7a4bf1d6abcb807eb01ed8c41100983671752c630ff0626a0 charts/messenger/templates/network-policy.yaml
a4fa258f575e01fba40dd0616d37e3defb43b84b5c83949420543621ac70af74 charts/messenger/templates/hpa.yaml
0fc92783f1a210eb5af8cf55ee531a8a474429e65fb37033d17b16f45f515658 charts/messenger/templates/postgres.yaml
58c4bb123e997054313db6b9044ba9f4f3659174c4dbaee4bb614364a8c8b846 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
6b9ce3c486a4cd1efcf73cd11ead32ddc67431024935851b75dd6c69753532a1 charts/messenger/values.yaml
aada77ad42debd425cec516e33668a640fc0257f30d1a9aa2f15534ed042bf01 scripts/restart.sh
7c4402c2a6ab80d3b4676e1866d6ecc87b6daea14c080bcb9be9a7e8b959d671 scripts/check_contract.py
cfde6a1eb3fec42727dc09691e49c68efad48b1458a08b584a7e608ddf37900f scripts/local-action.sh
1bcf34394520b89d95b7605ec56675be799eea920e83cfbba306d5dc0a6d9811 scripts/stop-one.example.sh
d1b09abb1447c9cbfbd17edc12491f0985dcd5652b16cb71a93651d289b46ce8 scripts/stop-one.sh
8d95bd4497cca2424027ac0a6e3eee4413a5623057d5abe95917a2cc609395db scripts/test-durable.sh
b231016d1e6be9735a6a8925031c6b0e7bf2be9f48be8e7b7aaa2ed5db8b2fbc scripts/port-forward.sh
6f29c6cf608d37dd12e17cf6b42611d6b224c013bb4d837b465ec2accc7bc3f3 scripts/test-local.sh
e70fd589b93cf610e7f18ecd741be9cebeea4320bb152d58438259cead557a84 scripts/init-secrets.sh
ef558cca63208965684764243b0e7ad2383d9d76082e929358479d24ae2bb436 scripts/coverage.sh
4e981acbfc10dac58817bf922d5896e996798551fedc1b2385130e1cddb13d54 scripts/validate_openapi.py
0328246ba75defbced992104e986fde973f63e3830d83251eced5953263e944b scripts/restart.example.sh
0587e6b6d9387fb0179b23d283694121300732c898aad95eabe0376f744fe94c scripts/coverage.awk
a7f93eedc694e099e2b609d04bee5e0920e0c4b06b0692a5688d4ba5913d7259 student-tests/quality_test.go
06afbaa27c7c30e2ed49628dd7fedafdbcd615191f8a05d5e30aa0f00549a9bd 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
View File
+4
View File
@@ -0,0 +1,4 @@
2026-10-29T13:47:54Z target=local-b action=stop
2026-10-29T13:48:11Z action=restart-api-worker-postgres-valkey-s3-broker retained-container-filesystems
2026-10-29T13:48:48Z action=stop-worker
2026-10-29T13:48:49Z action=restart-api-worker-postgres-valkey-s3-broker retained-container-filesystems
+1
View File
@@ -0,0 +1 @@
6f1a990310dc9a6baef485f139cd5156d44a1c22e82fdcc2b44a923dcd3708e4 /var/folders/j2/q072k5hn69lbhbzd5sbzrzbm0000gp/T/tmp.Efpku8qsqq/server
+2
View File
@@ -0,0 +1,2 @@
worker_stopped=true upload_status=202 snapshot=queued message_created=true content_status=409
PASS: accepted intent survived API, worker, PostgreSQL, S3 and AOF broker restart; ready=1 variants=3 original_unchanged=true
+4
View File
@@ -0,0 +1,4 @@
python3 tests/resilience.py --mode failover --action-script "/Users/marlo/go/src/gitflick.ru/vlad_marlo/gitea/mtusi2026lab5/scripts/local-action.sh" --base-url "http://127.0.0.1:50313"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 120, "failed_attempts": 0, "first_recovery_seconds": 0.876}
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/mtusi2026lab5/scripts/local-action.sh" --base-url "http://127.0.0.1:50313"
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:50313"
PASS: lab5 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:50313"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
View File
+57
View File
@@ -0,0 +1,57 @@
module gitea.privcloud.tech/vlad_marlo/mtusi2026lab5
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/disintegration/imaging v1.6.2 // 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/image v0.0.0-20191009234506-e7c1f5e7dbb8 // 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
)
+133
View File
@@ -0,0 +1,133 @@
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/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
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/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
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.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
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)
}
})
}
}
+25
View File
@@ -0,0 +1,25 @@
package config
import (
"fmt"
"os"
"github.com/google/uuid"
)
// Worker contains the broker address and a process-unique consumer identity.
type Worker struct {
// BrokerAddress is a private Valkey Streams endpoint.
BrokerAddress string
// Consumer is never used as an unbounded metric label.
Consumer string
}
// NewWorker requires an explicit broker separate from the admission shards.
func NewWorker() (*Worker, error) {
address := os.Getenv("BROKER_ADDRESS")
if address == "" {
return nil, fmt.Errorf("BROKER_ADDRESS is required")
}
return &Worker{BrokerAddress: address, Consumer: uuid.NewString()}, nil
}
+24
View File
@@ -0,0 +1,24 @@
package config
import "testing"
// TestWorkerConfiguration requires a broker and gives each process an independent consumer ID.
func TestWorkerConfiguration(t *testing.T) {
t.Run("missing", func(t *testing.T) {
t.Setenv("BROKER_ADDRESS", "")
if _, err := NewWorker(); err == nil {
t.Fatal("missing broker accepted")
}
})
t.Run("configured", func(t *testing.T) {
t.Setenv("BROKER_ADDRESS", "broker:6379")
first, err := NewWorker()
if err != nil {
t.Fatal(err)
}
second, err := NewWorker()
if err != nil || first.Consumer == second.Consumer || first.BrokerAddress != "broker:6379" {
t.Fatal("invalid consumer configuration")
}
})
}
+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,123 @@
package fiber
import (
"context"
"io"
"net/http"
"time"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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 []dto.Variant `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: publicVariants(a.Variants),
ErrorCode: a.ErrorCode,
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.StatusAccepted).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))
}
// publicVariants copies generated metadata without exposing storage keys.
func publicVariants(variants []dto.Variant) []dto.Variant {
result := make([]dto.Variant, 0, len(variants))
for _, variant := range variants {
variant.ObjectKey = ""
result = append(result, variant)
}
return result
}
@@ -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/mtusi2026lab5/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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 queued", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{attachment: dto.Attachment{ID: uuid.New(), Status: "queued"}}, http.StatusAccepted},
{"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/mtusi2026lab5/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/mtusi2026lab5/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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/mtusi2026lab5/internal/config"
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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/mtusi2026lab5/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/controller"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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/mtusi2026lab5/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/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
}

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