lab1
This commit is contained in:
@@ -18,3 +18,7 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
bin
|
||||
coverage.out
|
||||
coverage.out.tmp
|
||||
*.log
|
||||
|
||||
@@ -3,3 +3,5 @@
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
APP_READ_HEADER_TIMEOUT=10s
|
||||
APP_SHUTDOWN_TIMEOUT=10s
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
name: Application
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
GO_VERSION: "1.27.0"
|
||||
GOLANGCI_LINT_VERSION: v2.13.2
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
cache: true
|
||||
- run: make lint
|
||||
|
||||
unit-test:
|
||||
name: Unit tests
|
||||
needs: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
cache: true
|
||||
- run: make unit-test
|
||||
|
||||
build:
|
||||
name: Docker build
|
||||
needs: unit-test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: false
|
||||
tags: mtusi-messenger:ci
|
||||
@@ -24,6 +24,8 @@ target/
|
||||
bin/
|
||||
obj/
|
||||
coverage/
|
||||
coverage.out
|
||||
coverage.out.tmp
|
||||
*.log
|
||||
.DS_Store
|
||||
.idea/
|
||||
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
# yaml-language-server: $schema=https://golangci-lint.run/jsonschema/golangci.v2.13.jsonschema.json
|
||||
|
||||
version: "2"
|
||||
|
||||
run:
|
||||
timeout: 5m
|
||||
tests: true
|
||||
build-tags:
|
||||
- integration
|
||||
|
||||
linters:
|
||||
default: standard
|
||||
enable:
|
||||
- bodyclose
|
||||
- contextcheck
|
||||
- containedctx
|
||||
- noctx
|
||||
- rowserrcheck
|
||||
- sqlclosecheck
|
||||
- fatcontext
|
||||
- errorlint
|
||||
- errname
|
||||
- nilerr
|
||||
- nilnil
|
||||
- asasalint
|
||||
- durationcheck
|
||||
- exhaustive
|
||||
- forcetypeassert
|
||||
- gocheckcompilerdirectives
|
||||
- gocritic
|
||||
- makezero
|
||||
- musttag
|
||||
- reassign
|
||||
- recvcheck
|
||||
- unparam
|
||||
- wastedassign
|
||||
- gosec
|
||||
- canonicalheader
|
||||
- copyloopvar
|
||||
- exptostd
|
||||
- intrange
|
||||
- perfsprint
|
||||
- unconvert
|
||||
- usestdlibvars
|
||||
- usetesting
|
||||
- prealloc
|
||||
- revive
|
||||
- misspell
|
||||
- nolintlint
|
||||
- gomoddirectives
|
||||
- sloglint
|
||||
- depguard
|
||||
- forbidigo
|
||||
- testifylint
|
||||
- thelper
|
||||
- tparallel
|
||||
|
||||
settings:
|
||||
govet:
|
||||
enable-all: true
|
||||
disable:
|
||||
- fieldalignment
|
||||
- shadow
|
||||
|
||||
gosec:
|
||||
excludes:
|
||||
- G404
|
||||
|
||||
exhaustive:
|
||||
default-signifies-exhaustive: true
|
||||
|
||||
nolintlint:
|
||||
require-explanation: true
|
||||
require-specific: true
|
||||
|
||||
sloglint:
|
||||
attr-only: true
|
||||
no-global: default
|
||||
context: scope
|
||||
|
||||
testifylint:
|
||||
enable-all: true
|
||||
|
||||
depguard:
|
||||
rules:
|
||||
main:
|
||||
deny:
|
||||
- pkg: math/rand$
|
||||
desc: use math/rand/v2
|
||||
- pkg: github.com/pkg/errors
|
||||
desc: use stdlib errors and fmt.Errorf with %w
|
||||
- pkg: io/ioutil
|
||||
desc: deprecated
|
||||
domain:
|
||||
files:
|
||||
- "**/internal/domain/**"
|
||||
deny:
|
||||
- pkg: database/sql
|
||||
desc: domain must not depend on infrastructure
|
||||
- pkg: net/http
|
||||
desc: domain must not depend on transport
|
||||
|
||||
forbidigo:
|
||||
forbid:
|
||||
- pattern: ^fmt\.Print(f|ln)?$
|
||||
msg: use slog
|
||||
- pattern: ^log\.(Print|Fatal|Panic).*$
|
||||
msg: use slog
|
||||
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- comments
|
||||
- std-error-handling
|
||||
- common-false-positives
|
||||
rules:
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- gosec
|
||||
- prealloc
|
||||
- forcetypeassert
|
||||
- unparam
|
||||
|
||||
formatters:
|
||||
enable:
|
||||
- gofumpt
|
||||
- goimports
|
||||
settings:
|
||||
gofumpt:
|
||||
module-path: mtusi-messenger
|
||||
goimports:
|
||||
local-prefixes:
|
||||
- mtusi-messenger
|
||||
exclusions:
|
||||
generated: lax
|
||||
|
||||
issues:
|
||||
max-issues-per-linter: 0
|
||||
max-same-issues: 0
|
||||
@@ -0,0 +1,23 @@
|
||||
#https://vektra.github.io/mockery/latest/configuration/
|
||||
|
||||
all: false
|
||||
dir: "{{.InterfaceDir}}/mocks"
|
||||
pkgname: mocks
|
||||
filename: "{{.InterfaceName}}.go"
|
||||
structname: "Mock{{.InterfaceName}}"
|
||||
template: testify
|
||||
formatter: goimports
|
||||
force-file-write: true
|
||||
include-auto-generated: false
|
||||
log-level: info
|
||||
|
||||
packages:
|
||||
mtusi-messenger/internal/service/user:
|
||||
config:
|
||||
all: true
|
||||
mtusi-messenger/internal/service/chat:
|
||||
config:
|
||||
all: true
|
||||
mtusi-messenger/internal/service/message:
|
||||
config:
|
||||
all: true
|
||||
@@ -0,0 +1,10 @@
|
||||
# yaml-language-server: $schema=https://raw.githubusercontent.com/ogen-go/ogen/v1.24.0/schemas/ogen.jsonschema.json
|
||||
|
||||
# https://ogen.dev/docs/config/
|
||||
generator:
|
||||
features:
|
||||
disable:
|
||||
- paths/client
|
||||
- webhooks/client
|
||||
- webhooks/server
|
||||
- ogen/otel
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
ARG GO_VERSION=1.27.1
|
||||
ARG ALPINE_VERSION=3.22
|
||||
|
||||
FROM golang:${GO_VERSION}-alpine AS build
|
||||
ARG TARGETOS=linux
|
||||
ARG TARGETARCH=amd64
|
||||
ARG VERSION=dev
|
||||
ENV GOTOOLCHAIN=local
|
||||
WORKDIR /opt
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
|
||||
go build -trimpath -buildvcs=false -tags timetzdata \
|
||||
-ldflags="-s -w -X main.version=${VERSION}" \
|
||||
-o /out/messenger ./cmd/messenger
|
||||
|
||||
FROM alpine:${ALPINE_VERSION} AS runtime
|
||||
RUN apk add --no-cache ca-certificates wget \
|
||||
&& addgroup -S -g 10001 app \
|
||||
&& adduser -S -D -H -u 10001 -G app app
|
||||
|
||||
COPY --from=build --chown=10001:10001 /out/messenger /usr/local/bin/messenger
|
||||
|
||||
ENV APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080 \
|
||||
APP_READ_HEADER_TIMEOUT=10s \
|
||||
APP_SHUTDOWN_TIMEOUT=10s \
|
||||
APP_LOG_LEVEL=info \
|
||||
APP_LOG_FORMAT=json
|
||||
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
STOPSIGNAL SIGTERM
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget -q -O /dev/null "http://127.0.0.1:${APP_PORT}/health/live" || exit 1
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||
@@ -3,8 +3,9 @@ BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
PYTHON_LOCAL = env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 $(PYTHON)
|
||||
|
||||
.PHONY: help check validate test load
|
||||
.PHONY: help check validate test load smoke-local load-local
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -20,3 +21,59 @@ test:
|
||||
|
||||
load:
|
||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
smoke-local:
|
||||
$(PYTHON_LOCAL) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
load-local:
|
||||
$(PYTHON_LOCAL) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
GO ?= go
|
||||
APP_NAME ?= messenger
|
||||
CMD_PKG := ./cmd/$(APP_NAME)
|
||||
LOCAL_BIN := $(CURDIR)/bin
|
||||
GOLANGCI_LINT_VERSION ?= v2.13.2
|
||||
GOLANGCI_LINT := $(LOCAL_BIN)/golangci-lint
|
||||
OPENAPI_SPEC := contracts/openapi.json
|
||||
OGEN_CONFIG := .ogen.yml
|
||||
OAS_DIR := internal/transport/rest/oas
|
||||
|
||||
.PHONY: unit-test
|
||||
unit-test:
|
||||
$(GO) test -race -shuffle=on -count=1 -timeout=5m ./...
|
||||
|
||||
# не учитываем генеренные файлы, также cmd в подсчете покрытия
|
||||
COVER_EXCLUDE ?= /(mocks|oas)/|/cmd/
|
||||
|
||||
.PHONY: cover
|
||||
cover:
|
||||
$(GO) test -race -shuffle=on -count=1 -timeout=5m \
|
||||
-covermode=atomic -coverprofile=coverage.out.tmp ./...
|
||||
@grep -Ev '$(COVER_EXCLUDE)' coverage.out.tmp > coverage.out
|
||||
@rm coverage.out.tmp
|
||||
$(GO) tool cover -func=coverage.out | tail -n 1
|
||||
$(GO) tool cover -html=coverage.out
|
||||
|
||||
.PHONY: generate
|
||||
generate: generate-api generate-mocks
|
||||
|
||||
.PHONY: generate-api
|
||||
generate-api:
|
||||
$(GO) tool ogen --config $(OGEN_CONFIG) --target $(OAS_DIR) --package oas --clean $(OPENAPI_SPEC)
|
||||
|
||||
.PHONY: generate-mocks
|
||||
generate-mocks:
|
||||
$(GO) tool mockery
|
||||
|
||||
.PHONY: run
|
||||
run:
|
||||
$(GO) run $(CMD_PKG)
|
||||
|
||||
$(GOLANGCI_LINT):
|
||||
GOBIN=$(LOCAL_BIN) $(GO) install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION)
|
||||
|
||||
lint: $(GOLANGCI_LINT)
|
||||
$(GOLANGCI_LINT) run -v
|
||||
|
||||
|
||||
|
||||
@@ -1,37 +1,101 @@
|
||||
# Отчёт — лабораторная 1
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Владислав Кунецкий, БВT2303
|
||||
- Целевая оценка: 5
|
||||
- Выбранный трек 5: трек 1 — предел in-memory архитектуры
|
||||
- Commit/PR: solution/bvt2303-kunetsky
|
||||
- Использованные библиотеки: ogen - генерация транспортного слова из openapi спеки, testify, mockery/v3 - тесты, zap обернутый в slog - логгирование.
|
||||
- Помощь ИИ использовалась для обсуждения архитектуры, ревью и подготовки кода; решение проверено и изменено автором.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Требования: make, Go 1.27+ / Docker
|
||||
|
||||
запуск через go
|
||||
|
||||
```sh
|
||||
make run
|
||||
```
|
||||
|
||||
запуск через docker
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
docker build -t mtusi-messenger:lab1 .
|
||||
docker run --rm --name mtusi-messenger-lab1 \
|
||||
-p 127.0.0.1:8080:8080 --env-file .env mtusi-messenger:lab1
|
||||
```
|
||||
|
||||
|
||||
В другом терминале:
|
||||
|
||||
```sh
|
||||
make check
|
||||
make unit-test
|
||||
make test
|
||||
```
|
||||
|
||||
Контейнер останавливается через `Ctrl-C` или `docker stop mtusi-messenger-lab1`; приложение принимает SIGTERM и завершает HTTP-сервер с timeout 10 секунд. Состояние хранится только в памяти процесса. Удаление контейнера намеренно удаляет все учебные данные:
|
||||
|
||||
```sh
|
||||
docker rm -f mtusi-messenger-lab1
|
||||
```
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Клиент → ogen-generated HTTP transport → REST adapter → user/chat/message services → единый in-memory Store. Store реализован на mutex; создание чата вместе с проверкой участников выполняется атомарно. ID и `created_at` назначаются in-memory storage. После перезапуска процесса данные исчезают. Store реализован таким образом, чтобы в будущем изменить его на реальную базу данных, без изменения сигнатур и кода в сервисах
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Публичный smoke | `make test` | `PASS: lab1 public API scenario` | `evidence/smoke.txt` |
|
||||
| Контракт и структура | `make check` | `PASS` | `evidence/check.txt` |
|
||||
| Unit, vet, race, lint | `make unit-test`, `go vet ./...`, `make lint` | PASS | `evidence/quality.txt` |
|
||||
| Docker build/run/health | `docker build`, `curl /health/live` | image built, `{"status":"ok"}` | `evidence/docker.txt` |
|
||||
| Сброс in-memory состояния | restart container, old `X-User-Id` | old user receives 401 | `evidence/restart.txt` |
|
||||
| 100 concurrent messages | 10 clients × 10 messages | 100 unique messages | `evidence/concurrency.txt` |
|
||||
| SIGTERM | `kill -TERM <pid>` | graceful stop under 10 seconds | `evidence/sigterm.txt` |
|
||||
| Трек 1 benchmark | `go test -run '^$' -bench '^BenchmarkMessageCreate$' -benchmem -count=5 ./internal/storage/memory` и baseline через Go overlay; `scripts/track1_benchmark.py --mode ... --requests 100000` | изолированная вставка 1k/10k/50k и E2E с ровно 100 000 запросами на комбинацию, concurrency 1/4/16/32: RPS/p95/p99/RSS | `evidence/track1/` |
|
||||
| Memory exhaustion point | `python3 scripts/memory_experiment.py --image mtusi2026lab1-messenger:arm64 --memory 64m --max-messages 20000 --output evidence/memory-experiment.json --plot evidence/memory-experiment.png` | container OOMKilled, exit 137, 8997 successful messages | `evidence/memory-experiment.json`, `evidence/memory-experiment.png` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
В рамках трека оптимизировано добавление новых сообщений в конец отсортированной истории. Если ключ нового сообщения больше ключа последнего сообщения, используется прямой `append`; бинарный поиск и упорядоченная вставка остаются fallback-путём для сообщений, пришедших не по порядку. Изолированный Go benchmark выполнялся на Apple M5 Pro, darwin/arm64, Go 1.27.1, пять раз для историй 1 000, 10 000 и 50 000. Baseline собран через Go overlay с удалённым fast path, optimized — текущая версия. Полные сырые результаты: `evidence/track1/baseline-storage-benchmark.txt` и `optimized-storage-benchmark.txt`.
|
||||
|
||||
Отдельно выполнен end-to-end benchmark через `go run` без Docker: истории 1 000, 10 000 и 50 000; конкуренция 1, 4, 16 и 32; ровно 100 000 нагрузочных POST-запросов на каждую комбинацию и 100 warm-up запросов; RSS дочернего исполняемого процесса сэмплировался каждые 100 мс. Baseline запускается через `go run -overlay`, optimized — обычный `go run`. Результаты: `evidence/track1/go-baseline/results.json`, `go-optimized/results.json`, `go-comparison.json`.
|
||||
|
||||
Оптимизация уменьшила стоимость операции добавления сообщения: медиана составляет 308.2 / 241.8 ns/op для истории 1 000, 335.9 / 242.2 ns/op для 10 000 и 349.8 / 242.5 ns/op для 50 000 (baseline / optimized). Это соответствует ускорению примерно в 1.27×, 1.39× и 1.44× соответственно. Число аллокаций одинаковое: 1 alloc/op, 16 B/op. Вставка в середину по-прежнему использует бинарный поиск и `slices.Insert`; оптимизирован только наиболее частый сценарий последовательного добавления в конец.
|
||||
|
||||
На полном HTTP-пути это ускорение не переносится напрямую в RPS: там дополнительно присутствуют HTTP, JSON, маршрутизация и общий mutex `Store`. В новом эксперименте число запросов фиксировано, поэтому сравниваются одинаковые объёмы работы, а не разные числа запросов за заданное время. При увеличении объёма до 100 000 запросов результаты стали стабильнее: optimized выигрывает по RPS в 5 из 12 комбинаций, прежде всего при concurrency 4/16; на concurrency 32 система упирается в конкуренцию за общий mutex, поэтому дополнительное увеличение параллелизма не даёт ускорения. Разница остаётся умеренной, поскольку fast path оптимизирует только часть полного HTTP-запроса.
|
||||
|
||||
### Точка отказа по памяти
|
||||
|
||||
Эксперимент запускался с лимитом контейнера `64m`, swap отключён (`--memory-swap 64m`). В каждое сообщение записывалось 4000 Unicode-символов. Контейнер завершился после 8997 подтверждённых сообщений с `OOMKilled=true` и `ExitCode=137`. На графике `evidence/memory-experiment.png` показан рост памяти контейнера до лимита и число подтверждённых сообщений. Причина отказа — in-memory Store удерживает все сообщения и их строки; после достижения cgroup memory limit ядро завершает процесс OOM killer. Это ожидаемая граница выбранной архитектуры: сервер не вводит лимиты количества сообщений и не выполняет controlled degradation.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Перезапуск контейнера | in-memory данные исчезают | старый пользователь получает 401 | данные теряются намеренно при restart |
|
||||
| SIGTERM | сервер прекращает приём и завершает работу | остановка менее 10 секунд | подтверждённые данные не сохраняются |
|
||||
| 10 клиентов × 10 сообщений | ровно 100 уникальных сообщений | 100 уникальных сообщений | нет потери в рамках процесса |
|
||||
|
||||
### Трек 1: baseline / optimized
|
||||
|
||||
| History | Concurrency | Requests before/after | RPS before | RPS after | p95 before/after ms | p99 before/after ms | RSS max before/after KiB |
|
||||
| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 1000 | 1 | 100000 / 100000 | 7334.409 | 7184.594 | 0.146 / 0.150 | 0.186 / 0.231 | 32560 / 32272 |
|
||||
| 1000 | 4 | 100000 / 100000 | 8823.924 | 8996.523 | 0.654 / 0.632 | 0.869 / 0.867 | 35520 / 35504 |
|
||||
| 1000 | 16 | 100000 / 100000 | 7336.995 | 7482.719 | 3.514 / 3.445 | 4.631 / 4.577 | 35808 / 35680 |
|
||||
| 1000 | 32 | 100000 / 100000 | 7386.656 | 7381.500 | 7.026 / 7.058 | 8.953 / 9.054 | 36336 / 36208 |
|
||||
| 10000 | 1 | 100000 / 100000 | 7138.887 | 7150.931 | 0.149 / 0.146 | 0.210 / 0.187 | 36208 / 36224 |
|
||||
| 10000 | 4 | 100000 / 100000 | 9043.732 | 9052.965 | 0.626 / 0.628 | 0.841 / 0.859 | 38496 / 38384 |
|
||||
| 10000 | 16 | 100000 / 100000 | 7442.895 | 7440.817 | 3.485 / 3.468 | 4.703 / 4.701 | 38384 / 38624 |
|
||||
| 10000 | 32 | 100000 / 100000 | 7382.485 | 7419.326 | 7.051 / 7.049 | 9.096 / 9.096 | 38384 / 38400 |
|
||||
| 50000 | 1 | 100000 / 100000 | 7158.653 | 7213.610 | 0.149 / 0.145 | 0.211 / 0.191 | 52416 / 52304 |
|
||||
| 50000 | 4 | 100000 / 100000 | 9079.212 | 9036.335 | 0.623 / 0.630 | 0.823 / 0.842 | 53152 / 53008 |
|
||||
| 50000 | 16 | 100000 / 100000 | 7419.068 | 7453.530 | 3.471 / 3.455 | 4.694 / 4.688 | 53536 / 53216 |
|
||||
| 50000 | 32 | 100000 / 100000 | 7427.333 | 7384.536 | 7.049 / 7.084 | 9.007 / 9.203 | 53760 / 53776 |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Решение выдерживает конкурентные запросы внутри одного процесса и корректный SIGTERM. Оно не сохраняет состояние после перезапуска и не рассчитано на несколько API-процессов. Авторизация через `X-User-Id` является учебным механизмом lab1 и не является безопасной аутентификацией. Persistence, внешняя база и горизонтальное масштабирование не реализованы.
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/service/chat"
|
||||
"mtusi-messenger/internal/service/message"
|
||||
"mtusi-messenger/internal/service/user"
|
||||
"mtusi-messenger/internal/storage/memory"
|
||||
"mtusi-messenger/internal/transport/rest"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := logger.New()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Error("load config", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
log = logger.New(
|
||||
logger.WithLevel(cfg.SlogLevel()),
|
||||
logger.WithFormat(cfg.LoggerFormat()),
|
||||
)
|
||||
slog.SetDefault(log)
|
||||
|
||||
if err := run(cfg, log); err != nil {
|
||||
log.Error("shutdown with error", slog.Any("error", err))
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(cfg config.Config, log *slog.Logger) error {
|
||||
store := memory.NewStore()
|
||||
userService := user.NewService(store.Users())
|
||||
|
||||
router, err := rest.NewRouter(
|
||||
rest.NewHandler(
|
||||
userService,
|
||||
chat.NewService(store.Chats()),
|
||||
message.NewService(store.Messages()),
|
||||
),
|
||||
rest.NewSecurityHandler(userService),
|
||||
log,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build router: %w", err)
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: router,
|
||||
ReadHeaderTimeout: cfg.ReadHeaderTimeout,
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
errc := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Info("server started", slog.String("addr", cfg.Addr()))
|
||||
|
||||
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errc <- err
|
||||
}
|
||||
|
||||
close(errc)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err, ok := <-errc:
|
||||
if ok && err != nil {
|
||||
return fmt.Errorf("listen: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
log.Info("shutdown signal received", slog.Duration("timeout", cfg.ShutdownTimeout))
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
return fmt.Errorf("shutdown: %w", err)
|
||||
}
|
||||
|
||||
log.Info("server stopped")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
$ make check
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,2 @@
|
||||
command: docker run + Python ThreadPoolExecutor(10), 100 POST messages
|
||||
{"sent": 100, "read": 100, "unique": 100}
|
||||
@@ -0,0 +1,11 @@
|
||||
$ docker inspect --format ...
|
||||
status=running health=healthy user=10001:10001
|
||||
$ curl -i http://127.0.0.1:8080/health/live
|
||||
HTTP/1.1 200 OK
|
||||
Access-Control-Expose-Headers: X-Request-Id
|
||||
Content-Type: application/json; charset=utf-8
|
||||
X-Request-Id: 3d145e7d-423a-4510-9d6b-6f45b7cf552d
|
||||
Date: Thu, 24 Sep 2026 20:13:14 GMT
|
||||
Content-Length: 15
|
||||
|
||||
{"status":"ok"}
|
||||
@@ -0,0 +1 @@
|
||||
{"status":"ok"}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 102 KiB |
@@ -0,0 +1,8 @@
|
||||
$ python3 scripts/memory_experiment.py --image mtusi2026lab1-messenger:arm64 --memory 64m --max-messages 20000 --output evidence/memory-experiment.json --plot evidence/memory-experiment.png
|
||||
memory_limit=64m
|
||||
successful_messages=8610
|
||||
failed_requests=0
|
||||
OOMKilled=true
|
||||
exit_code=137
|
||||
failure_time_seconds=5.9315
|
||||
plot=evidence/memory-experiment.png
|
||||
@@ -0,0 +1,43 @@
|
||||
$ make check
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ go vet ./...
|
||||
|
||||
$ make lint
|
||||
/Users/vladislav/Projects/mtusi2026lab1-fork/bin/golangci-lint run -v
|
||||
level=info msg="golangci-lint has version 2.13.2 built with go1.27.0 from (unknown, modified: ?, mod sum: \"h1:bCyq3E4vo9qwzifjpzJqYndEt7Ncva80qkk8G2B4TXU=\") on (unknown)"
|
||||
level=info msg="[config_reader] Config search paths: [./ /Users/vladislav/Projects/mtusi2026lab1-fork /Users/vladislav/Projects /Users/vladislav /Users /]"
|
||||
level=info msg="[config_reader] Used config file .golangci.yml"
|
||||
level=info msg="[config_reader] Module name \"mtusi-messenger\""
|
||||
level=info msg="[goenv] Read go env for 5.97475ms: map[string]string{\"GOCACHE\":\"/Users/vladislav/Library/Caches/go-build\", \"GOROOT\":\"/opt/homebrew/Cellar/go/1.27.1/libexec\"}"
|
||||
level=info msg="[lintersdb] Active 50 linters: [asasalint bodyclose canonicalheader containedctx contextcheck copyloopvar depguard durationcheck errcheck errname errorlint exhaustive exptostd fatcontext forbidigo forcetypeassert gocheckcompilerdirectives gocritic gofumpt goimports gomoddirectives gosec govet ineffassign intrange makezero misspell musttag nilerr nilnil noctx nolintlint perfsprint prealloc reassign recvcheck revive rowserrcheck sloglint sqlclosecheck staticcheck testifylint thelper tparallel unconvert unparam unused usestdlibvars usetesting wastedassign]"
|
||||
level=info msg="[loader] Using build tags: [integration]"
|
||||
level=info msg="[loader] Go packages loading at mode 8767 (compiled_files|files|name|types_sizes|deps|exports_file|imports) took 122.006042ms"
|
||||
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 4.792166ms"
|
||||
level=info msg="[linters_context/goanalysis] analyzers took 0s with no stages"
|
||||
level=info msg="[runner/exclusion_rules] Skipped 2 issues by rules: [Path: \"_test\\\\.go\", Linters: \"gosec, prealloc, forcetypeassert, unparam\"]"
|
||||
level=info msg="[runner] Issues before processing: 280, after processing: 0"
|
||||
level=info msg="[runner] Processors filtering stat (in/out): exclusion_paths: 280/280, invalid_issue: 280/280, path_absoluter: 280/280, filename_unadjuster: 280/280, generated_file_filter: 280/100, exclusion_rules: 100/0, cgo: 280/280, path_relativity: 280/280"
|
||||
level=info msg="[runner] processing took 607.916µs with stages: generated_file_filter: 420.959µs, exclusion_rules: 86.124µs, path_relativity: 83.917µs, sort_results: 4.458µs, invalid_issue: 4.292µs, cgo: 3.959µs, path_absoluter: 1.417µs, filename_unadjuster: 792ns, max_same_issues: 582ns, nolint_filter: 457ns, fixer: 292ns, exclusion_paths: 167ns, path_prettifier: 125ns, source_code: 125ns, path_shortener: 124ns, uniq_by_line: 42ns, severity-rules: 42ns, max_per_file_from_linter: 42ns, max_from_linter: 0s, diff: 0s"
|
||||
level=info msg="[runner] linters took 422.737625ms with stages: goanalysis_metalinter: 422.101875ms"
|
||||
0 issues.
|
||||
level=info msg="File cache stats: 0 entries of total size 0B"
|
||||
level=info msg="Memory: 7 samples, avg is 87.0MB, max is 111.2MB"
|
||||
level=info msg="Execution took 555.972916ms"
|
||||
|
||||
$ make unit-test
|
||||
go test -race -shuffle=on -count=1 -timeout=5m ./...
|
||||
? mtusi-messenger/cmd/messenger [no test files]
|
||||
ok mtusi-messenger/internal/config 1.838s
|
||||
ok mtusi-messenger/internal/domain 1.498s
|
||||
ok mtusi-messenger/internal/logger 2.150s
|
||||
ok mtusi-messenger/internal/service/chat 2.470s
|
||||
? mtusi-messenger/internal/service/chat/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/message 2.797s
|
||||
? mtusi-messenger/internal/service/message/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/user 3.474s
|
||||
? mtusi-messenger/internal/service/user/mocks [no test files]
|
||||
ok mtusi-messenger/internal/storage/memory 3.159s
|
||||
ok mtusi-messenger/internal/transport/rest 3.863s
|
||||
? mtusi-messenger/internal/transport/rest/oas [no test files]
|
||||
@@ -0,0 +1,10 @@
|
||||
$ docker stop mtusi2026lab1-messenger-lab1
|
||||
$ docker run -d --name mtusi2026lab1-messenger-lab1 -p 127.0.0.1:8080:8080 mtusi2026lab1-messenger:verify
|
||||
$ curl -i -H "X-User-Id: <created-before-restart>" http://127.0.0.1:8080/api/v1/users/me
|
||||
HTTP/1.1 401 Unauthorized
|
||||
Content-Type: application/json; charset=utf-8
|
||||
X-Request-Id: eadf9c21-d861-4c2c-8e76-46f086d27a11
|
||||
Date: Thu, 24 Sep 2026 20:13:02 GMT
|
||||
Content-Length: 110
|
||||
|
||||
{"error":{"code":"unauthorized","message":"Unauthorized","request_id":"eadf9c21-d861-4c2c-8e76-46f086d27a11"}}
|
||||
@@ -0,0 +1,7 @@
|
||||
$ docker kill --signal=TERM mtusi2026lab1-messenger-lab1
|
||||
$ docker wait mtusi2026lab1-messenger-lab1
|
||||
0
|
||||
elapsed_ms=114
|
||||
{"level":"info","time":"2026-09-24T20:14:19.192628563Z","msg":"server started","addr":"0.0.0.0:8080"}
|
||||
{"level":"info","time":"2026-09-24T20:14:20.186231067Z","msg":"shutdown signal received","timeout":"10s"}
|
||||
{"level":"info","time":"2026-09-24T20:14:20.188996621Z","msg":"server stopped"}
|
||||
@@ -0,0 +1,2 @@
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/smoke.py --base-url "http://127.0.0.1:8080"
|
||||
PASS: lab1 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,21 @@
|
||||
goos: darwin
|
||||
goarch: arm64
|
||||
pkg: mtusi-messenger/internal/storage/memory
|
||||
cpu: Apple M5 Pro
|
||||
BenchmarkMessageCreate/history=1000-18 3822346 309.5 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 3904586 307.6 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 3889698 308.1 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 3892981 308.2 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 3888345 308.3 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3578911 335.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3570348 335.9 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3581305 335.0 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3573933 336.0 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 3563053 336.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3425475 349.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3435330 349.1 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3438290 349.3 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3420394 349.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 3420736 350.1 ns/op 16 B/op 1 allocs/op
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/memory 18.237s
|
||||
@@ -0,0 +1,128 @@
|
||||
[
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 526,
|
||||
"failed_requests": 0,
|
||||
"rps": 262.791,
|
||||
"p50_ms": 3.378,
|
||||
"p95_ms": 4.12,
|
||||
"p99_ms": 16.979,
|
||||
"rss_min_kib": 18880,
|
||||
"rss_max_kib": 22816,
|
||||
"rss_delta_kib": 3936
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 1450,
|
||||
"failed_requests": 0,
|
||||
"rps": 724.134,
|
||||
"p50_ms": 4.18,
|
||||
"p95_ms": 16.695,
|
||||
"p99_ms": 21.604,
|
||||
"rss_min_kib": 20512,
|
||||
"rss_max_kib": 24208,
|
||||
"rss_delta_kib": 3696
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.079,
|
||||
"successful_requests": 2315,
|
||||
"failed_requests": 0,
|
||||
"rps": 1113.309,
|
||||
"p50_ms": 8.563,
|
||||
"p95_ms": 29.584,
|
||||
"p99_ms": 93.023,
|
||||
"rss_min_kib": 18880,
|
||||
"rss_max_kib": 25296,
|
||||
"rss_delta_kib": 6416
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.007,
|
||||
"successful_requests": 478,
|
||||
"failed_requests": 0,
|
||||
"rps": 238.14,
|
||||
"p50_ms": 3.477,
|
||||
"p95_ms": 10.892,
|
||||
"p99_ms": 20.404,
|
||||
"rss_min_kib": 23120,
|
||||
"rss_max_kib": 23584,
|
||||
"rss_delta_kib": 464
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.003,
|
||||
"successful_requests": 1380,
|
||||
"failed_requests": 0,
|
||||
"rps": 688.971,
|
||||
"p50_ms": 4.197,
|
||||
"p95_ms": 17.189,
|
||||
"p99_ms": 28.458,
|
||||
"rss_min_kib": 23344,
|
||||
"rss_max_kib": 24592,
|
||||
"rss_delta_kib": 1248
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.005,
|
||||
"successful_requests": 2298,
|
||||
"failed_requests": 0,
|
||||
"rps": 1146.063,
|
||||
"p50_ms": 8.474,
|
||||
"p95_ms": 29.384,
|
||||
"p99_ms": 92.528,
|
||||
"rss_min_kib": 23232,
|
||||
"rss_max_kib": 26272,
|
||||
"rss_delta_kib": 3040
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.001,
|
||||
"successful_requests": 494,
|
||||
"failed_requests": 0,
|
||||
"rps": 246.902,
|
||||
"p50_ms": 3.414,
|
||||
"p95_ms": 10.767,
|
||||
"p99_ms": 18.996,
|
||||
"rss_min_kib": 25248,
|
||||
"rss_max_kib": 25296,
|
||||
"rss_delta_kib": 48
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.004,
|
||||
"successful_requests": 1398,
|
||||
"failed_requests": 0,
|
||||
"rps": 697.712,
|
||||
"p50_ms": 4.147,
|
||||
"p95_ms": 17.142,
|
||||
"p99_ms": 26.446,
|
||||
"rss_min_kib": 24816,
|
||||
"rss_max_kib": 25104,
|
||||
"rss_delta_kib": 288
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.006,
|
||||
"successful_requests": 2261,
|
||||
"failed_requests": 0,
|
||||
"rps": 1126.862,
|
||||
"p50_ms": 8.635,
|
||||
"p95_ms": 24.133,
|
||||
"p99_ms": 93.225,
|
||||
"rss_min_kib": 25200,
|
||||
"rss_max_kib": 26752,
|
||||
"rss_delta_kib": 1552
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,110 @@
|
||||
[
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 1,
|
||||
"rps_before": 262.791,
|
||||
"p95_ms_before": 4.12,
|
||||
"p99_ms_before": 16.979,
|
||||
"rss_max_kib_before": 22816,
|
||||
"rps_after": 265.189,
|
||||
"p95_ms_after": 4.276,
|
||||
"p99_ms_after": 17.123,
|
||||
"rss_max_kib_after": 22736
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 4,
|
||||
"rps_before": 724.134,
|
||||
"p95_ms_before": 16.695,
|
||||
"p99_ms_before": 21.604,
|
||||
"rss_max_kib_before": 24208,
|
||||
"rps_after": 720.55,
|
||||
"p95_ms_after": 16.868,
|
||||
"p99_ms_after": 21.043,
|
||||
"rss_max_kib_after": 24128
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 16,
|
||||
"rps_before": 1113.309,
|
||||
"p95_ms_before": 29.584,
|
||||
"p99_ms_before": 93.023,
|
||||
"rss_max_kib_before": 25296,
|
||||
"rps_after": 1125.923,
|
||||
"p95_ms_after": 29.142,
|
||||
"p99_ms_after": 91.221,
|
||||
"rss_max_kib_after": 25216
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"rps_before": 238.14,
|
||||
"p95_ms_before": 10.892,
|
||||
"p99_ms_before": 20.404,
|
||||
"rss_max_kib_before": 23584,
|
||||
"rps_after": 237.68,
|
||||
"p95_ms_after": 11.279,
|
||||
"p99_ms_after": 19.675,
|
||||
"rss_max_kib_after": 23504
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"rps_before": 688.971,
|
||||
"p95_ms_before": 17.189,
|
||||
"p99_ms_before": 28.458,
|
||||
"rss_max_kib_before": 24592,
|
||||
"rps_after": 667.05,
|
||||
"p95_ms_after": 17.243,
|
||||
"p99_ms_after": 29.938,
|
||||
"rss_max_kib_after": 25280
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"rps_before": 1146.063,
|
||||
"p95_ms_before": 29.384,
|
||||
"p99_ms_before": 92.528,
|
||||
"rss_max_kib_before": 26272,
|
||||
"rps_after": 1102.581,
|
||||
"p95_ms_after": 30.252,
|
||||
"p99_ms_after": 93.912,
|
||||
"rss_max_kib_after": 25200
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 1,
|
||||
"rps_before": 246.902,
|
||||
"p95_ms_before": 10.767,
|
||||
"p99_ms_before": 18.996,
|
||||
"rss_max_kib_before": 25296,
|
||||
"rps_after": 241.241,
|
||||
"p95_ms_after": 10.897,
|
||||
"p99_ms_after": 18.681,
|
||||
"rss_max_kib_after": 25456
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 4,
|
||||
"rps_before": 697.712,
|
||||
"p95_ms_before": 17.142,
|
||||
"p99_ms_before": 26.446,
|
||||
"rss_max_kib_before": 25104,
|
||||
"rps_after": 685.839,
|
||||
"p95_ms_after": 17.418,
|
||||
"p99_ms_after": 26.618,
|
||||
"rss_max_kib_after": 25376
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 16,
|
||||
"rps_before": 1126.862,
|
||||
"p95_ms_before": 24.133,
|
||||
"p99_ms_before": 93.225,
|
||||
"rss_max_kib_before": 26752,
|
||||
"rps_after": 1079.866,
|
||||
"p95_ms_after": 31.525,
|
||||
"p99_ms_after": 94.709,
|
||||
"rss_max_kib_after": 26640
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,211 @@
|
||||
{
|
||||
"mode": "baseline",
|
||||
"command": [
|
||||
"go",
|
||||
"run",
|
||||
"-overlay",
|
||||
"/var/folders/jd/nsgkfx9s75xb84909646j0zm0000gn/T/messenger-track1-58qai1az/overlay.json",
|
||||
"./cmd/messenger"
|
||||
],
|
||||
"go_version": "go version go1.27.1 darwin/arm64",
|
||||
"os_arch": [
|
||||
"darwin",
|
||||
"arm64"
|
||||
],
|
||||
"requests_per_case": 100000,
|
||||
"rss_source": "ps RSS of go run child executable, KiB; sampled every 100 ms",
|
||||
"rows": [
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.634,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7334.409,
|
||||
"p50_ms": 0.13,
|
||||
"p95_ms": 0.146,
|
||||
"p99_ms": 0.186,
|
||||
"rss_min_kib": 23616,
|
||||
"rss_max_kib": 59968,
|
||||
"rss_delta_kib": 36352
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.333,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 8823.924,
|
||||
"p50_ms": 0.42,
|
||||
"p95_ms": 0.654,
|
||||
"p99_ms": 0.869,
|
||||
"rss_min_kib": 23424,
|
||||
"rss_max_kib": 58464,
|
||||
"rss_delta_kib": 35040
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.63,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7336.995,
|
||||
"p50_ms": 2.021,
|
||||
"p95_ms": 3.514,
|
||||
"p99_ms": 4.631,
|
||||
"rss_min_kib": 23520,
|
||||
"rss_max_kib": 66544,
|
||||
"rss_delta_kib": 43024
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.538,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7386.656,
|
||||
"p50_ms": 4.022,
|
||||
"p95_ms": 7.026,
|
||||
"p99_ms": 8.953,
|
||||
"rss_min_kib": 23856,
|
||||
"rss_max_kib": 65616,
|
||||
"rss_delta_kib": 41760
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 14.008,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7138.887,
|
||||
"p50_ms": 0.13,
|
||||
"p95_ms": 0.149,
|
||||
"p99_ms": 0.21,
|
||||
"rss_min_kib": 25984,
|
||||
"rss_max_kib": 70416,
|
||||
"rss_delta_kib": 44432
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.057,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 9043.732,
|
||||
"p50_ms": 0.406,
|
||||
"p95_ms": 0.626,
|
||||
"p99_ms": 0.841,
|
||||
"rss_min_kib": 26272,
|
||||
"rss_max_kib": 67376,
|
||||
"rss_delta_kib": 41104
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.436,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7442.895,
|
||||
"p50_ms": 1.977,
|
||||
"p95_ms": 3.485,
|
||||
"p99_ms": 4.703,
|
||||
"rss_min_kib": 26576,
|
||||
"rss_max_kib": 75616,
|
||||
"rss_delta_kib": 49040
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.546,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7382.485,
|
||||
"p50_ms": 4.01,
|
||||
"p95_ms": 7.051,
|
||||
"p99_ms": 9.096,
|
||||
"rss_min_kib": 25456,
|
||||
"rss_max_kib": 77792,
|
||||
"rss_delta_kib": 52336
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.969,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7158.653,
|
||||
"p50_ms": 0.13,
|
||||
"p95_ms": 0.149,
|
||||
"p99_ms": 0.211,
|
||||
"rss_min_kib": 40080,
|
||||
"rss_max_kib": 81072,
|
||||
"rss_delta_kib": 40992
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.014,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 9079.212,
|
||||
"p50_ms": 0.404,
|
||||
"p95_ms": 0.623,
|
||||
"p99_ms": 0.823,
|
||||
"rss_min_kib": 40448,
|
||||
"rss_max_kib": 77088,
|
||||
"rss_delta_kib": 36640
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.479,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7419.068,
|
||||
"p50_ms": 1.99,
|
||||
"p95_ms": 3.471,
|
||||
"p99_ms": 4.694,
|
||||
"rss_min_kib": 42336,
|
||||
"rss_max_kib": 79552,
|
||||
"rss_delta_kib": 37216
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.464,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7427.333,
|
||||
"p50_ms": 3.99,
|
||||
"p95_ms": 7.049,
|
||||
"p99_ms": 9.007,
|
||||
"rss_min_kib": 40336,
|
||||
"rss_max_kib": 89552,
|
||||
"rss_delta_kib": 49216
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
[
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.634,
|
||||
"duration_seconds_after": 13.919,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7334.409,
|
||||
"rps_after": 7184.594,
|
||||
"p50_ms_before": 0.13,
|
||||
"p50_ms_after": 0.129,
|
||||
"p95_ms_before": 0.146,
|
||||
"p95_ms_after": 0.15,
|
||||
"p99_ms_before": 0.186,
|
||||
"p99_ms_after": 0.231,
|
||||
"rss_max_kib_before": 59968,
|
||||
"rss_max_kib_after": 62048
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 11.333,
|
||||
"duration_seconds_after": 11.115,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 8823.924,
|
||||
"rps_after": 8996.523,
|
||||
"p50_ms_before": 0.42,
|
||||
"p50_ms_after": 0.407,
|
||||
"p95_ms_before": 0.654,
|
||||
"p95_ms_after": 0.632,
|
||||
"p99_ms_before": 0.869,
|
||||
"p99_ms_after": 0.867,
|
||||
"rss_max_kib_before": 58464,
|
||||
"rss_max_kib_after": 61040
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.63,
|
||||
"duration_seconds_after": 13.364,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7336.995,
|
||||
"rps_after": 7482.719,
|
||||
"p50_ms_before": 2.021,
|
||||
"p50_ms_after": 1.977,
|
||||
"p95_ms_before": 3.514,
|
||||
"p95_ms_after": 3.445,
|
||||
"p99_ms_before": 4.631,
|
||||
"p99_ms_after": 4.577,
|
||||
"rss_max_kib_before": 66544,
|
||||
"rss_max_kib_after": 61328
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 32,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.538,
|
||||
"duration_seconds_after": 13.547,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7386.656,
|
||||
"rps_after": 7381.5,
|
||||
"p50_ms_before": 4.022,
|
||||
"p50_ms_after": 4.016,
|
||||
"p95_ms_before": 7.026,
|
||||
"p95_ms_after": 7.058,
|
||||
"p99_ms_before": 8.953,
|
||||
"p99_ms_after": 9.054,
|
||||
"rss_max_kib_before": 65616,
|
||||
"rss_max_kib_after": 68768
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 1,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 14.008,
|
||||
"duration_seconds_after": 13.984,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7138.887,
|
||||
"rps_after": 7150.931,
|
||||
"p50_ms_before": 0.13,
|
||||
"p50_ms_after": 0.131,
|
||||
"p95_ms_before": 0.149,
|
||||
"p95_ms_after": 0.146,
|
||||
"p99_ms_before": 0.21,
|
||||
"p99_ms_after": 0.187,
|
||||
"rss_max_kib_before": 70416,
|
||||
"rss_max_kib_after": 68128
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 4,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 11.057,
|
||||
"duration_seconds_after": 11.046,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 9043.732,
|
||||
"rps_after": 9052.965,
|
||||
"p50_ms_before": 0.406,
|
||||
"p50_ms_after": 0.404,
|
||||
"p95_ms_before": 0.626,
|
||||
"p95_ms_after": 0.628,
|
||||
"p99_ms_before": 0.841,
|
||||
"p99_ms_after": 0.859,
|
||||
"rss_max_kib_before": 67376,
|
||||
"rss_max_kib_after": 71632
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 16,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.436,
|
||||
"duration_seconds_after": 13.439,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7442.895,
|
||||
"rps_after": 7440.817,
|
||||
"p50_ms_before": 1.977,
|
||||
"p50_ms_after": 1.989,
|
||||
"p95_ms_before": 3.485,
|
||||
"p95_ms_after": 3.468,
|
||||
"p99_ms_before": 4.703,
|
||||
"p99_ms_after": 4.701,
|
||||
"rss_max_kib_before": 75616,
|
||||
"rss_max_kib_after": 73712
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 32,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.546,
|
||||
"duration_seconds_after": 13.478,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7382.485,
|
||||
"rps_after": 7419.326,
|
||||
"p50_ms_before": 4.01,
|
||||
"p50_ms_after": 3.984,
|
||||
"p95_ms_before": 7.051,
|
||||
"p95_ms_after": 7.049,
|
||||
"p99_ms_before": 9.096,
|
||||
"p99_ms_after": 9.096,
|
||||
"rss_max_kib_before": 77792,
|
||||
"rss_max_kib_after": 70976
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 1,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.969,
|
||||
"duration_seconds_after": 13.863,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7158.653,
|
||||
"rps_after": 7213.61,
|
||||
"p50_ms_before": 0.13,
|
||||
"p50_ms_after": 0.129,
|
||||
"p95_ms_before": 0.149,
|
||||
"p95_ms_after": 0.145,
|
||||
"p99_ms_before": 0.211,
|
||||
"p99_ms_after": 0.191,
|
||||
"rss_max_kib_before": 81072,
|
||||
"rss_max_kib_after": 81824
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 4,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 11.014,
|
||||
"duration_seconds_after": 11.066,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 9079.212,
|
||||
"rps_after": 9036.335,
|
||||
"p50_ms_before": 0.404,
|
||||
"p50_ms_after": 0.405,
|
||||
"p95_ms_before": 0.623,
|
||||
"p95_ms_after": 0.63,
|
||||
"p99_ms_before": 0.823,
|
||||
"p99_ms_after": 0.842,
|
||||
"rss_max_kib_before": 77088,
|
||||
"rss_max_kib_after": 86832
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 16,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.479,
|
||||
"duration_seconds_after": 13.416,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7419.068,
|
||||
"rps_after": 7453.53,
|
||||
"p50_ms_before": 1.99,
|
||||
"p50_ms_after": 1.978,
|
||||
"p95_ms_before": 3.471,
|
||||
"p95_ms_after": 3.455,
|
||||
"p99_ms_before": 4.694,
|
||||
"p99_ms_after": 4.688,
|
||||
"rss_max_kib_before": 79552,
|
||||
"rss_max_kib_after": 89824
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 32,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"duration_seconds_before": 13.464,
|
||||
"duration_seconds_after": 13.542,
|
||||
"successful_requests_before": 100000,
|
||||
"successful_requests_after": 100000,
|
||||
"failed_requests_before": 0,
|
||||
"failed_requests_after": 0,
|
||||
"rps_before": 7427.333,
|
||||
"rps_after": 7384.536,
|
||||
"p50_ms_before": 3.99,
|
||||
"p50_ms_after": 4.005,
|
||||
"p95_ms_before": 7.049,
|
||||
"p95_ms_after": 7.084,
|
||||
"p99_ms_before": 9.007,
|
||||
"p99_ms_after": 9.203,
|
||||
"rss_max_kib_before": 89552,
|
||||
"rss_max_kib_after": 80128
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,209 @@
|
||||
{
|
||||
"mode": "optimized",
|
||||
"command": [
|
||||
"go",
|
||||
"run",
|
||||
"./cmd/messenger"
|
||||
],
|
||||
"go_version": "go version go1.27.1 darwin/arm64",
|
||||
"os_arch": [
|
||||
"darwin",
|
||||
"arm64"
|
||||
],
|
||||
"requests_per_case": 100000,
|
||||
"rss_source": "ps RSS of go run child executable, KiB; sampled every 100 ms",
|
||||
"rows": [
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.919,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7184.594,
|
||||
"p50_ms": 0.129,
|
||||
"p95_ms": 0.15,
|
||||
"p99_ms": 0.231,
|
||||
"rss_min_kib": 23504,
|
||||
"rss_max_kib": 62048,
|
||||
"rss_delta_kib": 38544
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.115,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 8996.523,
|
||||
"p50_ms": 0.407,
|
||||
"p95_ms": 0.632,
|
||||
"p99_ms": 0.867,
|
||||
"rss_min_kib": 23744,
|
||||
"rss_max_kib": 61040,
|
||||
"rss_delta_kib": 37296
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.364,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7482.719,
|
||||
"p50_ms": 1.977,
|
||||
"p95_ms": 3.445,
|
||||
"p99_ms": 4.577,
|
||||
"rss_min_kib": 22480,
|
||||
"rss_max_kib": 61328,
|
||||
"rss_delta_kib": 38848
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.547,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7381.5,
|
||||
"p50_ms": 4.016,
|
||||
"p95_ms": 7.058,
|
||||
"p99_ms": 9.054,
|
||||
"rss_min_kib": 23152,
|
||||
"rss_max_kib": 68768,
|
||||
"rss_delta_kib": 45616
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.984,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7150.931,
|
||||
"p50_ms": 0.131,
|
||||
"p95_ms": 0.146,
|
||||
"p99_ms": 0.187,
|
||||
"rss_min_kib": 25936,
|
||||
"rss_max_kib": 68128,
|
||||
"rss_delta_kib": 42192
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.046,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 9052.965,
|
||||
"p50_ms": 0.404,
|
||||
"p95_ms": 0.628,
|
||||
"p99_ms": 0.859,
|
||||
"rss_min_kib": 26448,
|
||||
"rss_max_kib": 71632,
|
||||
"rss_delta_kib": 45184
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.439,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7440.817,
|
||||
"p50_ms": 1.989,
|
||||
"p95_ms": 3.468,
|
||||
"p99_ms": 4.701,
|
||||
"rss_min_kib": 26480,
|
||||
"rss_max_kib": 73712,
|
||||
"rss_delta_kib": 47232
|
||||
},
|
||||
{
|
||||
"history": 10000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.478,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7419.326,
|
||||
"p50_ms": 3.984,
|
||||
"p95_ms": 7.049,
|
||||
"p99_ms": 9.096,
|
||||
"rss_min_kib": 26176,
|
||||
"rss_max_kib": 70976,
|
||||
"rss_delta_kib": 44800
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 13.863,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7213.61,
|
||||
"p50_ms": 0.129,
|
||||
"p95_ms": 0.145,
|
||||
"p99_ms": 0.191,
|
||||
"rss_min_kib": 40592,
|
||||
"rss_max_kib": 81824,
|
||||
"rss_delta_kib": 41232
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 11.066,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 9036.335,
|
||||
"p50_ms": 0.405,
|
||||
"p95_ms": 0.63,
|
||||
"p99_ms": 0.842,
|
||||
"rss_min_kib": 42944,
|
||||
"rss_max_kib": 86832,
|
||||
"rss_delta_kib": 43888
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 13.416,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7453.53,
|
||||
"p50_ms": 1.978,
|
||||
"p95_ms": 3.455,
|
||||
"p99_ms": 4.688,
|
||||
"rss_min_kib": 40768,
|
||||
"rss_max_kib": 89824,
|
||||
"rss_delta_kib": 49056
|
||||
},
|
||||
{
|
||||
"history": 50000,
|
||||
"concurrency": 32,
|
||||
"duration_seconds": 13.542,
|
||||
"requested_requests": 100000,
|
||||
"warmup_requests": 100,
|
||||
"successful_requests": 100000,
|
||||
"failed_requests": 0,
|
||||
"rps": 7384.536,
|
||||
"p50_ms": 4.005,
|
||||
"p95_ms": 7.084,
|
||||
"p99_ms": 9.203,
|
||||
"rss_min_kib": 42848,
|
||||
"rss_max_kib": 80128,
|
||||
"rss_delta_kib": 37280
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
goos: darwin
|
||||
goarch: arm64
|
||||
pkg: mtusi-messenger/internal/storage/memory
|
||||
cpu: Apple M5 Pro
|
||||
BenchmarkMessageCreate/history=1000-18 4830075 243.3 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 4958697 241.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 4984602 241.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 4976372 241.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=1000-18 4962843 241.7 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4967149 241.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4946976 242.1 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4950400 242.3 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4938321 242.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=10000-18 4955269 242.2 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4943572 242.0 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4969927 242.4 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4931466 242.5 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4948990 242.8 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkMessageCreate/history=50000-18 4953249 242.6 ns/op 16 B/op 1 allocs/op
|
||||
PASS
|
||||
ok mtusi-messenger/internal/storage/memory 18.240s
|
||||
@@ -0,0 +1,128 @@
|
||||
[
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 531,
|
||||
"failed_requests": 0,
|
||||
"rps": 265.189,
|
||||
"p50_ms": 3.355,
|
||||
"p95_ms": 4.276,
|
||||
"p99_ms": 17.123,
|
||||
"rss_min_kib": 18800,
|
||||
"rss_max_kib": 22736,
|
||||
"rss_delta_kib": 3936
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.005,
|
||||
"successful_requests": 1445,
|
||||
"failed_requests": 0,
|
||||
"rps": 720.55,
|
||||
"p50_ms": 4.197,
|
||||
"p95_ms": 16.868,
|
||||
"p99_ms": 21.043,
|
||||
"rss_min_kib": 20768,
|
||||
"rss_max_kib": 24128,
|
||||
"rss_delta_kib": 3360
|
||||
},
|
||||
{
|
||||
"history": 100,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.012,
|
||||
"successful_requests": 2265,
|
||||
"failed_requests": 0,
|
||||
"rps": 1125.923,
|
||||
"p50_ms": 8.851,
|
||||
"p95_ms": 29.142,
|
||||
"p99_ms": 91.221,
|
||||
"rss_min_kib": 20672,
|
||||
"rss_max_kib": 25216,
|
||||
"rss_delta_kib": 4544
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.011,
|
||||
"successful_requests": 478,
|
||||
"failed_requests": 0,
|
||||
"rps": 237.68,
|
||||
"p50_ms": 3.467,
|
||||
"p95_ms": 11.279,
|
||||
"p99_ms": 19.675,
|
||||
"rss_min_kib": 23264,
|
||||
"rss_max_kib": 23504,
|
||||
"rss_delta_kib": 240
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.004,
|
||||
"successful_requests": 1337,
|
||||
"failed_requests": 0,
|
||||
"rps": 667.05,
|
||||
"p50_ms": 4.249,
|
||||
"p95_ms": 17.243,
|
||||
"p99_ms": 29.938,
|
||||
"rss_min_kib": 23264,
|
||||
"rss_max_kib": 25280,
|
||||
"rss_delta_kib": 2016
|
||||
},
|
||||
{
|
||||
"history": 1000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.005,
|
||||
"successful_requests": 2211,
|
||||
"failed_requests": 0,
|
||||
"rps": 1102.581,
|
||||
"p50_ms": 8.818,
|
||||
"p95_ms": 30.252,
|
||||
"p99_ms": 93.912,
|
||||
"rss_min_kib": 23424,
|
||||
"rss_max_kib": 25200,
|
||||
"rss_delta_kib": 1776
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 1,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 483,
|
||||
"failed_requests": 0,
|
||||
"rps": 241.241,
|
||||
"p50_ms": 3.466,
|
||||
"p95_ms": 10.897,
|
||||
"p99_ms": 18.681,
|
||||
"rss_min_kib": 25456,
|
||||
"rss_max_kib": 25456,
|
||||
"rss_delta_kib": 0
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 4,
|
||||
"duration_seconds": 2.003,
|
||||
"successful_requests": 1374,
|
||||
"failed_requests": 0,
|
||||
"rps": 685.839,
|
||||
"p50_ms": 4.207,
|
||||
"p95_ms": 17.418,
|
||||
"p99_ms": 26.618,
|
||||
"rss_min_kib": 24304,
|
||||
"rss_max_kib": 25376,
|
||||
"rss_delta_kib": 1072
|
||||
},
|
||||
{
|
||||
"history": 5000,
|
||||
"concurrency": 16,
|
||||
"duration_seconds": 2.002,
|
||||
"successful_requests": 2162,
|
||||
"failed_requests": 0,
|
||||
"rps": 1079.866,
|
||||
"p50_ms": 8.939,
|
||||
"p95_ms": 31.525,
|
||||
"p99_ms": 94.709,
|
||||
"rss_min_kib": 24848,
|
||||
"rss_max_kib": 26640,
|
||||
"rss_delta_kib": 1792
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,82 @@
|
||||
module mtusi-messenger
|
||||
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
github.com/go-faster/errors v0.8.0
|
||||
github.com/go-faster/jx v1.2.0
|
||||
github.com/go-playground/validator/v10 v10.30.5
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/ogen-go/ogen v1.24.0
|
||||
github.com/spf13/viper v1.21.0
|
||||
github.com/stretchr/testify v1.12.1
|
||||
go.uber.org/zap v1.28.0
|
||||
go.uber.org/zap/exp v0.3.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/brunoga/deep v1.3.1 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.2.0 // indirect
|
||||
github.com/dlclark/regexp2 v1.12.0 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/fatih/structs v1.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/ghodss/yaml v1.0.0 // indirect
|
||||
github.com/go-faster/yaml v0.4.6 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/huandu/xstrings v1.5.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8 // indirect
|
||||
github.com/knadh/koanf/maps v0.1.2 // indirect
|
||||
github.com/knadh/koanf/parsers/yaml v1.1.0 // indirect
|
||||
github.com/knadh/koanf/providers/env v1.1.0 // indirect
|
||||
github.com/knadh/koanf/providers/file v1.2.1 // indirect
|
||||
github.com/knadh/koanf/providers/posflag v1.0.1 // indirect
|
||||
github.com/knadh/koanf/providers/structs v1.0.0 // indirect
|
||||
github.com/knadh/koanf/v2 v2.3.2 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.19 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/rs/zerolog v1.34.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/shopspring/decimal v1.4.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/cobra v1.10.2 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/stretchr/objx v0.5.3 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/vektra/mockery/v3 v3.8.0 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||
github.com/yuin/goldmark v1.8.2 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a // indirect
|
||||
golang.org/x/mod v0.41.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/term v0.46.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
golang.org/x/tools v0.49.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
tool (
|
||||
github.com/ogen-go/ogen/cmd/ogen
|
||||
github.com/vektra/mockery/v3
|
||||
)
|
||||
@@ -0,0 +1,172 @@
|
||||
github.com/brunoga/deep v1.3.1 h1:bSrL6FhAZa6JlVv4vsi7Hg8SLwroDb1kgDERRVipBCo=
|
||||
github.com/brunoga/deep v1.3.1/go.mod h1:GDV6dnXqn80ezsLSZ5Wlv1PdKAWAO4L5PnKYtv2dgaI=
|
||||
github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY=
|
||||
github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
|
||||
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
|
||||
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
|
||||
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
|
||||
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
|
||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
github.com/go-faster/errors v0.8.0 h1:9T9eJrM+72dFk7n4DfhuaDDe6cyuFCSW2oNUkN77Yqc=
|
||||
github.com/go-faster/errors v0.8.0/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo=
|
||||
github.com/go-faster/jx v1.2.0 h1:T2YHJPrFaYu21fJtUxC9GzmluKu8rVIFDwwGBKTDseI=
|
||||
github.com/go-faster/jx v1.2.0/go.mod h1:UWLOVDmMG597a5tBFPLIWJdUxz5/2emOpfsj9Neg0PE=
|
||||
github.com/go-faster/yaml v0.4.6 h1:lOK/EhI04gCpPgPhgt0bChS6bvw7G3WwI8xxVe0sw9I=
|
||||
github.com/go-faster/yaml v0.4.6/go.mod h1:390dRIvV4zbnO7qC9FGo6YYutc+wyyUSHBgbXL52eXk=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4=
|
||||
github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
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/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
|
||||
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8 h1:BVYrDy5DPBA3Qn9ICT+PokP9cvCv1KaHv2i+Hc8sr5o=
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||
github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=
|
||||
github.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
|
||||
github.com/knadh/koanf/parsers/yaml v1.1.0 h1:3ltfm9ljprAHt4jxgeYLlFPmUaunuCgu1yILuTXRdM4=
|
||||
github.com/knadh/koanf/parsers/yaml v1.1.0/go.mod h1:HHmcHXUrp9cOPcuC+2wrr44GTUB0EC+PyfN3HZD9tFg=
|
||||
github.com/knadh/koanf/providers/env v1.1.0 h1:U2VXPY0f+CsNDkvdsG8GcsnK4ah85WwWyJgef9oQMSc=
|
||||
github.com/knadh/koanf/providers/env v1.1.0/go.mod h1:QhHHHZ87h9JxJAn2czdEl6pdkNnDh/JS1Vtsyt65hTY=
|
||||
github.com/knadh/koanf/providers/file v1.2.1 h1:bEWbtQwYrA+W2DtdBrQWyXqJaJSG3KrP3AESOJYp9wM=
|
||||
github.com/knadh/koanf/providers/file v1.2.1/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA=
|
||||
github.com/knadh/koanf/providers/posflag v1.0.1 h1:EnMxHSrPkYCFnKgBUl5KBgrjed8gVFrcXDzaW4l/C6Y=
|
||||
github.com/knadh/koanf/providers/posflag v1.0.1/go.mod h1:3Wn3+YG3f4ljzRyCUgIwH7G0sZ1pMjCOsNBovrbKmAk=
|
||||
github.com/knadh/koanf/providers/structs v1.0.0 h1:DznjB7NQykhqCar2LvNug3MuxEQsZ5KvfgMbio+23u4=
|
||||
github.com/knadh/koanf/providers/structs v1.0.0/go.mod h1:kjo5TFtgpaZORlpoJqcbeLowM2cINodv8kX+oFAeQ1w=
|
||||
github.com/knadh/koanf/v2 v2.3.2 h1:Ee6tuzQYFwcZXQpc2MiVeC6qHMandf5SMUJJNoFp/c4=
|
||||
github.com/knadh/koanf/v2 v2.3.2/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=
|
||||
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/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
|
||||
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
||||
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/ogen-go/ogen v1.24.0 h1:NehBG/8s0JeM6jYHPJeFJntBG3cE/xQgZd1q8BchPNM=
|
||||
github.com/ogen-go/ogen v1.24.0/go.mod h1:hcg4aTzLcu/MS1SGGahUriPBEOZB3c82RGIC6dYcdFU=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
||||
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
||||
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
|
||||
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
|
||||
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/vektra/mockery/v3 v3.8.0 h1:Tklqcx844iV8GtYziqJXam1a8RdcKip4UErMa66Nxps=
|
||||
github.com/vektra/mockery/v3 v3.8.0/go.mod h1:K+L72OoFVizA9eWtO4L+kU65oylgreiJEJ57Gu8g9Ew=
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
|
||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||
github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE=
|
||||
github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
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.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||
go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=
|
||||
go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a h1:ovFr6Z0MNmU7nH8VaX5xqw+05ST2uO1exVfZPVqRC5o=
|
||||
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
|
||||
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
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.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
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.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
const envPrefix = "APP"
|
||||
|
||||
type Config struct {
|
||||
Host string `mapstructure:"host" validate:"required,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"required,min=1,max=65535"`
|
||||
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" validate:"required,gt=0"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
|
||||
LogLevel string `mapstructure:"log_level" validate:"required,oneof=debug info warn error"`
|
||||
LogFormat string `mapstructure:"log_format" validate:"required,oneof=json console"`
|
||||
}
|
||||
|
||||
var defaults = map[string]any{
|
||||
"host": "0.0.0.0",
|
||||
"port": 8080,
|
||||
"read_header_timeout": "10s",
|
||||
"shutdown_timeout": "10s",
|
||||
"log_level": "info",
|
||||
"log_format": "json",
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
v := viper.New()
|
||||
|
||||
v.SetEnvPrefix(envPrefix)
|
||||
v.AllowEmptyEnv(true)
|
||||
v.AutomaticEnv()
|
||||
|
||||
for key, value := range defaults {
|
||||
v.SetDefault(key, value)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("unmarshal config: %w", err)
|
||||
}
|
||||
|
||||
if err := validate.Struct(cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("validate config: %w", err)
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string {
|
||||
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
|
||||
}
|
||||
|
||||
func (c Config) SlogLevel() slog.Level {
|
||||
level, _ := logger.ParseLevel(c.LogLevel)
|
||||
|
||||
return level
|
||||
}
|
||||
|
||||
func (c Config) LoggerFormat() logger.Format {
|
||||
format, _ := logger.ParseFormat(c.LogFormat)
|
||||
|
||||
return format
|
||||
}
|
||||
|
||||
var validate = newValidator()
|
||||
|
||||
func newValidator() *validator.Validate {
|
||||
v := validator.New(validator.WithRequiredStructEnabled())
|
||||
v.RegisterTagNameFunc(envName)
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
func envName(field reflect.StructField) string {
|
||||
key := field.Tag.Get("mapstructure")
|
||||
if key == "" {
|
||||
return field.Name
|
||||
}
|
||||
|
||||
return envPrefix + "_" + strings.ToUpper(key)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
type ConfigSuite struct {
|
||||
suite.Suite
|
||||
}
|
||||
|
||||
func TestConfigSuite(t *testing.T) {
|
||||
suite.Run(t, new(ConfigSuite))
|
||||
}
|
||||
|
||||
func (s *ConfigSuite) TestDefaults() {
|
||||
cfg, err := config.Load()
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal("0.0.0.0", cfg.Host)
|
||||
s.Equal(8080, cfg.Port)
|
||||
s.Equal(10*time.Second, cfg.ReadHeaderTimeout)
|
||||
s.Equal(10*time.Second, cfg.ShutdownTimeout)
|
||||
s.Equal("info", cfg.LogLevel)
|
||||
s.Equal("json", cfg.LogFormat)
|
||||
}
|
||||
|
||||
func (s *ConfigSuite) TestEnvOverridesDefaults() {
|
||||
s.T().Setenv("APP_HOST", "127.0.0.1")
|
||||
s.T().Setenv("APP_PORT", "9090")
|
||||
s.T().Setenv("APP_READ_HEADER_TIMEOUT", "3s")
|
||||
s.T().Setenv("APP_SHUTDOWN_TIMEOUT", "30s")
|
||||
s.T().Setenv("APP_LOG_LEVEL", "debug")
|
||||
s.T().Setenv("APP_LOG_FORMAT", "console")
|
||||
|
||||
cfg, err := config.Load()
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal("127.0.0.1", cfg.Host)
|
||||
s.Equal(9090, cfg.Port)
|
||||
s.Equal(3*time.Second, cfg.ReadHeaderTimeout)
|
||||
s.Equal(30*time.Second, cfg.ShutdownTimeout)
|
||||
s.Equal("debug", cfg.LogLevel)
|
||||
s.Equal("console", cfg.LogFormat)
|
||||
}
|
||||
|
||||
func (s *ConfigSuite) TestLoggerSettings() {
|
||||
s.T().Setenv("APP_LOG_LEVEL", "warn")
|
||||
s.T().Setenv("APP_LOG_FORMAT", "console")
|
||||
|
||||
cfg, err := config.Load()
|
||||
s.Require().NoError(err)
|
||||
|
||||
level, err := logger.ParseLevel(cfg.LogLevel)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(level, cfg.SlogLevel())
|
||||
|
||||
format, err := logger.ParseFormat(cfg.LogFormat)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(format, cfg.LoggerFormat())
|
||||
}
|
||||
|
||||
func (s *ConfigSuite) TestAddr() {
|
||||
s.T().Setenv("APP_HOST", "0.0.0.0")
|
||||
s.T().Setenv("APP_PORT", "8080")
|
||||
|
||||
cfg, err := config.Load()
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal("0.0.0.0:8080", cfg.Addr())
|
||||
}
|
||||
|
||||
func (s *ConfigSuite) TestAddrWithIPv6Host() {
|
||||
s.T().Setenv("APP_HOST", "::1")
|
||||
|
||||
cfg, err := config.Load()
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal("[::1]:8080", cfg.Addr())
|
||||
}
|
||||
|
||||
func (s *ConfigSuite) TestInvalidValues() {
|
||||
tests := map[string]struct {
|
||||
env map[string]string
|
||||
wantField string
|
||||
wantTag string
|
||||
}{
|
||||
"пустой host": {
|
||||
env: map[string]string{"APP_HOST": ""},
|
||||
wantField: "APP_HOST",
|
||||
wantTag: "required",
|
||||
},
|
||||
"host не адрес и не имя": {
|
||||
env: map[string]string{"APP_HOST": "не адрес"},
|
||||
wantField: "APP_HOST",
|
||||
wantTag: "hostname|ip",
|
||||
},
|
||||
"порт ниже диапазона": {
|
||||
env: map[string]string{"APP_PORT": "0"},
|
||||
wantField: "APP_PORT",
|
||||
wantTag: "required",
|
||||
},
|
||||
"порт выше диапазона": {
|
||||
env: map[string]string{"APP_PORT": "65536"},
|
||||
wantField: "APP_PORT",
|
||||
wantTag: "max",
|
||||
},
|
||||
"нулевой read header timeout": {
|
||||
env: map[string]string{"APP_READ_HEADER_TIMEOUT": "0s"},
|
||||
wantField: "APP_READ_HEADER_TIMEOUT",
|
||||
wantTag: "required",
|
||||
},
|
||||
"отрицательный shutdown timeout": {
|
||||
env: map[string]string{"APP_SHUTDOWN_TIMEOUT": "-1s"},
|
||||
wantField: "APP_SHUTDOWN_TIMEOUT",
|
||||
wantTag: "gt",
|
||||
},
|
||||
"неизвестный уровень логирования": {
|
||||
env: map[string]string{"APP_LOG_LEVEL": "trace"},
|
||||
wantField: "APP_LOG_LEVEL",
|
||||
wantTag: "oneof",
|
||||
},
|
||||
"неизвестный формат логирования": {
|
||||
env: map[string]string{"APP_LOG_FORMAT": "xml"},
|
||||
wantField: "APP_LOG_FORMAT",
|
||||
wantTag: "oneof",
|
||||
},
|
||||
}
|
||||
|
||||
for name, tt := range tests {
|
||||
s.Run(name, func() {
|
||||
for key, value := range tt.env {
|
||||
s.T().Setenv(key, value)
|
||||
}
|
||||
|
||||
_, err := config.Load()
|
||||
s.Require().Error(err)
|
||||
|
||||
var validationErrs validator.ValidationErrors
|
||||
s.Require().ErrorAs(err, &validationErrs)
|
||||
s.Require().Len(validationErrs, 1)
|
||||
|
||||
s.Equal(tt.wantField, validationErrs[0].Field())
|
||||
s.Equal(tt.wantTag, validationErrs[0].Tag())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ConfigSuite) TestUnparsableValues() {
|
||||
tests := map[string]map[string]string{
|
||||
"порт не число": {"APP_PORT": "не-число"},
|
||||
"timeout не длительность": {"APP_READ_HEADER_TIMEOUT": "быстро"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
s.Run(name, func() {
|
||||
for key, value := range env {
|
||||
s.T().Setenv(key, value)
|
||||
}
|
||||
|
||||
_, err := config.Load()
|
||||
s.Require().Error(err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadIsIndependentOfProcessState(t *testing.T) {
|
||||
t.Setenv("APP_PORT", "7070")
|
||||
|
||||
first, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
second, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, first, second)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (c Chat) HasMember(userID uuid.UUID) bool {
|
||||
return slices.Contains(c.MemberIDs, userID)
|
||||
}
|
||||
|
||||
type ChatDraft struct {
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CallerID uuid.UUID
|
||||
}
|
||||
|
||||
func (d ChatDraft) Validate() error {
|
||||
if err := validateNotBlank("title", d.Title); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !slices.Contains(d.MemberIDs, d.CallerID) {
|
||||
return fmt.Errorf("member_ids must contain the caller: %w", ErrValidation)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Cursor struct {
|
||||
Scope uuid.UUID
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (c Cursor) BelongsTo(scope uuid.UUID) bool {
|
||||
return c.Scope == scope
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package domain
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUsernameTaken = errors.New("username already taken")
|
||||
ErrUnknownMember = errors.New("member does not exist")
|
||||
ErrValidation = errors.New("validation failed")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type MessageDraft struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
func (d MessageDraft) Validate() error {
|
||||
return validateNotBlank("text", d.Text)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package domain
|
||||
|
||||
const DefaultPageLimit = 50
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
Next *Cursor
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func validateNotBlank(field, value string) error {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return fmt.Errorf("%s consists of whitespace only: %w", field, ErrValidation)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UserDraft struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
}
|
||||
|
||||
func (d UserDraft) Validate() error {
|
||||
return validateNotBlank("display_name", d.DisplayName)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package domain_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
// Длины, regex и uniqueItems проверяет сгенерированный слой по contracts/openapi.json.
|
||||
// Домен закрывает только то, что схема выразить не может.
|
||||
|
||||
func TestUserDraftRejectsBlankDisplayName(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, blank := range []string{" ", " ", "\t", "\n", "\u00a0"} {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: blank}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserDraftAcceptsVisibleName(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса"}
|
||||
assert.NoError(t, draft.Validate())
|
||||
}
|
||||
|
||||
func TestChatDraftRequiresCallerAmongMembers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
caller := uuid.New()
|
||||
|
||||
outside := domain.ChatDraft{
|
||||
Title: "Проект",
|
||||
MemberIDs: []uuid.UUID{uuid.New(), uuid.New()},
|
||||
CallerID: caller,
|
||||
}
|
||||
require.ErrorIs(t, outside.Validate(), domain.ErrValidation)
|
||||
|
||||
inside := domain.ChatDraft{
|
||||
Title: "Проект",
|
||||
MemberIDs: []uuid.UUID{uuid.New(), caller},
|
||||
CallerID: caller,
|
||||
}
|
||||
assert.NoError(t, inside.Validate())
|
||||
}
|
||||
|
||||
func TestChatDraftRejectsBlankTitle(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
caller := uuid.New()
|
||||
|
||||
draft := domain.ChatDraft{
|
||||
Title: " ",
|
||||
MemberIDs: []uuid.UUID{caller},
|
||||
CallerID: caller,
|
||||
}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
|
||||
}
|
||||
|
||||
func TestMessageDraftRejectsBlankText(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.MessageDraft{
|
||||
ChatID: uuid.New(),
|
||||
SenderID: uuid.New(),
|
||||
Text: strings.Repeat(" ", 10),
|
||||
}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
|
||||
}
|
||||
|
||||
func TestMessageDraftAcceptsTextWithSurroundingSpaces(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.MessageDraft{
|
||||
ChatID: uuid.New(),
|
||||
SenderID: uuid.New(),
|
||||
Text: " привет ",
|
||||
}
|
||||
assert.NoError(t, draft.Validate(), "контракт запрещает только полностью пробельный текст")
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package logger
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrUnknownLevel = errors.New("unknown log level")
|
||||
ErrUnknownFormat = errors.New("unknown log format")
|
||||
)
|
||||
@@ -0,0 +1,138 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"go.uber.org/zap/exp/zapslog"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
type Format string
|
||||
|
||||
const (
|
||||
FormatJSON Format = "json"
|
||||
FormatConsole Format = "console"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultLevel = slog.LevelInfo
|
||||
DefaultFormat = FormatJSON
|
||||
)
|
||||
|
||||
type options struct {
|
||||
writer io.Writer
|
||||
level slog.Level
|
||||
format Format
|
||||
name string
|
||||
}
|
||||
|
||||
type Option func(*options)
|
||||
|
||||
func WithWriter(writer io.Writer) Option {
|
||||
return func(opts *options) {
|
||||
if writer != nil {
|
||||
opts.writer = writer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithLevel(level slog.Level) Option {
|
||||
return func(opts *options) {
|
||||
opts.level = level
|
||||
}
|
||||
}
|
||||
|
||||
func WithFormat(format Format) Option {
|
||||
return func(opts *options) {
|
||||
if format != "" {
|
||||
opts.format = format
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithName(name string) Option {
|
||||
return func(opts *options) {
|
||||
opts.name = name
|
||||
}
|
||||
}
|
||||
|
||||
func New(options ...Option) *slog.Logger {
|
||||
opts := optionsConfig()
|
||||
for _, option := range options {
|
||||
option(&opts)
|
||||
}
|
||||
|
||||
encoderCfg := zapcore.EncoderConfig{
|
||||
TimeKey: "time",
|
||||
LevelKey: "level",
|
||||
NameKey: "logger",
|
||||
CallerKey: "caller",
|
||||
MessageKey: "msg",
|
||||
StacktraceKey: "stacktrace",
|
||||
LineEnding: zapcore.DefaultLineEnding,
|
||||
EncodeLevel: zapcore.LowercaseLevelEncoder,
|
||||
EncodeTime: zapcore.RFC3339NanoTimeEncoder,
|
||||
EncodeDuration: zapcore.StringDurationEncoder,
|
||||
EncodeCaller: zapcore.ShortCallerEncoder,
|
||||
}
|
||||
|
||||
var encoder zapcore.Encoder
|
||||
if opts.format == FormatConsole {
|
||||
encoder = zapcore.NewConsoleEncoder(encoderCfg)
|
||||
} else {
|
||||
encoder = zapcore.NewJSONEncoder(encoderCfg)
|
||||
}
|
||||
|
||||
core := zapcore.NewCore(encoder, zapcore.AddSync(opts.writer), zapLevel(opts.level))
|
||||
handlerOptions := make([]zapslog.HandlerOption, 0, 1)
|
||||
if opts.name != "" {
|
||||
handlerOptions = append(handlerOptions, zapslog.WithName(opts.name))
|
||||
}
|
||||
|
||||
return slog.New(zapslog.NewHandler(core, handlerOptions...))
|
||||
}
|
||||
|
||||
func optionsConfig() options {
|
||||
return options{
|
||||
writer: os.Stdout,
|
||||
level: DefaultLevel,
|
||||
format: DefaultFormat,
|
||||
}
|
||||
}
|
||||
|
||||
func ParseLevel(raw string) (slog.Level, error) {
|
||||
var level slog.Level
|
||||
if err := level.UnmarshalText([]byte(strings.TrimSpace(raw))); err != nil {
|
||||
return 0, fmt.Errorf("%q: %w", raw, ErrUnknownLevel)
|
||||
}
|
||||
|
||||
return level, nil
|
||||
}
|
||||
|
||||
func ParseFormat(raw string) (Format, error) {
|
||||
switch Format(strings.ToLower(strings.TrimSpace(raw))) {
|
||||
case FormatJSON:
|
||||
return FormatJSON, nil
|
||||
case FormatConsole:
|
||||
return FormatConsole, nil
|
||||
default:
|
||||
return "", fmt.Errorf("%q: %w", raw, ErrUnknownFormat)
|
||||
}
|
||||
}
|
||||
|
||||
func zapLevel(level slog.Level) zapcore.Level {
|
||||
switch {
|
||||
case level < slog.LevelInfo:
|
||||
return zapcore.DebugLevel
|
||||
case level < slog.LevelWarn:
|
||||
return zapcore.InfoLevel
|
||||
case level < slog.LevelError:
|
||||
return zapcore.WarnLevel
|
||||
default:
|
||||
return zapcore.ErrorLevel
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package logger_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
type LoggerSuite struct {
|
||||
suite.Suite
|
||||
|
||||
bb *bytes.Buffer
|
||||
}
|
||||
|
||||
func TestLoggerSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(LoggerSuite))
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) SetupTest() {
|
||||
s.bb = &bytes.Buffer{}
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) records() []map[string]any {
|
||||
var out []map[string]any
|
||||
|
||||
for line := range strings.SplitSeq(strings.TrimSpace(s.bb.String()), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var record map[string]any
|
||||
s.Require().NoError(json.Unmarshal([]byte(line), &record))
|
||||
|
||||
out = append(out, record)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestJSONOutputCarriesAttributes() {
|
||||
log := logger.New(logger.WithWriter(s.bb))
|
||||
|
||||
log.Info("сервер запущен", slog.String("addr", "0.0.0.0:8080"))
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
|
||||
s.Equal("info", records[0]["level"])
|
||||
s.Equal("сервер запущен", records[0]["msg"])
|
||||
s.Equal("0.0.0.0:8080", records[0]["addr"])
|
||||
s.Contains(records[0], "time")
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestDefaultLevelDropsDebug() {
|
||||
log := logger.New(logger.WithWriter(s.bb))
|
||||
|
||||
log.Debug("не должно попасть в вывод")
|
||||
log.Info("должно попасть")
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
s.Equal("должно попасть", records[0]["msg"])
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestWithLevelEnablesDebug() {
|
||||
log := logger.New(logger.WithWriter(s.bb), logger.WithLevel(slog.LevelDebug))
|
||||
|
||||
log.Debug("подробность")
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
s.Equal("debug", records[0]["level"])
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestGroupsAreNested() {
|
||||
log := logger.New(logger.WithWriter(s.bb))
|
||||
|
||||
log.Info("запрос", slog.Group("payload", slog.Int("size", 12)))
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
|
||||
payload, ok := records[0]["payload"].(map[string]any)
|
||||
s.Require().True(ok, "группа должна кодироваться вложенным объектом")
|
||||
s.InDelta(12, payload["size"], 0)
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestWithNameSetsLoggerField() {
|
||||
log := logger.New(logger.WithWriter(s.bb), logger.WithName("messenger"))
|
||||
|
||||
log.Info("старт")
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
s.Equal("messenger", records[0]["logger"])
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestConsoleFormatIsNotJSON() {
|
||||
log := logger.New(s.consoleOptions()...)
|
||||
|
||||
log.Info("человекочитаемо")
|
||||
|
||||
line := strings.TrimSpace(s.bb.String())
|
||||
s.Require().NotEmpty(line)
|
||||
|
||||
var record map[string]any
|
||||
s.Require().Error(json.Unmarshal([]byte(line), &record), "console-формат не должен быть JSON")
|
||||
s.Contains(line, "человекочитаемо")
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) consoleOptions() []logger.Option {
|
||||
return []logger.Option{
|
||||
logger.WithWriter(s.bb),
|
||||
logger.WithFormat(logger.FormatConsole),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestNilWriterKeepsDefault() {
|
||||
s.Require().NotPanics(func() {
|
||||
logger.New(logger.WithWriter(nil)).Info("пишем в stdout по умолчанию")
|
||||
})
|
||||
}
|
||||
|
||||
func TestParseLevel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := map[string]struct {
|
||||
want slog.Level
|
||||
wantErr bool
|
||||
}{
|
||||
"debug": {want: slog.LevelDebug},
|
||||
"info": {want: slog.LevelInfo},
|
||||
"WARN": {want: slog.LevelWarn},
|
||||
"error": {want: slog.LevelError},
|
||||
"trace": {wantErr: true},
|
||||
"": {wantErr: true},
|
||||
}
|
||||
|
||||
for raw, tt := range tests {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got, err := logger.ParseLevel(raw)
|
||||
if tt.wantErr {
|
||||
require.ErrorIs(t, err, logger.ErrUnknownLevel)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFormat(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := map[string]struct {
|
||||
want logger.Format
|
||||
wantErr bool
|
||||
}{
|
||||
"json": {want: logger.FormatJSON},
|
||||
"JSON": {want: logger.FormatJSON},
|
||||
"console": {want: logger.FormatConsole},
|
||||
"xml": {wantErr: true},
|
||||
"": {wantErr: true},
|
||||
}
|
||||
|
||||
for raw, tt := range tests {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got, err := logger.ParseFormat(raw)
|
||||
if tt.wantErr {
|
||||
require.ErrorIs(t, err, logger.ErrUnknownFormat)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.ChatDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.ChatDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.ChatDraft)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.ChatDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.ChatDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(chat domain.Chat, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, chatID, callerID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, chatID, callerID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVisible'
|
||||
type MockRepository_GetVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - callerID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) GetVisible(ctx any, chatID any, callerID any) *MockRepository_GetVisible_Call {
|
||||
return &MockRepository_GetVisible_Call{Call: _e.mock.On("GetVisible", ctx, chatID, callerID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID)) *MockRepository_GetVisible_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVisible_Call) Return(chat domain.Chat, err error) *MockRepository_GetVisible_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error)) *MockRepository_GetVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListVisible(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
ret := _mock.Called(ctx, callerID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Chat]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)); ok {
|
||||
return returnFunc(ctx, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Chat]); ok {
|
||||
r0 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Chat])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
|
||||
type MockRepository_ListVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockRepository_Expecter) ListVisible(ctx any, callerID any, after any, limit any) *MockRepository_ListVisible_Call {
|
||||
return &MockRepository_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Run(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 *domain.Cursor
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(*domain.Cursor)
|
||||
}
|
||||
var arg3 int
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Return(page domain.Page[domain.Chat], err error) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
//go:generate go tool mockery
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
chats Repository
|
||||
}
|
||||
|
||||
func NewService(chats Repository) *Service {
|
||||
return &Service{chats: chats}
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
created, err := s.chats.Create(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("create chat: %w", err)
|
||||
}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, callerID, chatID uuid.UUID) (domain.Chat, error) {
|
||||
found, err := s.chats.GetVisible(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func (s *Service) List(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
if after != nil && !after.BelongsTo(callerID) {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("cursor is bound to another list: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
page, err := s.chats.ListVisible(ctx, callerID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/chat"
|
||||
"mtusi-messenger/internal/service/chat/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
chats *mocks.MockRepository
|
||||
service *chat.Service
|
||||
caller uuid.UUID
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.chats = mocks.NewMockRepository(s.T())
|
||||
s.service = chat.NewService(s.chats)
|
||||
s.caller = uuid.New()
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) draft() domain.ChatDraft {
|
||||
return domain.ChatDraft{
|
||||
Title: "Проект по ВНП",
|
||||
MemberIDs: []uuid.UUID{s.caller},
|
||||
CallerID: s.caller,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateReturnsStoredChat() {
|
||||
draft := s.draft()
|
||||
stored := domain.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: draft.Title,
|
||||
MemberIDs: draft.MemberIDs,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.chats.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateRejectsDraftWithoutCallerWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.MemberIDs = []uuid.UUID{uuid.New()}
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateRejectsBlankTitleWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.Title = " "
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreatePropagatesUnknownMember() {
|
||||
draft := s.draft()
|
||||
|
||||
s.chats.EXPECT().Create(s.T().Context(), draft).Return(domain.Chat{}, domain.ErrUnknownMember).Once()
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrUnknownMember,
|
||||
"целостность участников проверяет хранилище, сервис только пробрасывает исход")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetPropagatesNotFoundForForeignChat() {
|
||||
chatID := uuid.New()
|
||||
|
||||
s.chats.EXPECT().GetVisible(s.T().Context(), chatID, s.caller).Return(domain.Chat{}, domain.ErrNotFound).Once()
|
||||
|
||||
_, err := s.service.Get(s.T().Context(), s.caller, chatID)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListPassesNilCursorOnFirstPage() {
|
||||
stored := domain.Chat{ID: uuid.New(), Title: "Проект", MemberIDs: []uuid.UUID{s.caller}, CreatedAt: s.now}
|
||||
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Chat]{Items: []domain.Chat{stored}}, nil).
|
||||
Once()
|
||||
|
||||
page, err := s.service.List(s.T().Context(), s.caller, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]domain.Chat{stored}, page.Items)
|
||||
s.Nil(page.Next, "на последней странице курсора нет")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListRejectsCursorFromAnotherCaller() {
|
||||
foreign := &domain.Cursor{Scope: uuid.New(), CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, foreign, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrInvalidCursor,
|
||||
"курсор чужого списка не должен открывать чужие чаты")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListAcceptsOwnCursor() {
|
||||
own := &domain.Cursor{Scope: s.caller, CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, own, 10).
|
||||
Return(domain.Page[domain.Chat]{}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, own, 10)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListWrapsRepositoryFailure() {
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Chat]{}, errRepository).
|
||||
Once()
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Message
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) (domain.Message, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) domain.Message); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Message)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.MessageDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.MessageDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.MessageDraft)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.MessageDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.MessageDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(message domain.Message, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(message, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error) {
|
||||
ret := _mock.Called(ctx, chatID, callerID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Message]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Message], error)); ok {
|
||||
return returnFunc(ctx, chatID, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Message]); ok {
|
||||
r0 = returnFunc(ctx, chatID, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Message])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
|
||||
type MockRepository_ListVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockRepository_Expecter) ListVisible(ctx any, chatID any, callerID any, after any, limit any) *MockRepository_ListVisible_Call {
|
||||
return &MockRepository_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, chatID, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
var arg3 *domain.Cursor
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(*domain.Cursor)
|
||||
}
|
||||
var arg4 int
|
||||
if args[4] != nil {
|
||||
arg4 = args[4].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
arg4,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Return(page domain.Page[domain.Message], err error) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
//go:generate go tool mockery
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
messages Repository
|
||||
}
|
||||
|
||||
func NewService(messages Repository) *Service {
|
||||
return &Service{messages: messages}
|
||||
}
|
||||
|
||||
func (s *Service) Send(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
sent, err := s.messages.Create(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("create message: %w", err)
|
||||
}
|
||||
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func (s *Service) History(
|
||||
ctx context.Context,
|
||||
callerID, chatID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error) {
|
||||
if after != nil && !after.BelongsTo(chatID) {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("cursor is bound to another chat: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
page, err := s.messages.ListVisible(ctx, chatID, callerID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package message_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/message"
|
||||
"mtusi-messenger/internal/service/message/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
messages *mocks.MockRepository
|
||||
service *message.Service
|
||||
caller uuid.UUID
|
||||
chatID uuid.UUID
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.messages = mocks.NewMockRepository(s.T())
|
||||
s.service = message.NewService(s.messages)
|
||||
s.caller = uuid.New()
|
||||
s.chatID = uuid.New()
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) draft() domain.MessageDraft {
|
||||
return domain.MessageDraft{
|
||||
ChatID: s.chatID,
|
||||
SenderID: s.caller,
|
||||
Text: "Привет, Боб!",
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendReturnsStoredMessage() {
|
||||
draft := s.draft()
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: draft.ChatID,
|
||||
SenderID: draft.SenderID,
|
||||
Text: draft.Text,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.messages.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsWhitespaceTextWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.Text = " \t\n "
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation,
|
||||
"пробельный текст не проходит схему контракта, но проходит minLength")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendPropagatesNotFoundForOutsider() {
|
||||
draft := s.draft()
|
||||
|
||||
s.messages.EXPECT().Create(s.T().Context(), draft).Return(domain.Message{}, domain.ErrNotFound).Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound,
|
||||
"доступ проверяет хранилище атомарно со вставкой")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryPassesNilCursorOnFirstPage() {
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: s.chatID,
|
||||
SenderID: s.caller,
|
||||
Text: "первое",
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{Items: []domain.Message{stored}}, nil).
|
||||
Once()
|
||||
|
||||
page, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]domain.Message{stored}, page.Items)
|
||||
s.Nil(page.Next)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryRejectsCursorFromAnotherChat() {
|
||||
foreign := &domain.Cursor{Scope: uuid.New(), CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, foreign, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrInvalidCursor,
|
||||
"контракт требует 400 на курсор от другого чата")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryAcceptsCursorOfSameChat() {
|
||||
own := &domain.Cursor{Scope: s.chatID, CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, own, 7).
|
||||
Return(domain.Page[domain.Message]{}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, own, 7)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryPropagatesNotFoundForOutsider() {
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{}, domain.ErrNotFound).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryWrapsRepositoryFailure() {
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{}, errRepository).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.UserDraft) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.UserDraft) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.UserDraft) domain.User); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.UserDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.UserDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.UserDraft)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.UserDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.UserDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(user domain.User, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.UserDraft) (domain.User, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetByID provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetByID")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) domain.User); ok {
|
||||
r0 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetByID'
|
||||
type MockRepository_GetByID_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetByID is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
func (_e *MockRepository_Expecter) GetByID(ctx any, id any) *MockRepository_GetByID_Call {
|
||||
return &MockRepository_GetByID_Call{Call: _e.mock.On("GetByID", ctx, id)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetByID_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockRepository_GetByID_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetByID_Call) Return(user domain.User, err error) *MockRepository_GetByID_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetByID_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) (domain.User, error)) *MockRepository_GetByID_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
//go:generate go tool mockery
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.UserDraft) (domain.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
users Repository
|
||||
}
|
||||
|
||||
func NewService(users Repository) *Service {
|
||||
return &Service{users: users}
|
||||
}
|
||||
|
||||
func (s *Service) Register(ctx context.Context, draft domain.UserDraft) (domain.User, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
user, err := s.users.Create(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, err := s.users.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package user_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/user"
|
||||
"mtusi-messenger/internal/service/user/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
users *mocks.MockRepository
|
||||
service *user.Service
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.users = mocks.NewMockRepository(s.T())
|
||||
s.service = user.NewService(s.users)
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterReturnsStoredUser() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса"}
|
||||
stored := domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.users.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got, "сервис отдаёт то, что присвоило хранилище")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterRejectsBlankDisplayNameWithoutRepositoryCall() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: " "}
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterPropagatesUsernameConflict() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса"}
|
||||
|
||||
s.users.EXPECT().Create(s.T().Context(), draft).Return(domain.User{}, domain.ErrUsernameTaken).Once()
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetByIDPropagatesNotFound() {
|
||||
id := uuid.New()
|
||||
|
||||
s.users.EXPECT().GetByID(s.T().Context(), id).Return(domain.User{}, domain.ErrNotFound).Once()
|
||||
|
||||
_, err := s.service.GetByID(s.T().Context(), id)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetByIDWrapsRepositoryFailure() {
|
||||
id := uuid.New()
|
||||
|
||||
s.users.EXPECT().GetByID(s.T().Context(), id).Return(domain.User{}, errRepository).Once()
|
||||
|
||||
_, err := s.service.GetByID(s.T().Context(), id)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(_ context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, id := range draft.MemberIDs {
|
||||
if _, ok := s.usersByID[id]; !ok {
|
||||
return domain.Chat{}, domain.ErrUnknownMember
|
||||
}
|
||||
}
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: s.ids.NewID(),
|
||||
Title: draft.Title,
|
||||
MemberIDs: slices.Clone(draft.MemberIDs),
|
||||
CreatedAt: s.clock.Now(),
|
||||
}
|
||||
|
||||
s.chatsByID[chat.ID] = chat
|
||||
|
||||
at, _ := slices.BinarySearchFunc(s.chatsOrdered, chat, func(a, b domain.Chat) int {
|
||||
return compareKeyset(a.CreatedAt, a.ID, b.CreatedAt, b.ID)
|
||||
})
|
||||
s.chatsOrdered = slices.Insert(s.chatsOrdered, at, chat)
|
||||
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(_ context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, ok := s.chatsByID[chatID]
|
||||
if !ok || !chat.HasMember(callerID) {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVisible(
|
||||
_ context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
visible := make([]domain.Chat, 0, len(s.chatsOrdered))
|
||||
|
||||
for _, chat := range s.chatsOrdered {
|
||||
if chat.HasMember(callerID) {
|
||||
visible = append(visible, chat)
|
||||
}
|
||||
}
|
||||
|
||||
page := paginate(visible, callerID, chatKey, after, limit)
|
||||
for i, chat := range page.Items {
|
||||
page.Items[i] = cloneChat(chat)
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func chatKey(chat domain.Chat) (time.Time, uuid.UUID) {
|
||||
return chat.CreatedAt, chat.ID
|
||||
}
|
||||
|
||||
func cloneChat(chat domain.Chat) domain.Chat {
|
||||
chat.MemberIDs = slices.Clone(chat.MemberIDs)
|
||||
|
||||
return chat
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type benchmarkClock struct{ now time.Time }
|
||||
|
||||
func (c benchmarkClock) Now() time.Time { return c.now }
|
||||
|
||||
func BenchmarkMessageCreate(b *testing.B) {
|
||||
for _, size := range []int{1000, 10000, 50000} {
|
||||
b.Run(fmt.Sprintf("history=%d", size), func(b *testing.B) {
|
||||
base := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
store := NewStore(WithClock(benchmarkClock{now: base.Add(time.Hour)}))
|
||||
chatID, senderID := uuid.New(), uuid.New()
|
||||
store.chatsByID[chatID] = domain.Chat{ID: chatID, MemberIDs: []uuid.UUID{senderID}}
|
||||
history := make([]domain.Message, size, size+1)
|
||||
for i := range history {
|
||||
history[i] = domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
CreatedAt: base.Add(time.Duration(i) * time.Microsecond),
|
||||
}
|
||||
}
|
||||
store.messagesByChat[chatID] = history
|
||||
draft := domain.MessageDraft{ChatID: chatID, SenderID: senderID, Text: "benchmark"}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
created, err := store.Messages().Create(context.Background(), draft)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if len(store.messagesByChat[chatID]) != size+1 ||
|
||||
compareKeyset(history[size-1].CreatedAt, history[size-1].ID, created.CreatedAt, created.ID) >= 0 {
|
||||
b.Fatal("message not appended in keyset order")
|
||||
}
|
||||
store.messagesByChat[chatID] = store.messagesByChat[chatID][:size]
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(_ context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
chat, ok := s.chatsByID[draft.ChatID]
|
||||
if !ok || !chat.HasMember(draft.SenderID) {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: s.ids.NewID(),
|
||||
ChatID: draft.ChatID,
|
||||
SenderID: draft.SenderID,
|
||||
Text: draft.Text,
|
||||
CreatedAt: s.clock.Now(),
|
||||
}
|
||||
|
||||
history := s.messagesByChat[message.ChatID]
|
||||
if len(history) == 0 || compareKeyset(
|
||||
history[len(history)-1].CreatedAt,
|
||||
history[len(history)-1].ID,
|
||||
message.CreatedAt,
|
||||
message.ID,
|
||||
) < 0 {
|
||||
s.messagesByChat[message.ChatID] = append(history, message)
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
at, _ := slices.BinarySearchFunc(history, message, func(a, b domain.Message) int {
|
||||
return compareKeyset(a.CreatedAt, a.ID, b.CreatedAt, b.ID)
|
||||
})
|
||||
s.messagesByChat[message.ChatID] = slices.Insert(history, at, message)
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) ListVisible(
|
||||
_ context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, ok := s.chatsByID[chatID]
|
||||
if !ok || !chat.HasMember(callerID) {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return paginate(s.messagesByChat[chatID], chatID, messageKey, after, limit), nil
|
||||
}
|
||||
|
||||
func messageKey(message domain.Message) (time.Time, uuid.UUID) {
|
||||
return message.CreatedAt, message.ID
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
package memory_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/chat"
|
||||
"mtusi-messenger/internal/service/message"
|
||||
"mtusi-messenger/internal/service/user"
|
||||
"mtusi-messenger/internal/storage/memory"
|
||||
)
|
||||
|
||||
type stepClock struct {
|
||||
mu sync.Mutex
|
||||
next time.Time
|
||||
}
|
||||
|
||||
func newStepClock() *stepClock {
|
||||
return &stepClock{next: time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)}
|
||||
}
|
||||
|
||||
func (c *stepClock) Now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
out := c.next
|
||||
c.next = c.next.Add(time.Second)
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
type RepositorySuite struct {
|
||||
suite.Suite
|
||||
|
||||
store *memory.Store
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) ctx() context.Context { return s.T().Context() }
|
||||
|
||||
func TestRepositorySuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(RepositorySuite))
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) SetupTest() {
|
||||
s.store = memory.NewStore(memory.WithClock(newStepClock()))
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) createUser(username string) domain.User {
|
||||
s.T().Helper()
|
||||
|
||||
created, err := s.store.Users().Create(s.ctx(), domain.UserDraft{
|
||||
Username: username,
|
||||
DisplayName: "Пользователь",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
return created
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) createChat(title string, members ...uuid.UUID) domain.Chat {
|
||||
s.T().Helper()
|
||||
|
||||
created, err := s.store.Chats().Create(s.ctx(), domain.ChatDraft{
|
||||
Title: title,
|
||||
MemberIDs: members,
|
||||
CallerID: members[0],
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
return created
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestCreateAssignsIdentityAndTime() {
|
||||
created := s.createUser("alice")
|
||||
|
||||
s.NotEqual(uuid.Nil, created.ID, "идентификатор назначает хранилище")
|
||||
s.False(created.CreatedAt.IsZero(), "время назначает хранилище")
|
||||
|
||||
got, err := s.store.Users().GetByID(s.ctx(), created.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(created, got)
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestGetUnknownUser() {
|
||||
_, err := s.store.Users().GetByID(s.ctx(), uuid.New())
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestDuplicateUsernameRejected() {
|
||||
s.createUser("alice")
|
||||
|
||||
_, err := s.store.Users().Create(s.ctx(), domain.UserDraft{
|
||||
Username: "alice",
|
||||
DisplayName: "Другая Алиса",
|
||||
})
|
||||
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestUsernameUniqueUnderConcurrency() {
|
||||
const attempts = 50
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
succeeded int
|
||||
)
|
||||
|
||||
for range attempts {
|
||||
wg.Go(func() {
|
||||
_, err := s.store.Users().Create(s.ctx(), domain.UserDraft{
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
})
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if err == nil {
|
||||
succeeded++
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
s.Equal(1, succeeded, "username уникален даже при гонке")
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestChatRejectsUnknownMember() {
|
||||
caller := s.createUser("alice")
|
||||
|
||||
_, err := s.store.Chats().Create(s.ctx(), domain.ChatDraft{
|
||||
Title: "Проект",
|
||||
MemberIDs: []uuid.UUID{caller.ID, uuid.New()},
|
||||
CallerID: caller.ID,
|
||||
})
|
||||
s.Require().ErrorIs(err, domain.ErrUnknownMember,
|
||||
"ссылочная целостность проверяется там же, где вставка")
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestChatVisibleOnlyToMembers() {
|
||||
member := s.createUser("alice")
|
||||
outsider := s.createUser("bob")
|
||||
|
||||
created := s.createChat("Проект", member.ID)
|
||||
|
||||
got, err := s.store.Chats().GetVisible(s.ctx(), created.ID, member.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(created.ID, got.ID)
|
||||
|
||||
_, err = s.store.Chats().GetVisible(s.ctx(), created.ID, outsider.ID)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound, "чужой чат неотличим от отсутствующего")
|
||||
|
||||
page, err := s.store.Chats().ListVisible(s.ctx(), outsider.ID, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Empty(page.Items, "чужой чат не попадает в список")
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestStoredChatIsIsolated() {
|
||||
member := s.createUser("alice")
|
||||
members := []uuid.UUID{member.ID}
|
||||
|
||||
created := s.createChat("Проект", members...)
|
||||
|
||||
members[0] = uuid.New()
|
||||
|
||||
got, err := s.store.Chats().GetVisible(s.ctx(), created.ID, member.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]uuid.UUID{member.ID}, got.MemberIDs, "хранилище не делит срез с вызывающим")
|
||||
|
||||
got.MemberIDs[0] = uuid.New()
|
||||
|
||||
again, err := s.store.Chats().GetVisible(s.ctx(), created.ID, member.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]uuid.UUID{member.ID}, again.MemberIDs)
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestChatsSortedByKeyset() {
|
||||
member := s.createUser("alice")
|
||||
|
||||
for range 3 {
|
||||
s.createChat("Чат", member.ID)
|
||||
}
|
||||
|
||||
page, err := s.store.Chats().ListVisible(s.ctx(), member.ID, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(page.Items, 3)
|
||||
|
||||
for i := 1; i < len(page.Items); i++ {
|
||||
s.True(
|
||||
page.Items[i-1].CreatedAt.Before(page.Items[i].CreatedAt),
|
||||
"порядок (created_at, id) по возрастанию",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestMessageRejectsOutsider() {
|
||||
member := s.createUser("alice")
|
||||
outsider := s.createUser("bob")
|
||||
created := s.createChat("Проект", member.ID)
|
||||
|
||||
_, err := s.store.Messages().Create(s.ctx(), domain.MessageDraft{
|
||||
ChatID: created.ID,
|
||||
SenderID: outsider.ID,
|
||||
Text: "привет",
|
||||
})
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
|
||||
_, err = s.store.Messages().ListVisible(s.ctx(), created.ID, outsider.ID, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestMessageHistoryIsolatedPerChat() {
|
||||
member := s.createUser("alice")
|
||||
first := s.createChat("Первый", member.ID)
|
||||
second := s.createChat("Второй", member.ID)
|
||||
|
||||
for _, tt := range []struct {
|
||||
chatID uuid.UUID
|
||||
text string
|
||||
}{
|
||||
{chatID: first.ID, text: "в первом"},
|
||||
{chatID: second.ID, text: "во втором"},
|
||||
} {
|
||||
_, err := s.store.Messages().Create(s.ctx(), domain.MessageDraft{
|
||||
ChatID: tt.chatID,
|
||||
SenderID: member.ID,
|
||||
Text: tt.text,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
page, err := s.store.Messages().ListVisible(s.ctx(), first.ID, member.ID, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(page.Items, 1)
|
||||
s.Equal("в первом", page.Items[0].Text)
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestEmptyHistoryReturnsEmptyPage() {
|
||||
member := s.createUser("alice")
|
||||
created := s.createChat("Проект", member.ID)
|
||||
|
||||
page, err := s.store.Messages().ListVisible(s.ctx(), created.ID, member.ID, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.NotNil(page.Items, `контракт требует "items": [], а не null`)
|
||||
s.Empty(page.Items)
|
||||
s.Nil(page.Next)
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestConcurrentMessagesAllStored() {
|
||||
const (
|
||||
clients = 10
|
||||
perClient = 10
|
||||
total = clients * perClient
|
||||
readerIterations = 20
|
||||
)
|
||||
|
||||
member := s.createUser("alice")
|
||||
created := s.createChat("Проект", member.ID)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
failures := make(chan error, total+readerIterations)
|
||||
|
||||
for range clients {
|
||||
wg.Go(func() {
|
||||
for range perClient {
|
||||
_, err := s.store.Messages().Create(s.ctx(), domain.MessageDraft{
|
||||
ChatID: created.ID,
|
||||
SenderID: member.ID,
|
||||
Text: "сообщение",
|
||||
})
|
||||
if err != nil {
|
||||
failures <- err
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
wg.Go(func() {
|
||||
for range readerIterations {
|
||||
_, err := s.store.Messages().ListVisible(
|
||||
s.ctx(), created.ID, member.ID, nil, domain.DefaultPageLimit,
|
||||
)
|
||||
if err != nil {
|
||||
failures <- err
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
wg.Wait()
|
||||
close(failures)
|
||||
|
||||
for err := range failures {
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, total)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Messages().ListVisible(s.ctx(), created.ID, member.ID, cursor, 7)
|
||||
s.Require().NoError(err)
|
||||
|
||||
for _, msg := range page.Items {
|
||||
_, duplicate := seen[msg.ID]
|
||||
s.Require().False(duplicate, "обход истории не должен повторять сообщения")
|
||||
seen[msg.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, total, "все подтверждённые сообщения должны быть видны следующему чтению")
|
||||
}
|
||||
|
||||
func (s *RepositorySuite) TestPageWalkIsStable() {
|
||||
const total = 25
|
||||
|
||||
member := s.createUser("alice")
|
||||
created := s.createChat("Проект", member.ID)
|
||||
|
||||
for range total {
|
||||
_, err := s.store.Messages().Create(s.ctx(), domain.MessageDraft{
|
||||
ChatID: created.ID,
|
||||
SenderID: member.ID,
|
||||
Text: "сообщение",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
whole, err := s.store.Messages().ListVisible(s.ctx(), created.ID, member.ID, nil, 100)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(whole.Items, total)
|
||||
|
||||
var (
|
||||
walked []domain.Message
|
||||
cursor *domain.Cursor
|
||||
)
|
||||
|
||||
for {
|
||||
page, err := s.store.Messages().ListVisible(s.ctx(), created.ID, member.ID, cursor, 4)
|
||||
s.Require().NoError(err)
|
||||
|
||||
walked = append(walked, page.Items...)
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Equal(whole.Items, walked)
|
||||
}
|
||||
|
||||
func TestRepositoriesImplementContracts(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := memory.NewStore()
|
||||
|
||||
require.Implements(t, (*user.Repository)(nil), store.Users())
|
||||
require.Implements(t, (*chat.Repository)(nil), store.Chats())
|
||||
require.Implements(t, (*message.Repository)(nil), store.Messages())
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type Clock interface {
|
||||
Now() time.Time
|
||||
}
|
||||
|
||||
type IDGenerator interface {
|
||||
NewID() uuid.UUID
|
||||
}
|
||||
|
||||
type systemClock struct{}
|
||||
|
||||
func (systemClock) Now() time.Time {
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
type randomIDGenerator struct{}
|
||||
|
||||
func (randomIDGenerator) NewID() uuid.UUID {
|
||||
return uuid.New()
|
||||
}
|
||||
|
||||
type options struct {
|
||||
clock Clock
|
||||
ids IDGenerator
|
||||
}
|
||||
|
||||
type Option func(*options)
|
||||
|
||||
func WithClock(clock Clock) Option {
|
||||
return func(o *options) {
|
||||
if clock != nil {
|
||||
o.clock = clock
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithIDGenerator(ids IDGenerator) Option {
|
||||
return func(o *options) {
|
||||
if ids != nil {
|
||||
o.ids = ids
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
clock Clock
|
||||
ids IDGenerator
|
||||
|
||||
mu sync.RWMutex
|
||||
usersByID map[uuid.UUID]domain.User
|
||||
usersByUsername map[string]uuid.UUID
|
||||
chatsByID map[uuid.UUID]domain.Chat
|
||||
chatsOrdered []domain.Chat
|
||||
messagesByChat map[uuid.UUID][]domain.Message
|
||||
|
||||
users *UserRepository
|
||||
chats *ChatRepository
|
||||
messages *MessageRepository
|
||||
}
|
||||
|
||||
func NewStore(opts ...Option) *Store {
|
||||
cfg := options{clock: systemClock{}, ids: randomIDGenerator{}}
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
|
||||
store := &Store{
|
||||
clock: cfg.clock,
|
||||
ids: cfg.ids,
|
||||
usersByID: make(map[uuid.UUID]domain.User),
|
||||
usersByUsername: make(map[string]uuid.UUID),
|
||||
chatsByID: make(map[uuid.UUID]domain.Chat),
|
||||
messagesByChat: make(map[uuid.UUID][]domain.Message),
|
||||
}
|
||||
|
||||
store.users = &UserRepository{store: store}
|
||||
store.chats = &ChatRepository{store: store}
|
||||
store.messages = &MessageRepository{store: store}
|
||||
|
||||
return store
|
||||
}
|
||||
|
||||
func (s *Store) Users() *UserRepository { return s.users }
|
||||
|
||||
func (s *Store) Chats() *ChatRepository { return s.chats }
|
||||
|
||||
func (s *Store) Messages() *MessageRepository { return s.messages }
|
||||
|
||||
func compareKeyset(aCreatedAt time.Time, aID uuid.UUID, bCreatedAt time.Time, bID uuid.UUID) int {
|
||||
if c := aCreatedAt.Compare(bCreatedAt); c != 0 {
|
||||
return c
|
||||
}
|
||||
|
||||
return cmp.Compare(aID.String(), bID.String())
|
||||
}
|
||||
|
||||
func paginate[T any](
|
||||
items []T,
|
||||
scope uuid.UUID,
|
||||
key func(T) (time.Time, uuid.UUID),
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) domain.Page[T] {
|
||||
start := 0
|
||||
|
||||
if after != nil {
|
||||
start, _ = slices.BinarySearchFunc(items, *after, func(item T, target domain.Cursor) int {
|
||||
createdAt, id := key(item)
|
||||
if compareKeyset(createdAt, id, target.CreatedAt, target.ID) > 0 {
|
||||
return 1
|
||||
}
|
||||
|
||||
return -1
|
||||
})
|
||||
}
|
||||
|
||||
rest := items[start:]
|
||||
|
||||
page := domain.Page[T]{Items: make([]T, 0, min(len(rest), limit))}
|
||||
if len(rest) <= limit {
|
||||
page.Items = append(page.Items, rest...)
|
||||
|
||||
return page
|
||||
}
|
||||
|
||||
page.Items = append(page.Items, rest[:limit]...)
|
||||
|
||||
createdAt, id := key(page.Items[limit-1])
|
||||
page.Next = &domain.Cursor{Scope: scope, CreatedAt: createdAt, ID: id}
|
||||
|
||||
return page
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type entry struct {
|
||||
createdAt time.Time
|
||||
id uuid.UUID
|
||||
}
|
||||
|
||||
func entryKey(e entry) (time.Time, uuid.UUID) {
|
||||
return e.createdAt, e.id
|
||||
}
|
||||
|
||||
func TestCompareKeyset(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
earlier := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
later := earlier.Add(time.Second)
|
||||
|
||||
lowID := uuid.MustParse("11111111-1111-4111-8111-111111111111")
|
||||
highID := uuid.MustParse("22222222-2222-4222-8222-222222222222")
|
||||
|
||||
tests := map[string]struct {
|
||||
a entry
|
||||
b entry
|
||||
want int
|
||||
}{
|
||||
"время решает": {
|
||||
a: entry{createdAt: earlier, id: highID},
|
||||
b: entry{createdAt: later, id: lowID},
|
||||
want: -1,
|
||||
},
|
||||
"при равном времени решает id": {
|
||||
a: entry{createdAt: earlier, id: lowID},
|
||||
b: entry{createdAt: earlier, id: highID},
|
||||
want: -1,
|
||||
},
|
||||
"полное совпадение": {
|
||||
a: entry{createdAt: earlier, id: lowID},
|
||||
b: entry{createdAt: earlier, id: lowID},
|
||||
want: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for name, tt := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
assert.Equal(t, tt.want, compareKeyset(tt.a.createdAt, tt.a.id, tt.b.createdAt, tt.b.id))
|
||||
assert.Equal(t, -tt.want, compareKeyset(tt.b.createdAt, tt.b.id, tt.a.createdAt, tt.a.id),
|
||||
"сравнение должно быть антисимметричным")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func makeEntries(n int) []entry {
|
||||
base := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
items := make([]entry, 0, n)
|
||||
|
||||
for i := range n {
|
||||
items = append(items, entry{
|
||||
createdAt: base.Add(time.Duration(i) * time.Second),
|
||||
id: uuid.New(),
|
||||
})
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
func TestPaginateFirstPage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
scope := uuid.New()
|
||||
items := makeEntries(5)
|
||||
|
||||
page := paginate(items, scope, entryKey, nil, 2)
|
||||
|
||||
require.Len(t, page.Items, 2)
|
||||
assert.Equal(t, items[:2], page.Items)
|
||||
require.NotNil(t, page.Next)
|
||||
assert.Equal(t, items[1].id, page.Next.ID)
|
||||
assert.Equal(t, scope, page.Next.Scope, "курсор должен нести привязку к последовательности")
|
||||
}
|
||||
|
||||
func TestPaginateLastPageHasNoCursor(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
items := makeEntries(3)
|
||||
|
||||
page := paginate(items, uuid.New(), entryKey, nil, 3)
|
||||
|
||||
assert.Equal(t, items, page.Items)
|
||||
assert.Nil(t, page.Next, "на последней странице next_cursor равен null")
|
||||
}
|
||||
|
||||
func TestPaginateEmptyResultIsNotNil(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
page := paginate([]entry{}, uuid.New(), entryKey, nil, 10)
|
||||
|
||||
assert.NotNil(t, page.Items, `контракт требует "items": [], а не null`)
|
||||
assert.Empty(t, page.Items)
|
||||
assert.Nil(t, page.Next)
|
||||
}
|
||||
|
||||
func TestPaginateWalkWithoutDuplicates(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
total = 10
|
||||
limit = 3
|
||||
)
|
||||
|
||||
scope := uuid.New()
|
||||
items := makeEntries(total)
|
||||
|
||||
var (
|
||||
seen []entry
|
||||
cursor *domain.Cursor
|
||||
)
|
||||
|
||||
for range total {
|
||||
page := paginate(items, scope, entryKey, cursor, limit)
|
||||
seen = append(seen, page.Items...)
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
assert.Equal(t, items, seen)
|
||||
}
|
||||
|
||||
func TestPaginateCursorBeyondEnd(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
scope := uuid.New()
|
||||
items := makeEntries(3)
|
||||
last := items[len(items)-1]
|
||||
|
||||
page := paginate(items, scope, entryKey, &domain.Cursor{
|
||||
Scope: scope,
|
||||
CreatedAt: last.createdAt,
|
||||
ID: last.id,
|
||||
}, 10)
|
||||
|
||||
assert.Empty(t, page.Items)
|
||||
assert.Nil(t, page.Next)
|
||||
}
|
||||
|
||||
func TestPaginateChangedLimitOnContinuation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
scope := uuid.New()
|
||||
items := makeEntries(6)
|
||||
|
||||
first := paginate(items, scope, entryKey, nil, 2)
|
||||
require.NotNil(t, first.Next)
|
||||
|
||||
second := paginate(items, scope, entryKey, first.Next, 4)
|
||||
|
||||
assert.Equal(t, items[2:], second.Items)
|
||||
assert.Nil(t, second.Next, "изменение limit при продолжении допустимо")
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(_ context.Context, draft domain.UserDraft) (domain.User, error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if _, taken := s.usersByUsername[draft.Username]; taken {
|
||||
return domain.User{}, domain.ErrUsernameTaken
|
||||
}
|
||||
|
||||
user := domain.User{
|
||||
ID: s.ids.NewID(),
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
CreatedAt: s.clock.Now(),
|
||||
}
|
||||
|
||||
s.usersByID[user.ID] = user
|
||||
s.usersByUsername[user.Username] = user.ID
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, ok := s.usersByID[id]
|
||||
if !ok {
|
||||
return domain.User{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/transport/rest/oas"
|
||||
)
|
||||
|
||||
var fallbackErrorBody = []byte(`{"error":{"code":"internal_error","message":"Internal error","request_id":""}}`)
|
||||
|
||||
func newErrorHandler(log *slog.Logger) oas.ErrorHandler {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
|
||||
status := statusForError(err)
|
||||
|
||||
if preMiddlewareError(err) {
|
||||
logRejected(ctx, log, r, status, err)
|
||||
}
|
||||
|
||||
writeError(ctx, log, w, r, status)
|
||||
}
|
||||
}
|
||||
|
||||
func statusForError(err error) int {
|
||||
if status := ogenerrors.ErrorCode(err); status != http.StatusInternalServerError {
|
||||
return status
|
||||
}
|
||||
|
||||
switch {
|
||||
case errors.Is(err, ErrUnauthenticated):
|
||||
return http.StatusUnauthorized
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return http.StatusNotFound
|
||||
case errors.Is(err, domain.ErrUsernameTaken):
|
||||
return http.StatusConflict
|
||||
case errors.Is(err, domain.ErrValidation),
|
||||
errors.Is(err, domain.ErrUnknownMember),
|
||||
errors.Is(err, domain.ErrInvalidCursor):
|
||||
return http.StatusBadRequest
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
|
||||
func newNotFoundHandler(log *slog.Logger) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
logRejected(r.Context(), log, r, http.StatusNotFound, nil)
|
||||
writeError(r.Context(), log, w, r, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func newMethodNotAllowedHandler(log *slog.Logger) func(http.ResponseWriter, *http.Request, string) {
|
||||
return func(w http.ResponseWriter, r *http.Request, allowed string) {
|
||||
w.Header().Set("Allow", allowed)
|
||||
logRejected(r.Context(), log, r, http.StatusMethodNotAllowed, nil)
|
||||
writeError(r.Context(), log, w, r, http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(ctx context.Context, log *slog.Logger, w http.ResponseWriter, r *http.Request, status int) {
|
||||
requestID := requestIDFromContext(ctx)
|
||||
if requestID == "" {
|
||||
requestID = r.Header.Get(requestIDHeader)
|
||||
}
|
||||
|
||||
body := oas.Error{
|
||||
Error: oas.ErrorError{
|
||||
Code: codeForStatus(status),
|
||||
Message: http.StatusText(status),
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
|
||||
payload, marshalErr := json.Marshal(body)
|
||||
if marshalErr != nil {
|
||||
status = http.StatusInternalServerError
|
||||
payload = fallbackErrorBody
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set(requestIDHeader, requestID)
|
||||
w.WriteHeader(status)
|
||||
|
||||
if _, err := w.Write(payload); err != nil && log != nil {
|
||||
log.WarnContext(ctx, "response write failed", slog.String("error", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func codeForStatus(status int) oas.ErrorErrorCode {
|
||||
switch status {
|
||||
case http.StatusBadRequest, http.StatusMethodNotAllowed:
|
||||
return oas.ErrorErrorCodeInvalidRequest
|
||||
case http.StatusUnauthorized:
|
||||
return oas.ErrorErrorCodeUnauthorized
|
||||
case http.StatusNotFound:
|
||||
return oas.ErrorErrorCodeNotFound
|
||||
case http.StatusConflict:
|
||||
return oas.ErrorErrorCodeConflict
|
||||
case http.StatusRequestEntityTooLarge:
|
||||
return oas.ErrorErrorCodePayloadTooLarge
|
||||
case http.StatusUnsupportedMediaType:
|
||||
return oas.ErrorErrorCodeUnsupportedMediaType
|
||||
case http.StatusTooManyRequests:
|
||||
return oas.ErrorErrorCodeRateLimited
|
||||
case http.StatusServiceUnavailable:
|
||||
return oas.ErrorErrorCodeUnavailable
|
||||
default:
|
||||
return oas.ErrorErrorCodeInternalError
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/transport/rest/oas"
|
||||
)
|
||||
|
||||
type UserService interface {
|
||||
Register(ctx context.Context, draft domain.UserDraft) (domain.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||
}
|
||||
|
||||
type ChatService interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
Get(ctx context.Context, callerID, chatID uuid.UUID) (domain.Chat, error)
|
||||
List(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type MessageService interface {
|
||||
Send(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
|
||||
History(
|
||||
ctx context.Context,
|
||||
callerID, chatID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
oas.UnimplementedHandler
|
||||
|
||||
users UserService
|
||||
chats ChatService
|
||||
messages MessageService
|
||||
}
|
||||
|
||||
var noCursor *domain.Cursor
|
||||
|
||||
func NewHandler(users UserService, chats ChatService, messages MessageService) *Handler {
|
||||
return &Handler{
|
||||
users: users,
|
||||
chats: chats,
|
||||
messages: messages,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Liveness(ctx context.Context) (oas.LivenessRes, error) {
|
||||
return &oas.HealthHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.Health{Status: oas.HealthStatusOk},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) Readiness(ctx context.Context) (oas.ReadinessRes, error) {
|
||||
return &oas.HealthHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.Health{Status: oas.HealthStatusOk},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterUser(ctx context.Context, req *oas.CreateUser) (oas.RegisterUserRes, error) {
|
||||
user, err := h.users.Register(ctx, domain.UserDraft{
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.UserHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: userResponse(user),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) CurrentUser(ctx context.Context) (oas.CurrentUserRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
user, err := h.users.GetByID(ctx, callerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.UserHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: userResponse(user),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(ctx context.Context, req *oas.CreateChat) (oas.CreateChatRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
chat, err := h.chats.Create(ctx, domain.ChatDraft{
|
||||
Title: req.Title,
|
||||
MemberIDs: req.MemberIds,
|
||||
CallerID: callerID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.ChatHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: chatResponse(chat),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) GetChat(ctx context.Context, params oas.GetChatParams) (oas.GetChatRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
chat, err := h.chats.Get(ctx, callerID, params.ChatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.ChatHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: chatResponse(chat),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) ListChats(ctx context.Context, params oas.ListChatsParams) (oas.ListChatsRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
after, err := parseCursor(params.Cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
page, err := h.chats.List(ctx, callerID, after, limitOrDefault(params.Limit))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]oas.Chat, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, chatResponse(chat))
|
||||
}
|
||||
|
||||
return &oas.ChatPageHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.ChatPage{
|
||||
Items: items,
|
||||
NextCursor: encodeCursor(page.Next),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) CreateMessage(
|
||||
ctx context.Context,
|
||||
req *oas.CreateMessage,
|
||||
params oas.CreateMessageParams,
|
||||
) (oas.CreateMessageRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
message, err := h.messages.Send(ctx, domain.MessageDraft{
|
||||
ChatID: params.ChatID,
|
||||
SenderID: callerID,
|
||||
Text: req.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.MessageHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: messageResponse(message),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) ListMessages(ctx context.Context, params oas.ListMessagesParams) (oas.ListMessagesRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
after, err := parseCursor(params.Cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
page, err := h.messages.History(ctx, callerID, params.ChatID, after, limitOrDefault(params.Limit))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]oas.Message, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, messageResponse(message))
|
||||
}
|
||||
|
||||
return &oas.MessagePageHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.MessagePage{
|
||||
Items: items,
|
||||
NextCursor: encodeCursor(page.Next),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseCursor(raw oas.OptString) (*domain.Cursor, error) {
|
||||
encoded, ok := raw.Get()
|
||||
if !ok {
|
||||
return noCursor, nil
|
||||
}
|
||||
|
||||
cursor, err := decodeCursor(encoded)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &cursor, nil
|
||||
}
|
||||
|
||||
func encodeCursor(next *domain.Cursor) oas.NilString {
|
||||
var out oas.NilString
|
||||
|
||||
if next == nil {
|
||||
out.SetToNull()
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
out.SetTo(encodeCursorValue(*next))
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
type cursorWire struct {
|
||||
Scope uuid.UUID `json:"scope"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
}
|
||||
|
||||
func encodeCursorValue(cursor domain.Cursor) string {
|
||||
payload, err := json.Marshal(cursorWire{
|
||||
Scope: cursor.Scope,
|
||||
CreatedAt: cursor.CreatedAt.UTC(),
|
||||
ID: cursor.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return base64.RawURLEncoding.EncodeToString(payload)
|
||||
}
|
||||
|
||||
func decodeCursor(encoded string) (domain.Cursor, error) {
|
||||
payload, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return domain.Cursor{}, fmt.Errorf("decode cursor: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
var wire cursorWire
|
||||
if err := decoder.Decode(&wire); err != nil {
|
||||
return domain.Cursor{}, fmt.Errorf("parse cursor: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
if wire.ID == uuid.Nil {
|
||||
return domain.Cursor{}, fmt.Errorf("cursor id is empty: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
return domain.Cursor{
|
||||
Scope: wire.Scope,
|
||||
CreatedAt: wire.CreatedAt.UTC(),
|
||||
ID: wire.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func limitOrDefault(limit oas.OptInt) int {
|
||||
if value, ok := limit.Get(); ok {
|
||||
return value
|
||||
}
|
||||
|
||||
return domain.DefaultPageLimit
|
||||
}
|
||||
|
||||
func userResponse(user domain.User) oas.User {
|
||||
return oas.User{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: user.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func chatResponse(chat domain.Chat) oas.Chat {
|
||||
return oas.Chat{
|
||||
ID: chat.ID,
|
||||
Title: chat.Title,
|
||||
MemberIds: chat.MemberIDs,
|
||||
CreatedAt: chat.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func messageResponse(message domain.Message) oas.Message {
|
||||
return oas.Message{
|
||||
ID: message.ID,
|
||||
ChatID: message.ChatID,
|
||||
SenderID: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
|
||||
"mtusi-messenger/internal/transport/rest/oas"
|
||||
)
|
||||
|
||||
func loggingMiddleware(log *slog.Logger) oas.Middleware {
|
||||
return func(req middleware.Request, next middleware.Next) (middleware.Response, error) {
|
||||
started := time.Now()
|
||||
|
||||
base := []any{
|
||||
slog.String("request_id", requestIDFromContext(req.Context)),
|
||||
slog.String("operation", req.OperationID),
|
||||
slog.String("method", req.Raw.Method),
|
||||
slog.String("path", req.Raw.URL.Path),
|
||||
}
|
||||
|
||||
accepted := make([]any, 0, len(base)+6)
|
||||
accepted = append(accepted, base...)
|
||||
accepted = append(accepted,
|
||||
slog.String("query", req.Raw.URL.RawQuery),
|
||||
slog.String("remote_addr", req.Raw.RemoteAddr),
|
||||
slog.String("user_agent", req.Raw.UserAgent()),
|
||||
slog.Int64("content_length", req.Raw.ContentLength),
|
||||
slog.Any("params", loggedParams(req.Params)),
|
||||
payloadAttr(req.RawBody),
|
||||
)
|
||||
|
||||
log.InfoContext(req.Context, "request accepted", accepted...)
|
||||
|
||||
resp, err := next(req)
|
||||
|
||||
handled := make([]any, 0, len(base)+4)
|
||||
handled = append(handled, base...)
|
||||
handled = append(handled, slog.Duration("duration", time.Since(started)))
|
||||
|
||||
if err != nil {
|
||||
status := ogenerrors.ErrorCode(err)
|
||||
|
||||
handled = append(handled,
|
||||
slog.Int("status", status),
|
||||
slog.String("error", err.Error()),
|
||||
)
|
||||
log.Log(req.Context, levelForStatus(status), "request failed", handled...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
handled = append(handled, slog.String("result", resultType(resp)))
|
||||
log.InfoContext(req.Context, "request handled", handled...)
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
func logRejected(ctx context.Context, log *slog.Logger, r *http.Request, status int, err error) {
|
||||
if log == nil {
|
||||
return
|
||||
}
|
||||
|
||||
attrs := []any{
|
||||
slog.String("request_id", requestIDFromContext(ctx)),
|
||||
slog.String("method", r.Method),
|
||||
slog.String("path", r.URL.Path),
|
||||
slog.Int("status", status),
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
attrs = append(attrs, slog.String("error", err.Error()))
|
||||
}
|
||||
|
||||
log.Log(ctx, levelForStatus(status), "request rejected", attrs...)
|
||||
}
|
||||
|
||||
func preMiddlewareError(err error) bool {
|
||||
return errors.As(err, new(*ogenerrors.SecurityError)) ||
|
||||
errors.As(err, new(*ogenerrors.DecodeParamsError)) ||
|
||||
errors.As(err, new(*ogenerrors.DecodeRequestError))
|
||||
}
|
||||
|
||||
func levelForStatus(status int) slog.Level {
|
||||
if status >= http.StatusInternalServerError {
|
||||
return slog.LevelError
|
||||
}
|
||||
|
||||
return slog.LevelWarn
|
||||
}
|
||||
|
||||
func loggedParams(params middleware.Parameters) map[string]any {
|
||||
if len(params) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
out := make(map[string]any, len(params))
|
||||
for key, value := range params {
|
||||
out[string(key.In)+"."+key.Name] = value
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func payloadAttr(body []byte) slog.Attr {
|
||||
size := len(body)
|
||||
if size == 0 {
|
||||
return slog.Attr{}
|
||||
}
|
||||
|
||||
return slog.Group("payload",
|
||||
slog.Int("size", size),
|
||||
slog.Bool("content_logged", false),
|
||||
)
|
||||
}
|
||||
|
||||
func resultType(resp middleware.Response) string {
|
||||
if resp.Type == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%T", resp.Type)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/openapi"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/transport/rest/oas"
|
||||
)
|
||||
|
||||
type LoggingSuite struct {
|
||||
suite.Suite
|
||||
|
||||
sink *strings.Builder
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func TestLoggingSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(LoggingSuite))
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) SetupTest() {
|
||||
s.sink = &strings.Builder{}
|
||||
s.log = logger.New(
|
||||
logger.WithWriter(s.sink),
|
||||
logger.WithLevel(slog.LevelDebug),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) records() []map[string]any {
|
||||
var out []map[string]any
|
||||
|
||||
for line := range strings.SplitSeq(strings.TrimSpace(s.sink.String()), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var record map[string]any
|
||||
s.Require().NoError(json.Unmarshal([]byte(line), &record))
|
||||
|
||||
out = append(out, record)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) request(method, target, body string) middleware.Request {
|
||||
raw := httptest.NewRequestWithContext(
|
||||
s.T().Context(),
|
||||
method,
|
||||
target,
|
||||
strings.NewReader(body),
|
||||
)
|
||||
raw.RemoteAddr = "192.0.2.10:54321"
|
||||
raw.Header.Set("User-Agent", "smoke/1.0")
|
||||
|
||||
ctx := withRequestID(raw.Context(), "req-42")
|
||||
|
||||
return middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: oas.CreateMessageOperation,
|
||||
OperationID: "createMessage",
|
||||
RawBody: []byte(body),
|
||||
Params: middleware.Parameters{
|
||||
{Name: "chat_id", In: openapi.LocationPath}: "33333333-3333-4333-8333-333333333333",
|
||||
{Name: "limit", In: openapi.LocationQuery}: 50,
|
||||
},
|
||||
Raw: raw,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestLogsAcceptedAndHandled() {
|
||||
req := s.request(http.MethodPost, "/api/v1/chats/33333333-3333-4333-8333-333333333333/messages?limit=50", `{"text":"привет"}`)
|
||||
|
||||
response := middleware.Response{Type: &oas.Message{}}
|
||||
|
||||
got, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return response, nil
|
||||
})
|
||||
|
||||
s.Require().NoError(err)
|
||||
s.Equal(response, got)
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 2, "ожидаются записи о принятом и обработанном запросе")
|
||||
|
||||
accepted, handled := records[0], records[1]
|
||||
|
||||
s.Equal("request accepted", accepted["msg"])
|
||||
s.Equal("info", accepted["level"])
|
||||
s.Equal("req-42", accepted["request_id"])
|
||||
s.Equal("createMessage", accepted["operation"])
|
||||
s.Equal(http.MethodPost, accepted["method"])
|
||||
s.Equal("/api/v1/chats/33333333-3333-4333-8333-333333333333/messages", accepted["path"])
|
||||
s.Equal("limit=50", accepted["query"])
|
||||
s.Equal("192.0.2.10:54321", accepted["remote_addr"])
|
||||
s.Equal("smoke/1.0", accepted["user_agent"])
|
||||
|
||||
params, ok := accepted["params"].(map[string]any)
|
||||
s.Require().True(ok, "params должны быть объектом")
|
||||
s.Equal("33333333-3333-4333-8333-333333333333", params["path.chat_id"])
|
||||
s.InEpsilon(float64(50), params["query.limit"], 0.0001)
|
||||
|
||||
payload, ok := accepted["payload"].(map[string]any)
|
||||
s.Require().True(ok, "payload должен быть объектом")
|
||||
|
||||
s.False(payload["content_logged"].(bool))
|
||||
s.NotContains(s.sink.String(), "привет")
|
||||
|
||||
s.Equal("request handled", handled["msg"])
|
||||
s.Equal("info", handled["level"])
|
||||
s.Equal("req-42", handled["request_id"])
|
||||
s.Equal("*oas.Message", handled["result"])
|
||||
s.NotEmpty(handled["duration"], "длительность обработки обязательна")
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestLogsFailure() {
|
||||
req := s.request(http.MethodGet, "/api/v1/chats", "")
|
||||
|
||||
wantErr := errors.New("storage unavailable")
|
||||
|
||||
_, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return middleware.Response{}, wantErr
|
||||
})
|
||||
|
||||
s.Require().ErrorIs(err, wantErr)
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 2)
|
||||
|
||||
failed := records[1]
|
||||
s.Equal("request failed", failed["msg"])
|
||||
s.Equal("error", failed["level"])
|
||||
s.Equal("storage unavailable", failed["error"])
|
||||
s.NotEmpty(failed["duration"])
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestOmitsPayloadWhenBodyIsEmpty() {
|
||||
req := s.request(http.MethodGet, "/api/v1/chats", "")
|
||||
|
||||
_, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return middleware.Response{Type: &oas.ChatPage{}}, nil
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
accepted := s.records()[0]
|
||||
s.NotContains(accepted, "payload", "у запроса без тела не должно быть payload")
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestPayloadContentIsNeverLogged() {
|
||||
body := strings.Repeat("s", 4096)
|
||||
req := s.request(http.MethodPost, "/api/v1/chats/33333333-3333-4333-8333-333333333333/messages", body)
|
||||
|
||||
_, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return middleware.Response{Type: &oas.Message{}}, nil
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
payload, ok := s.records()[0]["payload"].(map[string]any)
|
||||
s.Require().True(ok)
|
||||
|
||||
s.InEpsilon(float64(len(body)), payload["size"], 0.0001)
|
||||
s.False(payload["content_logged"].(bool))
|
||||
s.NotContains(s.sink.String(), body)
|
||||
}
|
||||
|
||||
func TestRequestIDMiddlewareSetsHeaderBeforeSecurity(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var seen string
|
||||
|
||||
handler := requestIDMiddleware(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
seen = requestIDFromContext(r.Context())
|
||||
}))
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/live", nil))
|
||||
|
||||
require.NotEmpty(t, seen, "идентификатор должен попадать в контекст")
|
||||
require.Equal(t, seen, rec.Header().Get("X-Request-ID"))
|
||||
}
|
||||
|
||||
func TestRequestIDMiddlewarePreservesIncomingID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
handler := requestIDMiddleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/live", nil)
|
||||
req.Header.Set("X-Request-ID", "from-client")
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, "from-client", rec.Header().Get("X-Request-ID"))
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/ogenregex"
|
||||
)
|
||||
|
||||
var regexMap = map[string]ogenregex.Regexp{
|
||||
"^[a-z0-9_]{3,32}$": ogenregex.MustCompile("^[a-z0-9_]{3,32}$"),
|
||||
}
|
||||
|
||||
type (
|
||||
optionFunc[C any] func(*C)
|
||||
)
|
||||
|
||||
// ErrorHandler is error handler.
|
||||
type ErrorHandler = ogenerrors.ErrorHandler
|
||||
|
||||
type serverConfig struct {
|
||||
NotFound http.HandlerFunc
|
||||
MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)
|
||||
ErrorHandler ErrorHandler
|
||||
Prefix string
|
||||
Middleware Middleware
|
||||
MaxMultipartMemory int64
|
||||
}
|
||||
|
||||
// ServerOption is server config option.
|
||||
type ServerOption interface {
|
||||
applyServer(*serverConfig)
|
||||
}
|
||||
|
||||
var _ ServerOption = (optionFunc[serverConfig])(nil)
|
||||
|
||||
func (o optionFunc[C]) applyServer(c *C) {
|
||||
o(c)
|
||||
}
|
||||
|
||||
func newServerConfig(opts ...ServerOption) serverConfig {
|
||||
cfg := serverConfig{
|
||||
NotFound: http.NotFound,
|
||||
MethodNotAllowed: nil,
|
||||
ErrorHandler: ogenerrors.DefaultErrorHandler,
|
||||
Middleware: nil,
|
||||
MaxMultipartMemory: 32 << 20, // 32 MB
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt.applyServer(&cfg)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
type baseServer struct {
|
||||
cfg serverConfig
|
||||
}
|
||||
|
||||
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
s.cfg.NotFound(w, r)
|
||||
}
|
||||
|
||||
type notAllowedParams struct {
|
||||
allowedMethods string
|
||||
allowedHeaders map[string]string
|
||||
acceptPost string
|
||||
acceptPatch string
|
||||
}
|
||||
|
||||
func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, params notAllowedParams) {
|
||||
h := w.Header()
|
||||
isOptions := r.Method == "OPTIONS"
|
||||
if isOptions {
|
||||
h.Set("Access-Control-Allow-Methods", params.allowedMethods)
|
||||
if params.allowedHeaders != nil {
|
||||
m := r.Header.Get("Access-Control-Request-Method")
|
||||
if m != "" {
|
||||
allowedHeaders, ok := params.allowedHeaders[strings.ToUpper(m)]
|
||||
if ok {
|
||||
h.Set("Access-Control-Allow-Headers", allowedHeaders)
|
||||
}
|
||||
}
|
||||
}
|
||||
if params.acceptPost != "" {
|
||||
h.Set("Accept-Post", params.acceptPost)
|
||||
}
|
||||
if params.acceptPatch != "" {
|
||||
h.Set("Accept-Patch", params.acceptPatch)
|
||||
}
|
||||
}
|
||||
if s.cfg.MethodNotAllowed != nil {
|
||||
s.cfg.MethodNotAllowed(w, r, params.allowedMethods)
|
||||
return
|
||||
}
|
||||
status := http.StatusNoContent
|
||||
if !isOptions {
|
||||
h.Set("Allow", params.allowedMethods)
|
||||
status = http.StatusMethodNotAllowed
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (cfg serverConfig) baseServer() (s baseServer, err error) {
|
||||
s = baseServer{cfg: cfg}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Option is config option.
|
||||
type Option interface {
|
||||
ServerOption
|
||||
}
|
||||
|
||||
// WithNotFound specifies Not Found handler to use.
|
||||
func WithNotFound(notFound http.HandlerFunc) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if notFound != nil {
|
||||
cfg.NotFound = notFound
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMethodNotAllowed specifies Method Not Allowed handler to use.
|
||||
func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if methodNotAllowed != nil {
|
||||
cfg.MethodNotAllowed = methodNotAllowed
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithErrorHandler specifies error handler to use.
|
||||
func WithErrorHandler(h ErrorHandler) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if h != nil {
|
||||
cfg.ErrorHandler = h
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithPathPrefix specifies server path prefix.
|
||||
func WithPathPrefix(prefix string) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
cfg.Prefix = prefix
|
||||
})
|
||||
}
|
||||
|
||||
// WithMiddleware specifies middlewares to use.
|
||||
func WithMiddleware(m ...Middleware) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
switch len(m) {
|
||||
case 0:
|
||||
cfg.Middleware = nil
|
||||
case 1:
|
||||
cfg.Middleware = m[0]
|
||||
default:
|
||||
cfg.Middleware = middleware.ChainMiddlewares(m...)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMaxMultipartMemory specifies limit of memory for storing file parts.
|
||||
// File parts which can't be stored in memory will be stored on disk in temporary files.
|
||||
func WithMaxMultipartMemory(max int64) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if max > 0 {
|
||||
cfg.MaxMultipartMemory = max
|
||||
}
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
package oas
|
||||
|
||||
type CreateChatRes interface {
|
||||
createChatRes()
|
||||
}
|
||||
|
||||
type CreateMessageRes interface {
|
||||
createMessageRes()
|
||||
}
|
||||
|
||||
type CurrentUserRes interface {
|
||||
currentUserRes()
|
||||
}
|
||||
|
||||
type GetChatRes interface {
|
||||
getChatRes()
|
||||
}
|
||||
|
||||
type ListChatsRes interface {
|
||||
listChatsRes()
|
||||
}
|
||||
|
||||
type ListMessagesRes interface {
|
||||
listMessagesRes()
|
||||
}
|
||||
|
||||
type LivenessRes interface {
|
||||
livenessRes()
|
||||
}
|
||||
|
||||
type ReadinessRes interface {
|
||||
readinessRes()
|
||||
}
|
||||
|
||||
type RegisterUserRes interface {
|
||||
registerUserRes()
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
)
|
||||
|
||||
// Middleware is middleware type.
|
||||
type Middleware = middleware.Middleware
|
||||
@@ -0,0 +1,18 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
// OperationName is the ogen operation name
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
CreateChatOperation OperationName = "CreateChat"
|
||||
CreateMessageOperation OperationName = "CreateMessage"
|
||||
CurrentUserOperation OperationName = "CurrentUser"
|
||||
GetChatOperation OperationName = "GetChat"
|
||||
ListChatsOperation OperationName = "ListChats"
|
||||
ListMessagesOperation OperationName = "ListMessages"
|
||||
LivenessOperation OperationName = "Liveness"
|
||||
ReadinessOperation OperationName = "Readiness"
|
||||
RegisterUserOperation OperationName = "RegisterUser"
|
||||
)
|
||||
@@ -0,0 +1,543 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
// CreateMessageParams is parameters of createMessage operation.
|
||||
type CreateMessageParams struct {
|
||||
ChatID uuid.UUID
|
||||
}
|
||||
|
||||
func unpackCreateMessageParams(packed middleware.Parameters) (params CreateMessageParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}
|
||||
params.ChatID = packed[key].(uuid.UUID)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeCreateMessageParams(args [1]string, argsEscaped bool, r *http.Request) (params CreateMessageParams, _ error) {
|
||||
// Decode path: chat_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "chat_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ChatID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetChatParams is parameters of getChat operation.
|
||||
type GetChatParams struct {
|
||||
ChatID uuid.UUID
|
||||
}
|
||||
|
||||
func unpackGetChatParams(packed middleware.Parameters) (params GetChatParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}
|
||||
params.ChatID = packed[key].(uuid.UUID)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetChatParams(args [1]string, argsEscaped bool, r *http.Request) (params GetChatParams, _ error) {
|
||||
// Decode path: chat_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "chat_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ChatID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListChatsParams is parameters of listChats operation.
|
||||
type ListChatsParams struct {
|
||||
Limit OptInt `json:",omitempty,omitzero"`
|
||||
Cursor OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackListChatsParams(packed middleware.Parameters) (params ListChatsParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Limit = v.(OptInt)
|
||||
}
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Cursor = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeListChatsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListChatsParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Set default value for query: limit.
|
||||
{
|
||||
val := int(50)
|
||||
params.Limit.SetTo(val)
|
||||
}
|
||||
// Decode query: limit.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "limit",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotLimitVal int
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotLimitVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Limit.SetTo(paramsDotLimitVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Limit.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 100,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(value)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: cursor.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "cursor",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotCursorVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCursorVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Cursor.SetTo(paramsDotCursorVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Cursor.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 0,
|
||||
MaxLengthSet: false,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListMessagesParams is parameters of listMessages operation.
|
||||
type ListMessagesParams struct {
|
||||
ChatID uuid.UUID
|
||||
Limit OptInt `json:",omitempty,omitzero"`
|
||||
Cursor OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackListMessagesParams(packed middleware.Parameters) (params ListMessagesParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}
|
||||
params.ChatID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Limit = v.(OptInt)
|
||||
}
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Cursor = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeListMessagesParams(args [1]string, argsEscaped bool, r *http.Request) (params ListMessagesParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Decode path: chat_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "chat_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ChatID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Set default value for query: limit.
|
||||
{
|
||||
val := int(50)
|
||||
params.Limit.SetTo(val)
|
||||
}
|
||||
// Decode query: limit.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "limit",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotLimitVal int
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotLimitVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Limit.SetTo(paramsDotLimitVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Limit.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 100,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(value)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: cursor.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "cursor",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotCursorVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCursorVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Cursor.SetTo(paramsDotCursorVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Cursor.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 0,
|
||||
MaxLengthSet: false,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *Server) decodeCreateChatRequest(r *http.Request) (
|
||||
req *CreateChat,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request CreateChat
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateMessageRequest(r *http.Request) (
|
||||
req *CreateMessage,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request CreateMessage
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeRegisterUserRequest(r *http.Request) (
|
||||
req *CreateUser,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request CreateUser
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,647 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
)
|
||||
|
||||
var (
|
||||
rn1AllowedHeaders = map[string]string{
|
||||
"GET": "X-User-Id",
|
||||
"POST": "Content-Type,X-User-Id",
|
||||
}
|
||||
rn3AllowedHeaders = map[string]string{
|
||||
"GET": "X-User-Id",
|
||||
}
|
||||
rn4AllowedHeaders = map[string]string{
|
||||
"GET": "X-User-Id",
|
||||
"POST": "Content-Type,X-User-Id",
|
||||
}
|
||||
rn11AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn6AllowedHeaders = map[string]string{
|
||||
"GET": "X-User-Id",
|
||||
}
|
||||
)
|
||||
|
||||
func (s *Server) cutPrefix(path string) (string, bool) {
|
||||
prefix := s.cfg.Prefix
|
||||
if prefix == "" {
|
||||
return path, true
|
||||
}
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
// Prefix doesn't match.
|
||||
return "", false
|
||||
}
|
||||
// Cut prefix from the path.
|
||||
return strings.TrimPrefix(path, prefix), true
|
||||
}
|
||||
|
||||
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
|
||||
// calling handler that matches the path or returning not found error.
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
elem := r.URL.Path
|
||||
elemIsEscaped := false
|
||||
if rawPath := r.URL.RawPath; rawPath != "" {
|
||||
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||
elem = normalized
|
||||
elemIsEscaped = strings.ContainsRune(elem, '%')
|
||||
}
|
||||
}
|
||||
|
||||
elem, ok := s.cutPrefix(elem)
|
||||
if !ok || len(elem) == 0 {
|
||||
s.notFound(w, r)
|
||||
return
|
||||
}
|
||||
args := [1]string{}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch {
|
||||
default:
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "api/v1/"
|
||||
|
||||
if l := len("api/v1/"); len(elem) >= l && elem[0:l] == "api/v1/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'c': // Prefix: "chats"
|
||||
|
||||
if l := len("chats"); len(elem) >= l && elem[0:l] == "chats" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListChatsRequest([0]string{}, elemIsEscaped, w, r)
|
||||
case "POST":
|
||||
s.handleCreateChatRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,POST",
|
||||
allowedHeaders: rn1AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "chat_id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetChatRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: rn3AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/messages"
|
||||
|
||||
if l := len("/messages"); len(elem) >= l && elem[0:l] == "/messages" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListMessagesRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
case "POST":
|
||||
s.handleCreateMessageRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,POST",
|
||||
allowedHeaders: rn4AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "users"
|
||||
|
||||
if l := len("users"); len(elem) >= l && elem[0:l] == "users" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleRegisterUserRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn11AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/me"
|
||||
|
||||
if l := len("/me"); len(elem) >= l && elem[0:l] == "/me" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleCurrentUserRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: rn6AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'h': // Prefix: "health/"
|
||||
|
||||
if l := len("health/"); len(elem) >= l && elem[0:l] == "health/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'l': // Prefix: "live"
|
||||
|
||||
if l := len("live"); len(elem) >= l && elem[0:l] == "live" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleLivenessRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'r': // Prefix: "ready"
|
||||
|
||||
if l := len("ready"); len(elem) >= l && elem[0:l] == "ready" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleReadinessRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
s.notFound(w, r)
|
||||
}
|
||||
|
||||
// Route is route object.
|
||||
type Route struct {
|
||||
name string
|
||||
summary string
|
||||
operationID string
|
||||
operationGroup string
|
||||
pathPattern string
|
||||
count int
|
||||
args [1]string
|
||||
}
|
||||
|
||||
// Name returns ogen operation name.
|
||||
//
|
||||
// It is guaranteed to be unique and not empty.
|
||||
func (r Route) Name() string {
|
||||
return r.name
|
||||
}
|
||||
|
||||
// Summary returns OpenAPI summary.
|
||||
func (r Route) Summary() string {
|
||||
return r.summary
|
||||
}
|
||||
|
||||
// OperationID returns OpenAPI operationId.
|
||||
func (r Route) OperationID() string {
|
||||
return r.operationID
|
||||
}
|
||||
|
||||
// OperationGroup returns the x-ogen-operation-group value.
|
||||
func (r Route) OperationGroup() string {
|
||||
return r.operationGroup
|
||||
}
|
||||
|
||||
// PathPattern returns OpenAPI path.
|
||||
func (r Route) PathPattern() string {
|
||||
return r.pathPattern
|
||||
}
|
||||
|
||||
// Args returns parsed arguments.
|
||||
func (r Route) Args() []string {
|
||||
return r.args[:r.count]
|
||||
}
|
||||
|
||||
// FindRoute finds Route for given method and path.
|
||||
//
|
||||
// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
|
||||
func (s *Server) FindRoute(method, path string) (Route, bool) {
|
||||
return s.FindPath(method, &url.URL{Path: path})
|
||||
}
|
||||
|
||||
// FindPath finds Route for given method and URL.
|
||||
func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
var (
|
||||
elem = u.Path
|
||||
args = r.args
|
||||
)
|
||||
if rawPath := u.RawPath; rawPath != "" {
|
||||
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||
elem = normalized
|
||||
}
|
||||
defer func() {
|
||||
for i, arg := range r.args[:r.count] {
|
||||
if unescaped, err := url.PathUnescape(arg); err == nil {
|
||||
r.args[i] = unescaped
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
elem, ok := s.cutPrefix(elem)
|
||||
if !ok {
|
||||
return r, false
|
||||
}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch {
|
||||
default:
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "api/v1/"
|
||||
|
||||
if l := len("api/v1/"); len(elem) >= l && elem[0:l] == "api/v1/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'c': // Prefix: "chats"
|
||||
|
||||
if l := len("chats"); len(elem) >= l && elem[0:l] == "chats" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListChatsOperation
|
||||
r.summary = "Чаты текущего пользователя"
|
||||
r.operationID = "listChats"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
case "POST":
|
||||
r.name = CreateChatOperation
|
||||
r.summary = "Создать чат; вызывающий должен входить в member_ids"
|
||||
r.operationID = "createChat"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "chat_id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetChatOperation
|
||||
r.summary = "Получить доступный чат"
|
||||
r.operationID = "getChat"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/messages"
|
||||
|
||||
if l := len("/messages"); len(elem) >= l && elem[0:l] == "/messages" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListMessagesOperation
|
||||
r.summary = "Сообщения по (created_at, id) по возрастанию"
|
||||
r.operationID = "listMessages"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/messages"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
case "POST":
|
||||
r.name = CreateMessageOperation
|
||||
r.summary = "Отправить сообщение"
|
||||
r.operationID = "createMessage"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/messages"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "users"
|
||||
|
||||
if l := len("users"); len(elem) >= l && elem[0:l] == "users" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = RegisterUserOperation
|
||||
r.summary = "Создать пользователя"
|
||||
r.operationID = "registerUser"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/users"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/me"
|
||||
|
||||
if l := len("/me"); len(elem) >= l && elem[0:l] == "/me" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = CurrentUserOperation
|
||||
r.summary = "Текущий пользователь"
|
||||
r.operationID = "currentUser"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/users/me"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'h': // Prefix: "health/"
|
||||
|
||||
if l := len("health/"); len(elem) >= l && elem[0:l] == "health/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'l': // Prefix: "live"
|
||||
|
||||
if l := len("live"); len(elem) >= l && elem[0:l] == "live" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = LivenessOperation
|
||||
r.summary = "Процесс жив"
|
||||
r.operationID = "liveness"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/health/live"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'r': // Prefix: "ready"
|
||||
|
||||
if l := len("ready"); len(elem) >= l && elem[0:l] == "ready" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ReadinessOperation
|
||||
r.summary = "Готов принимать трафик"
|
||||
r.operationID = "readiness"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/health/ready"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return r, false
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,84 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
)
|
||||
|
||||
// SecurityHandler is handler for security parameters.
|
||||
type SecurityHandler interface {
|
||||
// HandleDevUser handles devUser security.
|
||||
// Только учебная lab1: существующий UUID. Не является
|
||||
// аутентификацией.
|
||||
HandleDevUser(ctx context.Context, operationName OperationName, t DevUser) (context.Context, error)
|
||||
}
|
||||
|
||||
func findAuthorization(h http.Header, prefix string) (string, bool) {
|
||||
v, ok := h["Authorization"]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
for _, vv := range v {
|
||||
scheme, value, ok := strings.Cut(vv, " ")
|
||||
if !ok || !strings.EqualFold(scheme, prefix) {
|
||||
continue
|
||||
}
|
||||
return value, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// operationRolesDevUser is a private map storing roles per operation.
|
||||
var operationRolesDevUser = map[string][]string{
|
||||
CreateChatOperation: []string{},
|
||||
CreateMessageOperation: []string{},
|
||||
CurrentUserOperation: []string{},
|
||||
GetChatOperation: []string{},
|
||||
ListChatsOperation: []string{},
|
||||
ListMessagesOperation: []string{},
|
||||
}
|
||||
|
||||
// GetRolesForDevUser returns the required roles for the given operation.
|
||||
//
|
||||
// This is useful for authorization scenarios where you need to know which roles
|
||||
// are required for an operation.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// requiredRoles := GetRolesForDevUser(AddPetOperation)
|
||||
//
|
||||
// Returns nil if the operation has no role requirements or if the operation is unknown.
|
||||
func GetRolesForDevUser(operation string) []string {
|
||||
roles, ok := operationRolesDevUser[operation]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// Return a copy to prevent external modification
|
||||
result := make([]string, len(roles))
|
||||
copy(result, roles)
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Server) securityDevUser(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
|
||||
var t DevUser
|
||||
const parameterName = "X-User-Id"
|
||||
value := req.Header.Get(parameterName)
|
||||
if value == "" {
|
||||
return ctx, false, nil
|
||||
}
|
||||
t.APIKey = value
|
||||
t.Roles = operationRolesDevUser[operationName]
|
||||
rctx, err := s.sec.HandleDevUser(ctx, operationName, t)
|
||||
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
|
||||
return nil, false, nil
|
||||
} else if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return rctx, true, err
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Handler handles operations described by OpenAPI v3 specification.
|
||||
type Handler interface {
|
||||
// CreateChat implements createChat operation.
|
||||
//
|
||||
// Создать чат; вызывающий должен входить в member_ids.
|
||||
//
|
||||
// POST /api/v1/chats
|
||||
CreateChat(ctx context.Context, req *CreateChat) (CreateChatRes, error)
|
||||
// CreateMessage implements createMessage operation.
|
||||
//
|
||||
// Отправить сообщение.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/messages
|
||||
CreateMessage(ctx context.Context, req *CreateMessage, params CreateMessageParams) (CreateMessageRes, error)
|
||||
// CurrentUser implements currentUser operation.
|
||||
//
|
||||
// Текущий пользователь.
|
||||
//
|
||||
// GET /api/v1/users/me
|
||||
CurrentUser(ctx context.Context) (CurrentUserRes, error)
|
||||
// GetChat implements getChat operation.
|
||||
//
|
||||
// Получить доступный чат.
|
||||
//
|
||||
// GET /api/v1/chats/{chat_id}
|
||||
GetChat(ctx context.Context, params GetChatParams) (GetChatRes, error)
|
||||
// ListChats implements listChats operation.
|
||||
//
|
||||
// Чаты текущего пользователя.
|
||||
//
|
||||
// GET /api/v1/chats
|
||||
ListChats(ctx context.Context, params ListChatsParams) (ListChatsRes, error)
|
||||
// ListMessages implements listMessages operation.
|
||||
//
|
||||
// Сообщения по (created_at, id) по возрастанию.
|
||||
//
|
||||
// GET /api/v1/chats/{chat_id}/messages
|
||||
ListMessages(ctx context.Context, params ListMessagesParams) (ListMessagesRes, error)
|
||||
// Liveness implements liveness operation.
|
||||
//
|
||||
// Процесс жив.
|
||||
//
|
||||
// GET /health/live
|
||||
Liveness(ctx context.Context) (LivenessRes, error)
|
||||
// Readiness implements readiness operation.
|
||||
//
|
||||
// Готов принимать трафик.
|
||||
//
|
||||
// GET /health/ready
|
||||
Readiness(ctx context.Context) (ReadinessRes, error)
|
||||
// RegisterUser implements registerUser operation.
|
||||
//
|
||||
// Создать пользователя.
|
||||
//
|
||||
// POST /api/v1/users
|
||||
RegisterUser(ctx context.Context, req *CreateUser) (RegisterUserRes, error)
|
||||
}
|
||||
|
||||
// Server implements http server based on OpenAPI v3 specification and
|
||||
// calls Handler to handle requests.
|
||||
type Server struct {
|
||||
h Handler
|
||||
sec SecurityHandler
|
||||
baseServer
|
||||
}
|
||||
|
||||
// NewServer creates new Server.
|
||||
func NewServer(h Handler, sec SecurityHandler, opts ...ServerOption) (*Server, error) {
|
||||
s, err := newServerConfig(opts...).baseServer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Server{
|
||||
h: h,
|
||||
sec: sec,
|
||||
baseServer: s,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
)
|
||||
|
||||
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
|
||||
type UnimplementedHandler struct{}
|
||||
|
||||
var _ Handler = UnimplementedHandler{}
|
||||
|
||||
// CreateChat implements createChat operation.
|
||||
//
|
||||
// Создать чат; вызывающий должен входить в member_ids.
|
||||
//
|
||||
// POST /api/v1/chats
|
||||
func (UnimplementedHandler) CreateChat(ctx context.Context, req *CreateChat) (r CreateChatRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateMessage implements createMessage operation.
|
||||
//
|
||||
// Отправить сообщение.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/messages
|
||||
func (UnimplementedHandler) CreateMessage(ctx context.Context, req *CreateMessage, params CreateMessageParams) (r CreateMessageRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CurrentUser implements currentUser operation.
|
||||
//
|
||||
// Текущий пользователь.
|
||||
//
|
||||
// GET /api/v1/users/me
|
||||
func (UnimplementedHandler) CurrentUser(ctx context.Context) (r CurrentUserRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetChat implements getChat operation.
|
||||
//
|
||||
// Получить доступный чат.
|
||||
//
|
||||
// GET /api/v1/chats/{chat_id}
|
||||
func (UnimplementedHandler) GetChat(ctx context.Context, params GetChatParams) (r GetChatRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListChats implements listChats operation.
|
||||
//
|
||||
// Чаты текущего пользователя.
|
||||
//
|
||||
// GET /api/v1/chats
|
||||
func (UnimplementedHandler) ListChats(ctx context.Context, params ListChatsParams) (r ListChatsRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMessages implements listMessages operation.
|
||||
//
|
||||
// Сообщения по (created_at, id) по возрастанию.
|
||||
//
|
||||
// GET /api/v1/chats/{chat_id}/messages
|
||||
func (UnimplementedHandler) ListMessages(ctx context.Context, params ListMessagesParams) (r ListMessagesRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// Liveness implements liveness operation.
|
||||
//
|
||||
// Процесс жив.
|
||||
//
|
||||
// GET /health/live
|
||||
func (UnimplementedHandler) Liveness(ctx context.Context) (r LivenessRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// Readiness implements readiness operation.
|
||||
//
|
||||
// Готов принимать трафик.
|
||||
//
|
||||
// GET /health/ready
|
||||
func (UnimplementedHandler) Readiness(ctx context.Context) (r ReadinessRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// RegisterUser implements registerUser operation.
|
||||
//
|
||||
// Создать пользователя.
|
||||
//
|
||||
// POST /api/v1/users
|
||||
func (UnimplementedHandler) RegisterUser(ctx context.Context, req *CreateUser) (r RegisterUserRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,35 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const requestIDHeader = "X-Request-ID"
|
||||
|
||||
type requestIDKey struct{}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
id, _ := ctx.Value(requestIDKey{}).(string)
|
||||
|
||||
return id
|
||||
}
|
||||
|
||||
func withRequestID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey{}, id)
|
||||
}
|
||||
|
||||
func requestIDMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get(requestIDHeader)
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set(requestIDHeader, id)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(withRequestID(r.Context(), id)))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"mtusi-messenger/internal/transport/rest/oas"
|
||||
)
|
||||
|
||||
func NewRouter(
|
||||
handler oas.Handler,
|
||||
security oas.SecurityHandler,
|
||||
log *slog.Logger,
|
||||
) (http.Handler, error) {
|
||||
server, err := oas.NewServer(
|
||||
handler,
|
||||
security,
|
||||
oas.WithErrorHandler(newErrorHandler(log)),
|
||||
oas.WithNotFound(newNotFoundHandler(log)),
|
||||
oas.WithMethodNotAllowed(newMethodNotAllowedHandler(log)),
|
||||
oas.WithMiddleware(loggingMiddleware(log)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return requestIDMiddleware(server), nil
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/service/chat"
|
||||
"mtusi-messenger/internal/service/message"
|
||||
"mtusi-messenger/internal/service/user"
|
||||
"mtusi-messenger/internal/storage/memory"
|
||||
)
|
||||
|
||||
const userIDHeader = "X-User-Id"
|
||||
|
||||
type response struct {
|
||||
status int
|
||||
header http.Header
|
||||
body []byte
|
||||
}
|
||||
|
||||
type RouterSuite struct {
|
||||
suite.Suite
|
||||
|
||||
sink *strings.Builder
|
||||
log *slog.Logger
|
||||
server *httptest.Server
|
||||
}
|
||||
|
||||
func TestRouterSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(RouterSuite))
|
||||
}
|
||||
|
||||
func (s *RouterSuite) SetupTest() {
|
||||
s.sink = &strings.Builder{}
|
||||
s.log = logger.New(logger.WithWriter(s.sink), logger.WithLevel(slog.LevelDebug))
|
||||
|
||||
store := memory.NewStore()
|
||||
userService := user.NewService(store.Users())
|
||||
|
||||
router, err := NewRouter(
|
||||
NewHandler(
|
||||
userService,
|
||||
chat.NewService(store.Chats()),
|
||||
message.NewService(store.Messages()),
|
||||
),
|
||||
NewSecurityHandler(userService),
|
||||
s.log,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.server = httptest.NewServer(router)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TearDownTest() {
|
||||
s.server.Close()
|
||||
}
|
||||
|
||||
func (s *RouterSuite) do(method, path string, headers map[string]string) response {
|
||||
s.T().Helper()
|
||||
|
||||
return s.send(method, path, nil, headers)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) send(method, path string, body any, headers map[string]string) response {
|
||||
s.T().Helper()
|
||||
|
||||
if body == nil {
|
||||
return s.sendRaw(method, path, nil, headers)
|
||||
}
|
||||
|
||||
raw, err := json.Marshal(body)
|
||||
s.Require().NoError(err)
|
||||
|
||||
return s.sendRaw(method, path, raw, headers)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) sendRaw(method, path string, body []byte, headers map[string]string) response {
|
||||
s.T().Helper()
|
||||
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
reader = bytes.NewReader(body)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(s.T().Context(), method, s.server.URL+path, reader)
|
||||
s.Require().NoError(err)
|
||||
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
for key, value := range headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
resp, err := s.server.Client().Do(req)
|
||||
s.Require().NoError(err)
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
payload, err := io.ReadAll(resp.Body)
|
||||
s.Require().NoError(err)
|
||||
|
||||
return response{status: resp.StatusCode, header: resp.Header, body: payload}
|
||||
}
|
||||
|
||||
func (s *RouterSuite) records() []map[string]any {
|
||||
s.T().Helper()
|
||||
|
||||
var out []map[string]any
|
||||
|
||||
for line := range strings.SplitSeq(strings.TrimSpace(s.sink.String()), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var record map[string]any
|
||||
s.Require().NoError(json.Unmarshal([]byte(line), &record))
|
||||
|
||||
out = append(out, record)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *RouterSuite) lastRecord() map[string]any {
|
||||
s.T().Helper()
|
||||
|
||||
records := s.records()
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
return records[len(records)-1]
|
||||
}
|
||||
|
||||
func (s *RouterSuite) decodeError(resp response) map[string]any {
|
||||
s.T().Helper()
|
||||
|
||||
var body struct {
|
||||
Error map[string]any `json:"error"`
|
||||
}
|
||||
|
||||
s.Require().NoError(json.Unmarshal(resp.body, &body))
|
||||
s.Require().NotEmpty(body.Error)
|
||||
|
||||
return body.Error
|
||||
}
|
||||
|
||||
func (s *RouterSuite) decode(resp response) map[string]any {
|
||||
s.T().Helper()
|
||||
|
||||
var body map[string]any
|
||||
s.Require().NoError(json.Unmarshal(resp.body, &body))
|
||||
|
||||
return body
|
||||
}
|
||||
|
||||
func (s *RouterSuite) register(username string) map[string]any {
|
||||
s.T().Helper()
|
||||
|
||||
resp := s.send(http.MethodPost, "/api/v1/users", map[string]string{
|
||||
"username": username,
|
||||
"display_name": "Пользователь " + username,
|
||||
}, nil)
|
||||
s.Require().Equal(http.StatusCreated, resp.status, string(resp.body))
|
||||
|
||||
return s.decode(resp)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) actor(user map[string]any) map[string]string {
|
||||
s.T().Helper()
|
||||
|
||||
id, ok := user["id"].(string)
|
||||
s.Require().True(ok)
|
||||
|
||||
return map[string]string{userIDHeader: id}
|
||||
}
|
||||
|
||||
func (s *RouterSuite) createChat(owner map[string]any, members ...string) map[string]any {
|
||||
s.T().Helper()
|
||||
|
||||
resp := s.send(http.MethodPost, "/api/v1/chats", map[string]any{
|
||||
"title": "Контрактный чат",
|
||||
"member_ids": members,
|
||||
}, s.actor(owner))
|
||||
s.Require().Equal(http.StatusCreated, resp.status, string(resp.body))
|
||||
|
||||
return s.decode(resp)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) id(object map[string]any) string {
|
||||
s.T().Helper()
|
||||
|
||||
value, ok := object["id"].(string)
|
||||
s.Require().True(ok)
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestHealthLive() {
|
||||
resp := s.do(http.MethodGet, "/health/live", nil)
|
||||
|
||||
s.Equal(http.StatusOK, resp.status)
|
||||
s.NotEmpty(resp.header.Get(requestIDHeader))
|
||||
s.JSONEq(`{"status":"ok"}`, string(resp.body))
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestHealthReady() {
|
||||
resp := s.do(http.MethodGet, "/health/ready", nil)
|
||||
|
||||
s.Equal(http.StatusOK, resp.status)
|
||||
s.NotEmpty(resp.header.Get(requestIDHeader))
|
||||
s.JSONEq(`{"status":"ok"}`, string(resp.body))
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestRequestIDEchoedFromClient() {
|
||||
resp := s.do(http.MethodGet, "/health/live", map[string]string{
|
||||
requestIDHeader: "from-client",
|
||||
})
|
||||
|
||||
s.Equal("from-client", resp.header.Get(requestIDHeader))
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestUnauthorizedIsLoggedWithoutStacktrace() {
|
||||
resp := s.do(http.MethodGet, "/api/v1/chats", nil)
|
||||
|
||||
s.Equal(http.StatusUnauthorized, resp.status)
|
||||
|
||||
body := s.decodeError(resp)
|
||||
s.Equal("unauthorized", body["code"])
|
||||
s.Equal(resp.header.Get(requestIDHeader), body["request_id"])
|
||||
s.NotEmpty(body["message"])
|
||||
|
||||
record := s.lastRecord()
|
||||
s.Equal("request rejected", record["msg"])
|
||||
s.Equal("warn", record["level"])
|
||||
s.InEpsilon(float64(http.StatusUnauthorized), record["status"], 0.0001)
|
||||
s.NotEmpty(record["request_id"])
|
||||
s.NotContains(record, "stacktrace", "ожидаемый отказ не должен печатать стек")
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestNotFoundReturnsContractError() {
|
||||
resp := s.do(http.MethodGet, "/nope", nil)
|
||||
|
||||
s.Equal(http.StatusNotFound, resp.status)
|
||||
s.Equal("application/json; charset=utf-8", resp.header.Get("Content-Type"))
|
||||
|
||||
body := s.decodeError(resp)
|
||||
s.Equal("not_found", body["code"])
|
||||
s.Equal(resp.header.Get(requestIDHeader), body["request_id"])
|
||||
|
||||
record := s.lastRecord()
|
||||
s.Equal("request rejected", record["msg"])
|
||||
s.Equal("warn", record["level"])
|
||||
s.InEpsilon(float64(http.StatusNotFound), record["status"], 0.0001)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestMethodNotAllowedReturnsContractError() {
|
||||
resp := s.do(http.MethodDelete, "/health/live", nil)
|
||||
|
||||
s.Equal(http.StatusMethodNotAllowed, resp.status)
|
||||
s.Equal(http.MethodGet, resp.header.Get("Allow"))
|
||||
|
||||
body := s.decodeError(resp)
|
||||
s.Equal("invalid_request", body["code"])
|
||||
|
||||
record := s.lastRecord()
|
||||
s.Equal("request rejected", record["msg"])
|
||||
s.InEpsilon(float64(http.StatusMethodNotAllowed), record["status"], 0.0001)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestMalformedUserIDIsRejected() {
|
||||
resp := s.do(http.MethodGet, "/api/v1/chats", map[string]string{
|
||||
userIDHeader: "not-a-uuid",
|
||||
})
|
||||
|
||||
s.Equal(http.StatusUnauthorized, resp.status)
|
||||
s.Equal("unauthorized", s.decodeError(resp)["code"])
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestUnknownUserIDIsRejected() {
|
||||
resp := s.do(http.MethodGet, "/api/v1/chats", map[string]string{
|
||||
userIDHeader: "11111111-1111-4111-8111-111111111111",
|
||||
})
|
||||
|
||||
s.Equal(http.StatusUnauthorized, resp.status,
|
||||
"неизвестный пользователь не проходит идентификацию lab1")
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestRegisterUserReturnsContractShape() {
|
||||
resp := s.send(http.MethodPost, "/api/v1/users", map[string]string{
|
||||
"username": "alice",
|
||||
"display_name": "Алиса",
|
||||
}, nil)
|
||||
|
||||
s.Require().Equal(http.StatusCreated, resp.status)
|
||||
|
||||
body := s.decode(resp)
|
||||
s.Equal("alice", body["username"])
|
||||
s.Equal("Алиса", body["display_name"])
|
||||
s.NotEmpty(body["id"])
|
||||
s.NotEmpty(body["created_at"])
|
||||
s.Len(body, 4, "User не содержит лишних полей")
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestDuplicateUsernameConflicts() {
|
||||
s.register("alice")
|
||||
|
||||
resp := s.send(http.MethodPost, "/api/v1/users", map[string]string{
|
||||
"username": "alice",
|
||||
"display_name": "Другая Алиса",
|
||||
}, nil)
|
||||
|
||||
s.Equal(http.StatusConflict, resp.status)
|
||||
s.Equal("conflict", s.decodeError(resp)["code"])
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestRegisterRejectsInvalidPayload() {
|
||||
tests := map[string]map[string]string{
|
||||
"username в верхнем регистре": {"username": "Alice", "display_name": "Алиса"},
|
||||
"слишком короткий username": {"username": "ab", "display_name": "Алиса"},
|
||||
"пробельный display_name": {"username": "alice", "display_name": " "},
|
||||
}
|
||||
|
||||
for name, payload := range tests {
|
||||
s.Run(name, func() {
|
||||
resp := s.send(http.MethodPost, "/api/v1/users", payload, nil)
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status)
|
||||
s.Equal("invalid_request", s.decodeError(resp)["code"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Контракт: "JSON с лишними полями или неверными типами — 400; malformed JSON также 400".
|
||||
// Проверку выполняет сгенерированный слой, поэтому тест фиксирует границу, а не домен.
|
||||
func (s *RouterSuite) TestRegisterRejectsMalformedBody() {
|
||||
tests := map[string]string{
|
||||
"лишнее поле": `{"username":"alice","display_name":"Алиса","is_admin":true}`,
|
||||
"неверный тип": `{"username":"alice","display_name":42}`,
|
||||
"битый json": `{"username":"alice",`,
|
||||
"не объект": `"alice"`,
|
||||
"пропущено поле": `{"username":"alice"}`,
|
||||
}
|
||||
|
||||
for name, body := range tests {
|
||||
s.Run(name, func() {
|
||||
resp := s.sendRaw(http.MethodPost, "/api/v1/users", []byte(body), nil)
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status)
|
||||
s.Equal("invalid_request", s.decodeError(resp)["code"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestCurrentUser() {
|
||||
alice := s.register("alice")
|
||||
|
||||
resp := s.do(http.MethodGet, "/api/v1/users/me", s.actor(alice))
|
||||
|
||||
s.Require().Equal(http.StatusOK, resp.status)
|
||||
s.Equal(alice, s.decode(resp))
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestCreateChatRequiresCallerAsMember() {
|
||||
alice := s.register("alice")
|
||||
bob := s.register("bob")
|
||||
|
||||
resp := s.send(http.MethodPost, "/api/v1/chats", map[string]any{
|
||||
"title": "Без создателя",
|
||||
"member_ids": []string{s.id(bob)},
|
||||
}, s.actor(alice))
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status)
|
||||
s.Equal("invalid_request", s.decodeError(resp)["code"])
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestCreateChatRejectsUnknownMember() {
|
||||
alice := s.register("alice")
|
||||
|
||||
resp := s.send(http.MethodPost, "/api/v1/chats", map[string]any{
|
||||
"title": "Неизвестный участник",
|
||||
"member_ids": []string{s.id(alice), "11111111-1111-4111-8111-111111111111"},
|
||||
}, s.actor(alice))
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestCreateChatRejectsDuplicateMembers() {
|
||||
alice := s.register("alice")
|
||||
|
||||
resp := s.send(http.MethodPost, "/api/v1/chats", map[string]any{
|
||||
"title": "Дубликаты",
|
||||
"member_ids": []string{s.id(alice), s.id(alice)},
|
||||
}, s.actor(alice))
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestChatIsHiddenFromOutsider() {
|
||||
alice := s.register("alice")
|
||||
bob := s.register("bob")
|
||||
eve := s.register("eve")
|
||||
|
||||
chat := s.createChat(alice, s.id(alice), s.id(bob))
|
||||
|
||||
resp := s.do(http.MethodGet, "/api/v1/chats/"+s.id(chat), s.actor(eve))
|
||||
s.Equal(http.StatusNotFound, resp.status, "посторонний получает 404, а не 403")
|
||||
|
||||
resp = s.do(http.MethodGet, "/api/v1/chats/"+s.id(chat), s.actor(bob))
|
||||
s.Equal(http.StatusOK, resp.status, "участник читает чат")
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestListChatsShowsOnlyVisibleChats() {
|
||||
alice := s.register("alice")
|
||||
bob := s.register("bob")
|
||||
eve := s.register("eve")
|
||||
|
||||
chat := s.createChat(alice, s.id(alice), s.id(bob))
|
||||
|
||||
resp := s.do(http.MethodGet, "/api/v1/chats", s.actor(bob))
|
||||
s.Require().Equal(http.StatusOK, resp.status)
|
||||
|
||||
body := s.decode(resp)
|
||||
items, ok := body["items"].([]any)
|
||||
s.Require().True(ok)
|
||||
s.Require().Len(items, 1)
|
||||
s.Nil(body["next_cursor"])
|
||||
|
||||
first, ok := items[0].(map[string]any)
|
||||
s.Require().True(ok)
|
||||
s.Equal(s.id(chat), first["id"])
|
||||
|
||||
resp = s.do(http.MethodGet, "/api/v1/chats", s.actor(eve))
|
||||
s.Require().Equal(http.StatusOK, resp.status)
|
||||
|
||||
body = s.decode(resp)
|
||||
items, ok = body["items"].([]any)
|
||||
s.Require().True(ok)
|
||||
s.Empty(items, "чужой чат не попадает в список")
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestSenderIsDerivedFromIdentity() {
|
||||
alice := s.register("alice")
|
||||
bob := s.register("bob")
|
||||
chat := s.createChat(alice, s.id(alice), s.id(bob))
|
||||
|
||||
resp := s.send(http.MethodPost, "/api/v1/chats/"+s.id(chat)+"/messages", map[string]any{
|
||||
"text": "Привет, мир 👋",
|
||||
"sender_id": s.id(bob),
|
||||
}, s.actor(alice))
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status, "sender_id в запросе не принимается")
|
||||
|
||||
resp = s.send(http.MethodPost, "/api/v1/chats/"+s.id(chat)+"/messages", map[string]any{
|
||||
"text": "Привет, мир 👋",
|
||||
}, s.actor(alice))
|
||||
|
||||
s.Require().Equal(http.StatusCreated, resp.status)
|
||||
|
||||
body := s.decode(resp)
|
||||
s.Equal(s.id(alice), body["sender_id"])
|
||||
s.Equal(s.id(chat), body["chat_id"])
|
||||
s.Equal("Привет, мир 👋", body["text"])
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestMessageTextValidation() {
|
||||
alice := s.register("alice")
|
||||
chat := s.createChat(alice, s.id(alice))
|
||||
path := "/api/v1/chats/" + s.id(chat) + "/messages"
|
||||
|
||||
tests := map[string]string{
|
||||
"пустой текст": "",
|
||||
"пробельный текст": " ",
|
||||
"слишком длинный": strings.Repeat("я", 4001),
|
||||
}
|
||||
|
||||
for name, text := range tests {
|
||||
s.Run(name, func() {
|
||||
resp := s.send(http.MethodPost, path, map[string]any{"text": text}, s.actor(alice))
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status)
|
||||
s.Equal("invalid_request", s.decodeError(resp)["code"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestOutsiderCannotUseChat() {
|
||||
alice := s.register("alice")
|
||||
eve := s.register("eve")
|
||||
chat := s.createChat(alice, s.id(alice))
|
||||
path := "/api/v1/chats/" + s.id(chat) + "/messages"
|
||||
|
||||
resp := s.send(http.MethodPost, path, map[string]any{"text": "чужое"}, s.actor(eve))
|
||||
s.Equal(http.StatusNotFound, resp.status)
|
||||
|
||||
resp = s.do(http.MethodGet, path, s.actor(eve))
|
||||
s.Equal(http.StatusNotFound, resp.status)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestHistoryPaginationDoesNotRepeatItems() {
|
||||
alice := s.register("alice")
|
||||
chat := s.createChat(alice, s.id(alice))
|
||||
path := "/api/v1/chats/" + s.id(chat) + "/messages"
|
||||
|
||||
const total = 5
|
||||
|
||||
for range total {
|
||||
resp := s.send(http.MethodPost, path, map[string]any{"text": "сообщение"}, s.actor(alice))
|
||||
s.Require().Equal(http.StatusCreated, resp.status)
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, total)
|
||||
cursor := ""
|
||||
|
||||
for {
|
||||
query := path + "?limit=2"
|
||||
if cursor != "" {
|
||||
query += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
resp := s.do(http.MethodGet, query, s.actor(alice))
|
||||
s.Require().Equal(http.StatusOK, resp.status)
|
||||
|
||||
body := s.decode(resp)
|
||||
items, ok := body["items"].([]any)
|
||||
s.Require().True(ok)
|
||||
|
||||
for _, item := range items {
|
||||
message, ok := item.(map[string]any)
|
||||
s.Require().True(ok)
|
||||
|
||||
id, ok := message["id"].(string)
|
||||
s.Require().True(ok)
|
||||
|
||||
_, duplicate := seen[id]
|
||||
s.Require().False(duplicate, "страницы не повторяют сообщения")
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
next, ok := body["next_cursor"].(string)
|
||||
if !ok {
|
||||
s.Nil(body["next_cursor"])
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
cursor = next
|
||||
}
|
||||
|
||||
s.Len(seen, total)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestCursorFromAnotherChatIsRejected() {
|
||||
alice := s.register("alice")
|
||||
first := s.createChat(alice, s.id(alice))
|
||||
second := s.createChat(alice, s.id(alice))
|
||||
|
||||
firstPath := "/api/v1/chats/" + s.id(first) + "/messages"
|
||||
|
||||
for range 2 {
|
||||
resp := s.send(http.MethodPost, firstPath, map[string]any{"text": "сообщение"}, s.actor(alice))
|
||||
s.Require().Equal(http.StatusCreated, resp.status)
|
||||
}
|
||||
|
||||
resp := s.do(http.MethodGet, firstPath+"?limit=1", s.actor(alice))
|
||||
s.Require().Equal(http.StatusOK, resp.status)
|
||||
|
||||
cursor, ok := s.decode(resp)["next_cursor"].(string)
|
||||
s.Require().True(ok)
|
||||
|
||||
resp = s.do(
|
||||
http.MethodGet,
|
||||
"/api/v1/chats/"+s.id(second)+"/messages?cursor="+url.QueryEscape(cursor),
|
||||
s.actor(alice),
|
||||
)
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status, "cursor привязан к чату")
|
||||
s.Equal("invalid_request", s.decodeError(resp)["code"])
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestInvalidCursorIsRejected() {
|
||||
alice := s.register("alice")
|
||||
chat := s.createChat(alice, s.id(alice))
|
||||
|
||||
resp := s.do(
|
||||
http.MethodGet,
|
||||
"/api/v1/chats/"+s.id(chat)+"/messages?cursor=not-a-cursor",
|
||||
s.actor(alice),
|
||||
)
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status)
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestLimitOutOfRangeIsRejected() {
|
||||
alice := s.register("alice")
|
||||
chat := s.createChat(alice, s.id(alice))
|
||||
|
||||
for _, limit := range []string{"0", "101"} {
|
||||
resp := s.do(
|
||||
http.MethodGet,
|
||||
"/api/v1/chats/"+s.id(chat)+"/messages?limit="+limit,
|
||||
s.actor(alice),
|
||||
)
|
||||
|
||||
s.Equal(http.StatusBadRequest, resp.status)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestEmptyHistoryReturnsEmptyItems() {
|
||||
alice := s.register("alice")
|
||||
chat := s.createChat(alice, s.id(alice))
|
||||
|
||||
resp := s.do(http.MethodGet, "/api/v1/chats/"+s.id(chat)+"/messages", s.actor(alice))
|
||||
|
||||
s.Require().Equal(http.StatusOK, resp.status)
|
||||
s.JSONEq(`{"items":[],"next_cursor":null}`, string(resp.body))
|
||||
}
|
||||
|
||||
func (s *RouterSuite) TestSuccessfulRequestIsLogged() {
|
||||
alice := s.register("alice")
|
||||
|
||||
s.sink.Reset()
|
||||
|
||||
resp := s.do(http.MethodGet, "/api/v1/users/me", s.actor(alice))
|
||||
s.Require().Equal(http.StatusOK, resp.status)
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 2)
|
||||
s.Equal("request accepted", records[0]["msg"])
|
||||
s.Equal("request handled", records[1]["msg"])
|
||||
s.NotEmpty(records[1]["duration"])
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/transport/rest/oas"
|
||||
)
|
||||
|
||||
var ErrUnauthenticated = errors.New("caller is not identified")
|
||||
|
||||
type callerKey struct{}
|
||||
|
||||
func CallerFromContext(ctx context.Context) (uuid.UUID, bool) {
|
||||
id, ok := ctx.Value(callerKey{}).(uuid.UUID)
|
||||
|
||||
return id, ok
|
||||
}
|
||||
|
||||
func caller(ctx context.Context) uuid.UUID {
|
||||
id, _ := CallerFromContext(ctx)
|
||||
|
||||
return id
|
||||
}
|
||||
|
||||
type UserLookup interface {
|
||||
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||
}
|
||||
|
||||
type SecurityHandler struct {
|
||||
users UserLookup
|
||||
}
|
||||
|
||||
func NewSecurityHandler(users UserLookup) *SecurityHandler {
|
||||
return &SecurityHandler{users: users}
|
||||
}
|
||||
|
||||
func (h *SecurityHandler) HandleDevUser(
|
||||
ctx context.Context,
|
||||
_ oas.OperationName,
|
||||
t oas.DevUser,
|
||||
) (context.Context, error) {
|
||||
id, err := uuid.Parse(t.APIKey)
|
||||
if err != nil {
|
||||
return ctx, ErrUnauthenticated
|
||||
}
|
||||
|
||||
if _, err := h.users.GetByID(ctx, id); err != nil {
|
||||
return ctx, ErrUnauthenticated
|
||||
}
|
||||
|
||||
return context.WithValue(ctx, callerKey{}, id), nil
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def request(base_url, method, path, body=None, user_id=None):
|
||||
payload = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
|
||||
headers = {"Content-Type": "application/json"} if payload else {}
|
||||
if user_id:
|
||||
headers["X-User-Id"] = user_id
|
||||
request = urllib.request.Request(
|
||||
base_url + path,
|
||||
data=payload,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=3) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def wait_ready(base_url):
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
request(base_url, "GET", "/health/live")
|
||||
return
|
||||
except OSError:
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("container did not become ready")
|
||||
|
||||
|
||||
def process_alive(container):
|
||||
result = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{.State.Running}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return result.stdout.strip() == "true"
|
||||
|
||||
|
||||
def sample_stats(container, samples, stop):
|
||||
while not stop.is_set():
|
||||
result = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{json .}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
try:
|
||||
value = json.loads(result.stdout)
|
||||
memory = value.get("MemUsage", "").split("/")[0].strip()
|
||||
if memory == "0B" or not process_alive(container):
|
||||
continue
|
||||
samples.append({
|
||||
"time_seconds": time.monotonic(),
|
||||
"memory": memory,
|
||||
"memory_mib": parse_memory(memory),
|
||||
})
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
stop.wait(0.1)
|
||||
|
||||
|
||||
def parse_memory(value):
|
||||
units = {"B": 1 / 1024 / 1024, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}
|
||||
for unit, factor in sorted(units.items(), key=lambda item: -len(item[0])):
|
||||
if value.endswith(unit):
|
||||
return float(value[:-len(unit)].strip()) * factor
|
||||
raise ValueError(value)
|
||||
|
||||
|
||||
def make_plot(data, output):
|
||||
samples = [sample for sample in data["memory_samples"] if sample["memory_mib"] > 0]
|
||||
start = samples[0]["time_seconds"] if samples else 0
|
||||
x = [sample["time_seconds"] - start for sample in samples]
|
||||
memory = [sample["memory_mib"] for sample in samples]
|
||||
|
||||
fig, memory_axis = plt.subplots(figsize=(11, 6))
|
||||
memory_axis.plot(x, memory, color="tab:red", label="RSS / container memory")
|
||||
memory_axis.axhline(data["memory_limit_mib"], color="black", linestyle="--", label="memory limit")
|
||||
memory_axis.set_xlabel("Time, seconds")
|
||||
memory_axis.set_ylabel("Memory, MiB")
|
||||
memory_axis.grid(True, alpha=0.25)
|
||||
|
||||
message_axis = memory_axis.twinx()
|
||||
message_axis.plot(
|
||||
data["message_points_x"],
|
||||
data["message_points_y"],
|
||||
color="tab:blue",
|
||||
label="successful messages",
|
||||
)
|
||||
message_axis.set_ylabel("Successful messages")
|
||||
|
||||
lines, labels = memory_axis.get_legend_handles_labels()
|
||||
other_lines, other_labels = message_axis.get_legend_handles_labels()
|
||||
memory_axis.legend(lines + other_lines, labels + other_labels, loc="upper left")
|
||||
memory_axis.set_title("In-memory messenger: memory exhaustion point")
|
||||
if data["oom_killed"] and data["failure_time_seconds"] is not None:
|
||||
memory_axis.axvline(
|
||||
data["failure_time_seconds"],
|
||||
color="tab:purple",
|
||||
linestyle=":",
|
||||
label="container OOMKilled",
|
||||
)
|
||||
memory_axis.annotate(
|
||||
"OOMKilled",
|
||||
(data["failure_time_seconds"], data["memory_limit_mib"]),
|
||||
xytext=(8, -18),
|
||||
textcoords="offset points",
|
||||
color="tab:purple",
|
||||
)
|
||||
fig.tight_layout()
|
||||
fig.savefig(output, dpi=160)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--image", required=True)
|
||||
parser.add_argument("--memory", default="32m")
|
||||
parser.add_argument("--output", default="evidence/memory-experiment.json")
|
||||
parser.add_argument("--plot", default="evidence/memory-experiment.png")
|
||||
parser.add_argument("--max-messages", type=int, default=100000)
|
||||
args = parser.parse_args()
|
||||
|
||||
container = "mtusi-memory-experiment-" + uuid.uuid4().hex[:8]
|
||||
port = 18081
|
||||
base_url = f"http://127.0.0.1:{port}"
|
||||
subprocess.run(
|
||||
[
|
||||
"docker", "run", "-d", "--name", container,
|
||||
"--memory", args.memory, "--memory-swap", args.memory,
|
||||
"-p", f"127.0.0.1:{port}:8080", args.image,
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
samples = []
|
||||
stop_sampling = threading.Event()
|
||||
sampler = threading.Thread(target=sample_stats, args=(container, samples, stop_sampling))
|
||||
successful = 0
|
||||
failures = 0
|
||||
fatal_error = None
|
||||
started = time.monotonic()
|
||||
message_points_x = []
|
||||
message_points_y = []
|
||||
failure_time = None
|
||||
oom_killed = False
|
||||
last_error = None
|
||||
last_state = {}
|
||||
logs = ""
|
||||
|
||||
try:
|
||||
wait_ready(base_url)
|
||||
user = request(base_url, "POST", "/api/v1/users", {
|
||||
"username": "memory_" + uuid.uuid4().hex[:16],
|
||||
"display_name": "Memory experiment",
|
||||
})
|
||||
chat = request(base_url, "POST", "/api/v1/chats", {
|
||||
"title": "Memory experiment",
|
||||
"member_ids": [user["id"]],
|
||||
}, user["id"])
|
||||
sampler.start()
|
||||
time.sleep(0.5)
|
||||
|
||||
body = "x" * 4000
|
||||
for index in range(args.max_messages):
|
||||
try:
|
||||
request(
|
||||
base_url,
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
{"text": body},
|
||||
user["id"],
|
||||
)
|
||||
successful += 1
|
||||
message_points_x.append(time.monotonic() - started)
|
||||
message_points_y.append(successful)
|
||||
except (OSError, urllib.error.HTTPError, ValueError) as exc:
|
||||
last_error = type(exc).__name__ + ": " + str(exc)
|
||||
failures += 1
|
||||
failure_time = time.monotonic() - started
|
||||
break
|
||||
|
||||
time.sleep(0.5)
|
||||
if not process_alive(container):
|
||||
failure_time = failure_time or (time.monotonic() - started)
|
||||
inspect = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(inspect.stdout) if inspect.stdout.strip() else {}
|
||||
if not state:
|
||||
state_result = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(state_result.stdout) if state_result.stdout.strip() else {}
|
||||
last_state = state
|
||||
logs_result = subprocess.run(["docker", "logs", container], capture_output=True, text=True, check=False)
|
||||
logs = logs_result.stdout + logs_result.stderr
|
||||
oom_killed = bool(state.get("OOMKilled"))
|
||||
if failure_time is None and failures:
|
||||
failure_time = time.monotonic() - started
|
||||
except Exception as exc:
|
||||
fatal_error = type(exc).__name__ + ": " + str(exc)
|
||||
failure_time = failure_time or (time.monotonic() - started)
|
||||
finally:
|
||||
stop_sampling.set()
|
||||
if sampler.is_alive():
|
||||
sampler.join(timeout=2)
|
||||
|
||||
memory_limit_mib = float(args.memory.rstrip("mM")) if args.memory.lower().endswith("m") else 0
|
||||
if not oom_killed:
|
||||
inspect = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(inspect.stdout) if inspect.stdout.strip() else {}
|
||||
last_state = state
|
||||
oom_killed = bool(state.get("OOMKilled"))
|
||||
|
||||
result = {
|
||||
"image": args.image,
|
||||
"memory_limit": args.memory,
|
||||
"memory_limit_mib": memory_limit_mib,
|
||||
"successful_messages": successful,
|
||||
"failed_requests": failures,
|
||||
"oom_killed": oom_killed,
|
||||
"last_error": last_error,
|
||||
"fatal_error": fatal_error,
|
||||
"container_state": last_state,
|
||||
"container_logs_tail": logs[-20000:],
|
||||
"failure_time_seconds": failure_time,
|
||||
"memory_samples": samples,
|
||||
"message_points_x": message_points_x,
|
||||
"message_points_y": message_points_y,
|
||||
"reason": "process stopped after the container memory limit was reached" if oom_killed else "request processing did not reach the memory limit",
|
||||
}
|
||||
with open(args.output, "w", encoding="utf-8") as output:
|
||||
json.dump(result, output, ensure_ascii=False, indent=2)
|
||||
make_plot(result, args.plot)
|
||||
print(json.dumps({key: result[key] for key in (
|
||||
"memory_limit", "successful_messages", "failed_requests", "oom_killed", "failure_time_seconds", "reason",
|
||||
)}, ensure_ascii=False, indent=2))
|
||||
subprocess.run(["docker", "rm", "-f", container], capture_output=True, check=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,267 @@
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FAST_PATH = """\tif len(history) == 0 || compareKeyset(
|
||||
\t\thistory[len(history)-1].CreatedAt,
|
||||
\t\thistory[len(history)-1].ID,
|
||||
\t\tmessage.CreatedAt,
|
||||
\t\tmessage.ID,
|
||||
\t) < 0 {
|
||||
\t\ts.messagesByChat[message.ChatID] = append(history, message)
|
||||
|
||||
\t\treturn message, nil
|
||||
\t}
|
||||
|
||||
"""
|
||||
|
||||
|
||||
def request(opener, base, method, path, body=None, user=None):
|
||||
data = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
|
||||
headers = {}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if user is not None:
|
||||
headers["X-User-Id"] = user
|
||||
req = urllib.request.Request(base + path, data=data, headers=headers, method=method)
|
||||
with opener.open(req, timeout=10) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def available_port():
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
return listener.getsockname()[1]
|
||||
|
||||
|
||||
def descendants(root_pid):
|
||||
result = subprocess.run(
|
||||
["ps", "-axo", "pid=,ppid=,rss=,command="],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
entries = []
|
||||
for line in result.stdout.splitlines():
|
||||
fields = line.strip().split(None, 3)
|
||||
if len(fields) == 4:
|
||||
try:
|
||||
entries.append((int(fields[0]), int(fields[1]), int(fields[2]), fields[3]))
|
||||
except ValueError:
|
||||
continue
|
||||
children = {root_pid}
|
||||
while True:
|
||||
discovered = children | {pid for pid, ppid, _, _ in entries if ppid in children}
|
||||
if discovered == children:
|
||||
break
|
||||
children = discovered
|
||||
return [entry for entry in entries if entry[0] in children and entry[0] != root_pid]
|
||||
|
||||
|
||||
def server_rss_kib(go_run_pid):
|
||||
servers = [rss for _, _, rss, command in descendants(go_run_pid) if command.rstrip().endswith("/messenger")]
|
||||
if not servers:
|
||||
raise RuntimeError("go run server process was not found")
|
||||
return max(servers)
|
||||
|
||||
|
||||
def wait_ready(process, opener, base):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError(f"go run exited with code {process.returncode}")
|
||||
try:
|
||||
request(opener, base, "GET", "/health/live")
|
||||
server_rss_kib(process.pid)
|
||||
return
|
||||
except (OSError, RuntimeError):
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("go run server did not become ready")
|
||||
|
||||
|
||||
def percentile(latencies, fraction):
|
||||
ordered = sorted(latencies)
|
||||
index = max(0, min(len(ordered) - 1, (len(ordered) * int(fraction * 100) + 99) // 100 - 1))
|
||||
return round(ordered[index] * 1000, 3)
|
||||
|
||||
|
||||
def setup(opener, base, history):
|
||||
users = []
|
||||
for _ in range(10):
|
||||
user = request(opener, base, "POST", "/api/v1/users", {
|
||||
"username": "b" + uuid.uuid4().hex[:20],
|
||||
"display_name": "Benchmark",
|
||||
})
|
||||
users.append(user)
|
||||
|
||||
chat = request(opener, base, "POST", "/api/v1/chats", {
|
||||
"title": "Benchmark",
|
||||
"member_ids": [user["id"] for user in users],
|
||||
}, users[0]["id"])
|
||||
|
||||
for index in range(history):
|
||||
request(opener, base, "POST", f"/api/v1/chats/{chat['id']}/messages", {
|
||||
"text": f"history-{index}",
|
||||
}, users[index % len(users)]["id"])
|
||||
|
||||
return chat, users
|
||||
|
||||
|
||||
def launch(mode, port, overlay):
|
||||
command = ["go", "run"]
|
||||
if mode == "baseline":
|
||||
command.extend(["-overlay", str(overlay)])
|
||||
command.append("./cmd/messenger")
|
||||
process = subprocess.Popen(
|
||||
command,
|
||||
cwd=ROOT,
|
||||
env={**os.environ, "APP_HOST": "127.0.0.1", "APP_PORT": str(port)},
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
start_new_session=True,
|
||||
)
|
||||
return process, command
|
||||
|
||||
|
||||
def run_case(mode, history, concurrency, requests, overlay):
|
||||
port = available_port()
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
process, command = launch(mode, port, overlay)
|
||||
try:
|
||||
wait_ready(process, opener, base)
|
||||
chat, users = setup(opener, base, history)
|
||||
rss = []
|
||||
stop_sampling = threading.Event()
|
||||
sampling_errors = []
|
||||
|
||||
def sample():
|
||||
while not stop_sampling.is_set():
|
||||
try:
|
||||
rss.append(server_rss_kib(process.pid))
|
||||
except RuntimeError as exc:
|
||||
sampling_errors.append(str(exc))
|
||||
stop_sampling.wait(0.1)
|
||||
|
||||
sampler = threading.Thread(target=sample)
|
||||
sampler.start()
|
||||
warmup = min(100, max(10, requests // 100))
|
||||
|
||||
for index in range(warmup):
|
||||
request(opener, base, "POST", f"/api/v1/chats/{chat['id']}/messages", {
|
||||
"text": f"warmup-{index}",
|
||||
}, users[index % len(users)]["id"])
|
||||
|
||||
started = time.monotonic()
|
||||
|
||||
def worker(worker_id):
|
||||
latencies = []
|
||||
failures = 0
|
||||
worker_requests = requests // concurrency + (1 if worker_id < requests % concurrency else 0)
|
||||
for index in range(worker_requests):
|
||||
request_started = time.perf_counter()
|
||||
try:
|
||||
request(opener, base, "POST", f"/api/v1/chats/{chat['id']}/messages", {
|
||||
"text": f"load-{worker_id}-{index}",
|
||||
}, users[worker_id % len(users)]["id"])
|
||||
latencies.append(time.perf_counter() - request_started)
|
||||
except (OSError, ValueError, urllib.error.HTTPError):
|
||||
failures += 1
|
||||
index += 1
|
||||
return latencies, failures
|
||||
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
results = list(pool.map(worker, range(concurrency)))
|
||||
finally:
|
||||
elapsed = time.monotonic() - started
|
||||
stop_sampling.set()
|
||||
sampler.join()
|
||||
|
||||
latencies = [value for values, _ in results for value in values]
|
||||
failures = sum(value for _, value in results)
|
||||
if not latencies or not rss or sampling_errors:
|
||||
raise RuntimeError(f"invalid sample: successes={len(latencies)} rss={len(rss)} errors={sampling_errors}")
|
||||
|
||||
return {
|
||||
"history": history,
|
||||
"concurrency": concurrency,
|
||||
"duration_seconds": round(elapsed, 3),
|
||||
"requested_requests": requests,
|
||||
"warmup_requests": warmup,
|
||||
"successful_requests": len(latencies),
|
||||
"failed_requests": failures,
|
||||
"rps": round(len(latencies) / elapsed, 3),
|
||||
"p50_ms": percentile(latencies, 0.50),
|
||||
"p95_ms": percentile(latencies, 0.95),
|
||||
"p99_ms": percentile(latencies, 0.99),
|
||||
"rss_min_kib": min(rss),
|
||||
"rss_max_kib": max(rss),
|
||||
"rss_delta_kib": max(rss) - min(rss),
|
||||
}, command
|
||||
finally:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
|
||||
|
||||
def baseline_overlay(directory):
|
||||
source = (ROOT / "internal/storage/memory/message_repository.go").resolve()
|
||||
content = source.read_text()
|
||||
if content.count(FAST_PATH) != 1:
|
||||
raise RuntimeError("expected exactly one optimized append block")
|
||||
replacement = directory / "message_repository_baseline.go"
|
||||
replacement.write_text(content.replace(FAST_PATH, "", 1))
|
||||
overlay = directory / "overlay.json"
|
||||
overlay.write_text(json.dumps({"Replace": {str(source): str(replacement)}}))
|
||||
return overlay
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--mode", choices=("baseline", "optimized"), required=True)
|
||||
parser.add_argument("--requests", type=int, default=10000)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if args.requests <= 0:
|
||||
parser.error("--requests must be positive")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="messenger-track1-") as temp_dir:
|
||||
overlay = baseline_overlay(Path(temp_dir))
|
||||
rows = []
|
||||
for history in (1000, 10000, 50000):
|
||||
for concurrency in (1, 4, 16, 32):
|
||||
row, command = run_case(args.mode, history, concurrency, args.requests, overlay)
|
||||
rows.append(row)
|
||||
print(json.dumps(row, ensure_ascii=False), flush=True)
|
||||
result = {
|
||||
"mode": args.mode,
|
||||
"command": command,
|
||||
"go_version": subprocess.check_output(["go", "version"], text=True).strip(),
|
||||
"os_arch": subprocess.check_output(["go", "env", "GOOS", "GOARCH"], text=True).split(),
|
||||
"requests_per_case": args.requests,
|
||||
"rss_source": "ps RSS of go run child executable, KiB; sampled every 100 ms",
|
||||
"rows": rows,
|
||||
}
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user