2 Commits
Author SHA1 Message Date
Vladislav Kunetskiy 5ea57db639 lab2
Application / Lint (pull_request) Canceled after 0s
Application / Unit tests (pull_request) Canceled after 0s
Application / Docker build (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
2026-10-06 00:19:15 +03:00
Vladislav Kunetskiy 51b236a69f lab1 2026-10-01 12:59:06 +03:00
150 changed files with 41140 additions and 27 deletions
+4
View File
@@ -18,3 +18,7 @@ __pycache__
node_modules node_modules
evidence evidence
.DS_Store .DS_Store
bin
coverage.out
coverage.out.tmp
*.log
+39 -11
View File
@@ -1,11 +1,39 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. APP_ENV=dev
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0 APP_SERVER_HOST=0.0.0.0
APP_PORT=8080 APP_SERVER_PORT=8080
APP_ENV=lab APP_SERVER_READ_HEADER_TIMEOUT=10s
SESSION_TTL_SECONDS=3600 APP_SERVER_SHUTDOWN_TIMEOUT=10s
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url APP_LOG_LEVEL=info
# Optional on 3, required use on 4 in lab2; Redis OR Valkey: APP_LOG_FORMAT=json
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url APP_POSTGRES_HOST=localhost
APP_POSTGRES_PORT=5432
APP_POSTGRES_DATABASE=messenger
APP_POSTGRES_USER=messenger
APP_POSTGRES_PASSWORD=messenger
APP_POSTGRES_SSL_MODE=disable
APP_POSTGRES_MAX_CONNS=10
APP_POSTGRES_MIN_CONNS=1
APP_POSTGRES_MAX_CONN_LIFETIME=1h
APP_POSTGRES_MAX_CONN_IDLE_TIME=30m
APP_POSTGRES_CONNECT_TIMEOUT=5s
APP_POSTGRES_QUERY_TIMEOUT=5s
APP_REDIS_ENABLED=true
APP_REDIS_HOST=localhost
APP_REDIS_PORT=6379
APP_REDIS_PASSWORD=
APP_REDIS_DB=0
APP_REDIS_MAX_RETRIES=3
APP_REDIS_DIAL_TIMEOUT=5s
APP_REDIS_READ_TIMEOUT=3s
APP_REDIS_WRITE_TIMEOUT=3s
APP_REDIS_POOL_SIZE=10
APP_CACHE_ENABLED=true
APP_CACHE_CHAT_LIST_TTL=5m
APP_CACHE_SESSION_TTL=5m
APP_SESSION_TTL_SECONDS=3600
+47
View File
@@ -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
+2
View File
@@ -24,6 +24,8 @@ target/
bin/ bin/
obj/ obj/
coverage/ coverage/
coverage.out
coverage.out.tmp
*.log *.log
.DS_Store .DS_Store
.idea/ .idea/
+139
View File
@@ -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
+29
View File
@@ -0,0 +1,29 @@
#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
mtusi-messenger/internal/service/session:
config:
all: true
mtusi-messenger/internal/transport/rest:
config:
all: true
+10
View File
@@ -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
+41
View File
@@ -0,0 +1,41 @@
# 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 \
&& CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
go build -trimpath -buildvcs=false -tags timetzdata \
-ldflags="-s -w -X main.version=${VERSION}" \
-o /out/migrate ./cmd/migrate
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
COPY --from=build --chown=10001:10001 /out/migrate /usr/local/bin/migrate
COPY --chown=10001:10001 config/dev/config.yaml /etc/messenger/dev/config.yaml
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_SERVER_PORT}/health/live" || exit 1
ENTRYPOINT ["/usr/local/bin/messenger"]
+84 -1
View File
@@ -3,8 +3,9 @@ BASE_URL ?= http://localhost:8080
CA_FILE ?= CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) 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 test-persistence .PHONY: help check validate test load test-persistence smoke-local load-local
help: help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@@ -24,3 +25,85 @@ load:
test-persistence: test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
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/internal/oas
-include .env
export
.PHONY: unit-test
unit-test:
$(GO) test -race -shuffle=on -count=1 -timeout=5m ./...
.PHONY: integration-test
integration-test:
$(GO) test -tags=integration -count=1 -timeout=15m ./internal/storage/postgres ./internal/storage/redis
.PHONY: test-db-up test-db-down
test-db-up:
@docker-compose -f docker-compose.local.yaml up -d --wait postgres redis
test-db-down:
@docker-compose -f docker-compose.local.yaml down
# не учитываем генеренные файлы, также 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 sqlc
.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: sqlc
sqlc:
$(GO) tool sqlc generate
.PHONY: dev-up dev-down dev-reload
dev-up:
@docker-compose -f docker-compose.local.yaml up -d --build
dev-down:
@docker-compose -f docker-compose.local.yaml down
dev-reload:
@docker-compose -f docker-compose.local.yaml up -d --build --force-recreate
.PHONY: migrate
migrate:
$(GO) run ./cmd/migrate up
$(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
+79 -15
View File
@@ -1,37 +1,101 @@
# Отчёт — лабораторная 2 # Отчёт — лабораторная 2
- Автор, группа: TODO - Автор, группа: Владислав Кунецкий, БВT2303
- Целевая оценка; выбранный трек 5, если нужен: TODO - Целевая оценка: 5
- Commit/PR: TODO после публикации - Выбранный трек 5: трек 1 — предел in-memory архитектуры
- Использованные источники, библиотеки и помощь ИИ: TODO - Commit/PR: solution/bvt2303-kunetsky
- Использованные библиотеки: ogen - генерация транспортного слова из openapi спеки, testify, mockery/v3 - тесты, zap обернутый в slog - логгирование.
- Помощь ИИ использовалась для обсуждения архитектуры, ревью и подготовки кода; решение проверено и изменено автором.
## Запуск из чистого clone ## Запуск из чистого 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 | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO | | Публичный smoke | `make test` | `PASS: lab1 public API scenario` | `evidence/smoke.txt` |
| Остальные пункты уровня 3 | TODO | TODO | TODO | | Контракт и структура | `make check` | `PASS` | `evidence/check.txt` |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | | Unit, vet, race, lint | `make unit-test`, `go vet ./...`, `make lint` | PASS | `evidence/quality.txt` |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO | | 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` |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. | 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, внешняя база и горизонтальное масштабирование не реализованы.
+173
View File
@@ -0,0 +1,173 @@
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/health"
"mtusi-messenger/internal/logger"
"mtusi-messenger/internal/platform/cache"
"mtusi-messenger/internal/platform/token"
"mtusi-messenger/internal/service/chat"
"mtusi-messenger/internal/service/message"
"mtusi-messenger/internal/service/session"
"mtusi-messenger/internal/service/user"
"mtusi-messenger/internal/storage/postgres"
storageredis "mtusi-messenger/internal/storage/redis"
"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 {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
store, err := postgres.New(ctx, cfg.Postgres)
if err != nil {
return fmt.Errorf("connect database: %w", err)
}
defer store.Close()
redisCache, err := connectRedis(cfg.Redis)
if err != nil {
return err
}
defer func() { _ = redisCache.Close() }()
sessionRepo := session.Repository(store.Sessions())
chatRepo := chat.Repository(store.Chats())
pingers := []health.Pinger{store}
if cfg.Redis.Enabled {
sessionRepo = storageredis.NewSessionRepository(
store.Sessions(),
redisCache,
cfg.Cache.SessionTTL,
log,
)
if cfg.Cache.Enabled {
chatRepo = storageredis.NewChatRepository(
store.Chats(),
cache.WithSingleflight(redisCache),
cfg.Cache.ChatListTTL,
log,
)
}
log.Info("redis cache enabled", slog.String("host", cfg.Redis.Host), slog.Int("port", cfg.Redis.Port))
}
ttl := time.Duration(cfg.Session.TTLSeconds) * time.Second
sessionService := session.NewService(sessionRepo, token.New(), ttl)
router, err := rest.NewRouter(
rest.NewHandler(
user.NewService(store.Users()),
chat.NewService(chatRepo),
message.NewService(store.Messages()),
health.New(pingers...),
sessionService,
),
rest.NewSecurityHandler(sessionService),
log,
)
if err != nil {
return fmt.Errorf("build router: %w", err)
}
server := &http.Server{
Addr: cfg.Addr(),
Handler: router,
ReadHeaderTimeout: cfg.Server.ReadHeaderTimeout,
}
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.Server.ShutdownTimeout))
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
log.Info("server stopped")
return nil
}
func connectRedis(cfg config.Redis) (cache.Cache, error) {
if !cfg.Enabled {
return cache.NoOpCache{}, nil
}
client, err := cache.NewRedis(cache.RedisConfig{
Host: cfg.Host,
Port: cfg.Port,
Password: cfg.Password,
DB: cfg.DB,
MaxRetries: cfg.MaxRetries,
DialTimeout: cfg.DialTimeout,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
PoolSize: cfg.PoolSize,
})
if err != nil {
return nil, fmt.Errorf("connect redis: %w", err)
}
return client, nil
}
+89
View File
@@ -0,0 +1,89 @@
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"log/slog"
"os"
"github.com/pressly/goose/v3"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/logger"
"mtusi-messenger/internal/storage/postgres/migrations"
_ "github.com/jackc/pgx/v5/stdlib"
)
func main() {
log := logger.New()
if err := run(os.Args[1:]); err != nil {
log.Error("migrate failed", slog.Any("error", err))
os.Exit(1)
}
}
func run(args []string) error {
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("load config: %w", err)
}
slog.SetDefault(logger.New(
logger.WithLevel(cfg.SlogLevel()),
logger.WithFormat(cfg.LoggerFormat()),
))
command := "up"
if len(args) > 0 {
command = args[0]
}
db, err := sql.Open("pgx", cfg.Postgres.DSN())
if err != nil {
return fmt.Errorf("open database: %w", err)
}
defer func() { _ = db.Close() }()
pingCtx, cancel := context.WithTimeout(context.Background(), cfg.Postgres.ConnectTimeout)
defer cancel()
if err := db.PingContext(pingCtx); err != nil {
return fmt.Errorf("ping database: %w", err)
}
goose.SetBaseFS(migrations.FS)
if err := goose.SetDialect("postgres"); err != nil {
return fmt.Errorf("set dialect: %w", err)
}
if err := goCommand(db, command); err != nil {
return err
}
return nil
}
func goCommand(db *sql.DB, command string) error {
switch command {
case "up":
return goose.Up(db, ".")
case "up-by-one":
return goose.UpByOne(db, ".")
case "down":
return goose.Down(db, ".")
case "status":
return goose.Status(db, ".")
case "version":
return goose.Version(db, ".")
case "redo":
return goose.Redo(db, ".")
default:
return errors.New("unknown command: " + command + " (up, up-by-one, down, status, version, redo)")
}
}
+44
View File
@@ -0,0 +1,44 @@
env: dev
server:
host: 0.0.0.0
port: 8080
read_header_timeout: 10s
shutdown_timeout: 10s
log:
level: info
format: json
postgres:
host: localhost
port: 5432
database: messenger
user: messenger
password: ${APP_POSTGRES_PASSWORD}
ssl_mode: disable
max_conns: 10
min_conns: 1
max_conn_lifetime: 1h
max_conn_idle_time: 30m
connect_timeout: 5s
query_timeout: 5s
redis:
enabled: true
host: localhost
port: 6379
db: 0
max_retries: 3
dial_timeout: 5s
read_timeout: 3s
write_timeout: 3s
pool_size: 10
cache:
enabled: true
chat_list_ttl: 5m
session_ttl: 5m
session:
ttl_seconds: 3600
+101
View File
@@ -0,0 +1,101 @@
name: mtusi-messenger-lab2
x-app: &app
build:
context: .
dockerfile: Dockerfile
image: mtusi-messenger:lab2
services:
postgres:
image: postgres:18-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873
environment:
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_DB: ${POSTGRES_DB:-messenger}
ports:
- "127.0.0.1:${POSTGRES_PORT:-5432}:5432"
volumes:
- postgres18-data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 10
start_period: 5s
restart: unless-stopped
redis:
image: redis:7.4-alpine
command:
- redis-server
- --appendonly
- "yes"
- --appendfsync
- everysec
- --save
- "60"
- "1"
ports:
- "127.0.0.1:${REDIS_PORT:-6379}:6379"
volumes:
- redis7-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 10
start_period: 3s
restart: unless-stopped
migrate:
<<: *app
entrypoint: ["/usr/local/bin/migrate"]
command: ["up"]
environment:
APP_CONFIG: /etc/messenger/dev/config.yaml
APP_POSTGRES_HOST: postgres
APP_POSTGRES_PORT: "5432"
APP_POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
APP_POSTGRES_USER: ${POSTGRES_USER:-messenger}
APP_POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
APP_POSTGRES_SSL_MODE: disable
depends_on:
postgres:
condition: service_healthy
restart: "no"
api:
<<: *app
environment:
APP_CONFIG: /etc/messenger/dev/config.yaml
APP_POSTGRES_HOST: postgres
APP_POSTGRES_PORT: "5432"
APP_POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
APP_POSTGRES_USER: ${POSTGRES_USER:-messenger}
APP_POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
APP_POSTGRES_SSL_MODE: disable
APP_REDIS_ENABLED: "${APP_REDIS_ENABLED:-true}"
APP_REDIS_HOST: redis
APP_REDIS_PORT: "6379"
APP_CACHE_ENABLED: "${APP_CACHE_ENABLED:-true}"
ports:
- "127.0.0.1:${APP_SERVER_PORT:-8080}:8080"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
migrate:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"]
interval: 10s
timeout: 3s
retries: 5
start_period: 5s
restart: unless-stopped
volumes:
postgres18-data:
name: mtusi-messenger-lab2-postgres18-data
redis7-data:
name: mtusi-messenger-lab2-redis7-data
+11
View File
@@ -0,0 +1,11 @@
# API cache performance experiment
# generated: 2026-10-05T20:32:23Z
running trial 1, cache=False, requests=1000
{"requests": 1000, "workers": 8, "duration_seconds": 0.37194291700143367, "rps": 2688.584603416834, "p50_ms": 2.7120834565721452, "p95_ms": 4.2240830371156335, "p99_ms": 5.933874985203147, "trial": 1, "cache_enabled": false}
running trial 1, cache=True, requests=1000
{"requests": 1000, "workers": 8, "duration_seconds": 0.30397041607648134, "rps": 3289.7938322668615, "p50_ms": 2.237749984487891, "p95_ms": 3.605750040151179, "p99_ms": 5.097458022646606, "trial": 1, "cache_enabled": true}
running trial 2, cache=False, requests=1000
{"requests": 1000, "workers": 8, "duration_seconds": 0.4000672500114888, "rps": 2499.5797580813796, "p50_ms": 2.929750015027821, "p95_ms": 4.9592910800129175, "p99_ms": 7.416000007651746, "trial": 2, "cache_enabled": false}
running trial 2, cache=True, requests=1000
{"requests": 1000, "workers": 8, "duration_seconds": 0.3116560000926256, "rps": 3208.665964084745, "p50_ms": 2.319625054951757, "p95_ms": 3.7357090041041374, "p99_ms": 4.752291017211974, "trial": 2, "cache_enabled": true}
{"results": [{"requests": 1000, "workers": 8, "duration_seconds": 0.37194291700143367, "rps": 2688.584603416834, "p50_ms": 2.7120834565721452, "p95_ms": 4.2240830371156335, "p99_ms": 5.933874985203147, "trial": 1, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.30397041607648134, "rps": 3289.7938322668615, "p50_ms": 2.237749984487891, "p95_ms": 3.605750040151179, "p99_ms": 5.097458022646606, "trial": 1, "cache_enabled": true}, {"requests": 1000, "workers": 8, "duration_seconds": 0.4000672500114888, "rps": 2499.5797580813796, "p50_ms": 2.929750015027821, "p95_ms": 4.9592910800129175, "p99_ms": 7.416000007651746, "trial": 2, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.3116560000926256, "rps": 3208.665964084745, "p50_ms": 2.319625054951757, "p95_ms": 3.7357090041041374, "p99_ms": 4.752291017211974, "trial": 2, "cache_enabled": true}], "users": 4, "chats": 60, "sessions_cached_in_both_modes": true}
+36
View File
@@ -0,0 +1,36 @@
# Cache consistency evidence (track 1)
# generated: 2026-10-04T13:47:04Z
# redis: localhost:6379 db=1
=== RUN TestChatRepositorySuite
=== RUN TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated
chat_repository_test.go:158: singleflight: 100 concurrent cold reads -> 1 source loads
=== RUN TestChatRepositorySuite/TestConcurrentColdReadsWithoutProtectionStampede
chat_repository_test.go:207: stampede demonstration: 100 concurrent reads -> 100 source loads
=== RUN TestChatRepositorySuite/TestCreateInvalidatesMemberCaches
=== RUN TestChatRepositorySuite/TestDeeperPagesBypassCache
=== RUN TestChatRepositorySuite/TestFirstPageIsCached
=== RUN TestChatRepositorySuite/TestLimitIsPartOfCacheKey
--- PASS: TestChatRepositorySuite (0.11s)
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated (0.06s)
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsWithoutProtectionStampede (0.02s)
--- PASS: TestChatRepositorySuite/TestCreateInvalidatesMemberCaches (0.01s)
--- PASS: TestChatRepositorySuite/TestDeeperPagesBypassCache (0.00s)
--- PASS: TestChatRepositorySuite/TestFirstPageIsCached (0.00s)
--- PASS: TestChatRepositorySuite/TestLimitIsPartOfCacheKey (0.01s)
=== RUN TestSessionRepositorySuite
=== RUN TestSessionRepositorySuite/TestCacheTTLCapAndSessionExpiry
=== RUN TestSessionRepositorySuite/TestEvictedCacheEntryReloadsFromSource
=== RUN TestSessionRepositorySuite/TestExpiredSessionIsRejected
=== RUN TestSessionRepositorySuite/TestResolveFallsBackToSourceOnMiss
=== RUN TestSessionRepositorySuite/TestResolvePopulatesCacheAndServesFromIt
=== RUN TestSessionRepositorySuite/TestRevokeEvictsCacheAndSource
--- PASS: TestSessionRepositorySuite (0.01s)
--- PASS: TestSessionRepositorySuite/TestCacheTTLCapAndSessionExpiry (0.00s)
--- PASS: TestSessionRepositorySuite/TestEvictedCacheEntryReloadsFromSource (0.00s)
--- PASS: TestSessionRepositorySuite/TestExpiredSessionIsRejected (0.00s)
--- PASS: TestSessionRepositorySuite/TestResolveFallsBackToSourceOnMiss (0.00s)
--- PASS: TestSessionRepositorySuite/TestResolvePopulatesCacheAndServesFromIt (0.00s)
--- PASS: TestSessionRepositorySuite/TestRevokeEvictsCacheAndSource (0.00s)
PASS
ok mtusi-messenger/internal/storage/redis 0.565s
+22
View File
@@ -0,0 +1,22 @@
# Cache latency experiment
# generated: 2026-10-05T19:27:40Z
go version go1.27.1 darwin/arm64
Darwin arm64
2026/10/05 22:27:42 OK 00001_init.sql (10.85ms)
2026/10/05 22:27:42 goose: successfully migrated database to version: 1
=== RUN TestCacheLatencyExperiment
cache_latency_experiment_test.go:67: baseline: requests=1000 source_loads=1000 p50=518.084µs p95=915.292µs p99=1.312875ms
cache_latency_experiment_test.go:68: redis cache: requests=1000 source_loads=1 p50=593.625µs p95=1.013958ms p99=1.388084ms
--- PASS: TestCacheLatencyExperiment (1.35s)
=== RUN TestCacheLatencyExperiment
cache_latency_experiment_test.go:67: baseline: requests=1000 source_loads=1000 p50=524.875µs p95=847.917µs p99=1.037875ms
cache_latency_experiment_test.go:68: redis cache: requests=1000 source_loads=1 p50=882.042µs p95=1.2005ms p99=1.415583ms
--- PASS: TestCacheLatencyExperiment (1.59s)
=== RUN TestCacheLatencyExperiment
cache_latency_experiment_test.go:67: baseline: requests=1000 source_loads=1000 p50=509.292µs p95=774.875µs p99=987.583µs
cache_latency_experiment_test.go:68: redis cache: requests=1000 source_loads=1 p50=475.375µs p95=927.708µs p99=1.195708ms
--- PASS: TestCacheLatencyExperiment (1.26s)
PASS
ok mtusi-messenger/internal/storage/postgres 5.016s
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
+25
View File
@@ -0,0 +1,25 @@
# Cache performance experiment
# generated: 2026-10-05T19:28:14Z
go version go1.27.1 darwin/arm64
Darwin arm64
2026/10/05 22:28:15 OK 00001_init.sql (13.83ms)
2026/10/05 22:28:15 goose: successfully migrated database to version: 1
=== RUN TestCachePerformanceExperiment
cache_performance_experiment_test.go:94: baseline (no cache): requests=10000 concurrency=50 sql=1 duration=1.327s rps=7534 p50=6.455042ms p95=7.747375ms p99=10.882916ms
cache_performance_experiment_test.go:95: redis cache (cold): requests=10000 concurrency=50 sql=0 duration=893ms rps=11204 p50=4.412375ms p95=5.025167ms p99=6.189958ms
cache_performance_experiment_test.go:96: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=895ms rps=11177 p50=4.396541ms p95=5.287709ms p99=6.229542ms
--- PASS: TestCachePerformanceExperiment (3.45s)
=== RUN TestCachePerformanceExperiment
cache_performance_experiment_test.go:94: baseline (no cache): requests=10000 concurrency=50 sql=1 duration=1.279s rps=7817 p50=6.285041ms p95=7.161833ms p99=9.118583ms
cache_performance_experiment_test.go:95: redis cache (cold): requests=10000 concurrency=50 sql=0 duration=886ms rps=11286 p50=4.3635ms p95=5.0135ms p99=5.986041ms
cache_performance_experiment_test.go:96: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=884ms rps=11317 p50=4.379667ms p95=5.01725ms p99=5.431542ms
--- PASS: TestCachePerformanceExperiment (3.39s)
=== RUN TestCachePerformanceExperiment
cache_performance_experiment_test.go:94: baseline (no cache): requests=10000 concurrency=50 sql=1 duration=1.299s rps=7697 p50=6.23975ms p95=8.681917ms p99=10.371709ms
cache_performance_experiment_test.go:95: redis cache (cold): requests=10000 concurrency=50 sql=0 duration=897ms rps=11147 p50=4.438375ms p95=5.078459ms p99=5.789542ms
cache_performance_experiment_test.go:96: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=902ms rps=11091 p50=4.395708ms p95=5.31425ms p99=7.578416ms
--- PASS: TestCachePerformanceExperiment (3.35s)
PASS
ok mtusi-messenger/internal/storage/postgres 10.620s
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
+3
View File
@@ -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.
+2
View File
@@ -0,0 +1,2 @@
command: docker run + Python ThreadPoolExecutor(10), 100 POST messages
{"sent": 100, "read": 100, "unique": 100}
+11
View File
@@ -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"}
+1
View File
@@ -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

+8
View File
@@ -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
+64
View File
@@ -0,0 +1,64 @@
# EXPLAIN (ANALYZE, BUFFERS)
## history_first_page
Limit (cost=0.29..5.40 rows=51 width=73) (actual time=0.007..0.012 rows=51.00 loops=1)
Buffers: shared hit=4
-> Index Scan using messages_chat_id_created_at_id_idx on messages (cost=0.29..1002.85 rows=10000 width=73) (actual time=0.006..0.009 rows=51.00 loops=1)
Index Cond: (chat_id = '01a0f77e-9381-736f-9a2b-af3b1e1e87fd'::uuid)
Index Searches: 1
Buffers: shared hit=4
Planning:
Buffers: shared hit=44
Planning Time: 0.147 ms
Execution Time: 0.019 ms
## history_next_page
Limit (cost=0.29..7.71 rows=51 width=73) (actual time=0.004..0.010 rows=51.00 loops=1)
Buffers: shared hit=4
-> Index Scan using messages_chat_id_created_at_id_idx on messages (cost=0.29..524.01 rows=3599 width=73) (actual time=0.004..0.008 rows=51.00 loops=1)
Index Cond: ((chat_id = '01a0f77e-9381-736f-9a2b-af3b1e1e87fd'::uuid) AND (ROW(created_at, id) > ROW('2026-10-01 11:44:23.146682+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
Index Searches: 1
Buffers: shared hit=4
Planning Time: 0.021 ms
Execution Time: 0.027 ms
## chats_list_for_member
Limit (cost=0.57..446.14 rows=51 width=70) (actual time=0.018..0.081 rows=51.00 loops=1)
Buffers: shared hit=309
-> Nested Loop (cost=0.57..87375.78 rows=10001 width=70) (actual time=0.018..0.079 rows=51.00 loops=1)
Buffers: shared hit=309
-> Index Scan using chats_created_at_id_idx on chats c (cost=0.29..554.24 rows=10001 width=38) (actual time=0.004..0.007 rows=51.00 loops=1)
Index Searches: 1
Buffers: shared hit=3
-> Index Only Scan using chat_members_user_id_chat_id_idx on chat_members visible (cost=0.29..0.36 rows=1 width=16) (actual time=0.001..0.001 rows=1.00 loops=51)
Index Cond: ((user_id = '01a0f77e-937a-7d1e-aacb-8909b9a65779'::uuid) AND (chat_id = c.id))
Heap Fetches: 51
Index Searches: 51
Buffers: shared hit=153
SubPlan 1
-> Aggregate (cost=8.31..8.32 rows=1 width=32) (actual time=0.001..0.001 rows=1.00 loops=51)
Buffers: shared hit=153
-> Index Only Scan using chat_members_pkey on chat_members m (cost=0.29..8.30 rows=1 width=16) (actual time=0.000..0.000 rows=1.00 loops=51)
Index Cond: (chat_id = c.id)
Heap Fetches: 51
Index Searches: 51
Buffers: shared hit=153
Planning:
Buffers: shared hit=95
Planning Time: 0.250 ms
Execution Time: 0.098 ms
## user_by_username
Index Scan using users_username_key on users (cost=0.29..8.30 rows=1 width=42) (actual time=0.005..0.005 rows=1.00 loops=1)
Index Cond: (username = 'bulk_5000'::text)
Index Searches: 1
Buffers: shared hit=3
Planning:
Buffers: shared hit=43
Planning Time: 0.085 ms
Execution Time: 0.008 ms
+43
View File
@@ -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]
+10
View File
@@ -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"}}
+7
View File
@@ -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"}
+2
View File
@@ -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
+128
View File
@@ -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
}
]
+110
View File
@@ -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
}
]
+211
View File
@@ -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
}
]
}
+266
View File
@@ -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
}
]
+209
View File
@@ -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
+128
View File
@@ -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
}
]
+120
View File
@@ -0,0 +1,120 @@
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/jackc/pgx/v5 v5.11.0
github.com/ogen-go/ogen v1.24.0
github.com/pressly/goose/v3 v3.28.0
github.com/redis/go-redis/v9 v9.22.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
golang.org/x/crypto v0.57.0
golang.org/x/sync v0.23.0
)
require (
cel.dev/expr v0.25.2 // indirect
filippo.io/edwards25519 v1.2.0 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/brunoga/deep v1.3.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/clipperhouse/uax29/v2 v2.2.0 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/cubicdaiya/gonp v1.0.4 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // 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/fatih/structtag v1.2.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-sql-driver/mysql v1.10.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/google/cel-go v0.28.0 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jedib0t/go-pretty/v6 v6.7.8 // indirect
github.com/jinzhu/inflection v1.0.0 // 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/mfridman/interpolate v0.0.2 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/ncruces/go-sqlite3 v0.32.0 // indirect
github.com/ncruces/julianday v1.0.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pganalyze/pg_query_go/v6 v6.2.2 // indirect
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee // indirect
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect
github.com/pingcap/log v1.1.0 // indirect
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 // indirect
github.com/riza-io/grpc-go v0.2.0 // 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/sethvargo/go-retry v0.4.0 // 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/sqlc-dev/doubleclick v1.0.0 // indirect
github.com/sqlc-dev/sqlc v1.31.1 // indirect
github.com/stretchr/objx v0.5.3 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tetratelabs/wazero v1.11.0 // indirect
github.com/vektra/mockery/v3 v3.8.0 // indirect
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 // indirect
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // 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/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/net v0.58.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
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a // indirect
google.golang.org/grpc v1.83.2 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // 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/sqlc-dev/sqlc/cmd/sqlc
github.com/vektra/mockery/v3
)
+322
View File
@@ -0,0 +1,322 @@
cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs=
cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/brunoga/deep v1.3.1 h1:bSrL6FhAZa6JlVv4vsi7Hg8SLwroDb1kgDERRVipBCo=
github.com/brunoga/deep v1.3.1/go.mod h1:GDV6dnXqn80ezsLSZ5Wlv1PdKAWAO4L5PnKYtv2dgaI=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/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-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4=
github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec=
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/cubicdaiya/gonp v1.0.4 h1:ky2uIAJh81WiLcGKBVD5R7KsM/36W6IqqTy6Bo6rGws=
github.com/cubicdaiya/gonp v1.0.4/go.mod h1:iWGuP/7+JVTn02OWhRemVbMmG1DOUnmrGTYYACpOI0I=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/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/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
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-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
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-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
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/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/cel-go v0.28.0 h1:KjSWstCpz/MN5t4a8gnGJNIYUsJRpdi/r97xWDphIQc=
github.com/google/cel-go v0.28.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8=
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/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/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/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
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.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
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/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
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/ncruces/go-sqlite3 v0.32.0 h1:hNBUXp88LrfQCsuyXLqWTbTUG35sUuktDsqhhgHvU20=
github.com/ncruces/go-sqlite3 v0.32.0/go.mod h1:MIWTK60ONDl0oVY073zYvJP21C3Dly6P9bxVpgkLwdQ=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M=
github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g=
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/pganalyze/pg_query_go/v6 v6.2.2 h1:O0L6zMC226R82RF3X5n0Ki6HjytDsoAzuzp4ATVAHNo=
github.com/pganalyze/pg_query_go/v6 v6.2.2/go.mod h1:Cn6+j4870kJz3iYNsb0VsNG04vpSWgEvBwc590J4qD0=
github.com/pingcap/errors v0.11.0/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee h1:/IDPbpzkzA97t1/Z1+C3KlxbevjMeaI6BQYxvivu4u8=
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee/go.mod h1:X2r9ueLEUZgtx2cIogM0v4Zj5uvvzhuuiu7Pn8HzMPg=
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 h1:tdMsjOqUR7YXHoBitzdebTvOjs/swniBTOLy5XiMtuE=
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86/go.mod h1:exzhVYca3WRtd6gclGNErRWb1qEgff3LYta0LvRmON4=
github.com/pingcap/log v1.1.0 h1:ELiPxACz7vdo1qAvvaWJg1NrYFoY6gqAh/+Uo6aXdD8=
github.com/pingcap/log v1.1.0/go.mod h1:DWQW5jICDR7UJh4HtxXSM20Churx4CQL0fwL/SoOSA4=
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 h1:zYmP5fBH+i2yhhU6f5uOol6zxHtR2/sD47BsJLfy0oU=
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124/go.mod h1:zDLDsfNBU5+L6T4J9/OgWAHc/WZvMUjbpgHqQ/t3yKo=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
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/pressly/goose/v3 v3.28.0 h1:D2M+iL31GmpZxSHOhX8mqyqAT3CXnokUmm0eKoSP+Vc=
github.com/pressly/goose/v3 v3.28.0/go.mod h1:v26MOuB8bL3kzzrt3Vqhb3R0PRVsl8hFQKdrht/L6Rk=
github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/riza-io/grpc-go v0.2.0 h1:2HxQKFVE7VuYstcJ8zqpN84VnAoJ4dCL6YFhJewNcHQ=
github.com/riza-io/grpc-go v0.2.0/go.mod h1:2bDvR9KkKC3KhtlSHfR3dAXjUMT86kg4UfWFyVGWqi8=
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/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
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/sqlc-dev/doubleclick v1.0.0 h1:2/OApfQ2eLgcfa/Fqs8WSMA6atH0G8j9hHbQIgMfAXI=
github.com/sqlc-dev/doubleclick v1.0.0/go.mod h1:ODHRroSrk/rr5neRHlWMSRijqOak8YmNaO3VAZCNl5Y=
github.com/sqlc-dev/sqlc v1.31.1 h1:+V+BjBJfFNPX/RFfL8eiZD9jk9lVJUEGGllWvnYNqbc=
github.com/sqlc-dev/sqlc v1.31.1/go.mod h1:6ZPww/Jd3G6MzJeW6NrqizjL+52vYNaaXP9yMeJ/Nao=
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.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
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/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
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/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 h1:mJdDDPblDfPe7z7go8Dvv1AJQDI3eQ/5xith3q2mFlo=
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07/go.mod h1:Ak17IJ037caFp4jpCw/iQQ7/W74Sqpb1YuKJU6HTKfM=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 h1:OvLBa8SqJnZ6P+mjlzc2K7PM22rRUPE1x32G9DTPrC4=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52/go.mod h1:jMeV4Vpbi8osrE/pKUxRZkVaA0EX7NZN0A9/oRzgpgY=
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=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
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.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=
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.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
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.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
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-20260824195058-e88cd73687aa h1:QSyA8ishJCyT21kER9KwNt0b7BM3iRK4x9QXhjN5Fdk=
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa/go.mod h1:zeBbvyFKDaLwa7CH/zI8KXt7gTl14SF7sO08Pl5jBCM=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
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.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
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.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
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-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
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.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
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.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a h1:3Dnd1cDaZlB68lziofO+bJXpjOy8UfRv8Unt+yH8tQ4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/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/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
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.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.75.6 h1:yKk8qo+Di4gkmvRboK8ocCqH22FiUCR6jRy2OwtCRus=
modernc.org/libc v1.75.6/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg=
modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
+220
View File
@@ -0,0 +1,220 @@
package config
import (
"errors"
"fmt"
"log/slog"
"net"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"github.com/go-playground/validator/v10"
"github.com/spf13/viper"
"mtusi-messenger/internal/logger"
)
const (
envPrefix = "APP"
configEnvKey = "APP_CONFIG"
configName = "config"
defaultEnv = "dev"
configDir = "./config/"
)
type Config struct {
Env string `mapstructure:"env" validate:"omitempty,eq=dev"`
Server Server `mapstructure:"server"`
Log Log `mapstructure:"log"`
Postgres Postgres `mapstructure:"postgres"`
Redis Redis `mapstructure:"redis"`
Cache Cache `mapstructure:"cache"`
Session Session `mapstructure:"session"`
}
type Session struct {
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
}
type Redis struct {
Enabled bool `mapstructure:"enabled"`
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=0"`
DialTimeout time.Duration `mapstructure:"dial_timeout" validate:"omitempty,gt=0"`
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"omitempty,gt=0"`
WriteTimeout time.Duration `mapstructure:"write_timeout" validate:"omitempty,gt=0"`
PoolSize int `mapstructure:"pool_size" validate:"omitempty,gt=0"`
}
type Cache struct {
Enabled bool `mapstructure:"enabled"`
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
SessionTTL time.Duration `mapstructure:"session_ttl" validate:"required,gt=0"`
}
type Server 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"`
}
type Log struct {
Level string `mapstructure:"level" validate:"required,oneof=debug info warn error"`
Format string `mapstructure:"format" validate:"required,oneof=json console"`
}
type Postgres struct {
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
Database string `mapstructure:"database" validate:"omitempty,min=1"`
User string `mapstructure:"user" validate:"omitempty,min=1"`
Password string `mapstructure:"password"`
SSLMode string `mapstructure:"ssl_mode" validate:"omitempty,oneof=disable require verify-ca verify-full"`
MaxConns int32 `mapstructure:"max_conns" validate:"omitempty,gt=0"`
MinConns int32 `mapstructure:"min_conns" validate:"omitempty,gte=0"`
MaxConnLifetime time.Duration `mapstructure:"max_conn_lifetime" validate:"omitempty,gt=0"`
MaxConnIdleTime time.Duration `mapstructure:"max_conn_idle_time" validate:"omitempty,gt=0"`
ConnectTimeout time.Duration `mapstructure:"connect_timeout" validate:"omitempty,gt=0"`
QueryTimeout time.Duration `mapstructure:"query_timeout" validate:"omitempty,gt=0"`
}
func (p Postgres) DSN() string {
u := &url.URL{
Scheme: "postgres",
Host: net.JoinHostPort(p.Host, strconv.Itoa(p.Port)),
Path: "/" + p.Database,
}
if p.Password == "" {
u.User = url.User(p.User)
} else {
u.User = url.UserPassword(p.User, p.Password)
}
query := url.Values{}
query.Set("sslmode", p.SSLMode)
u.RawQuery = query.Encode()
return u.String()
}
var defaults = map[string]any{
"env": "dev",
"server.host": "0.0.0.0",
"server.port": 8080,
"server.read_header_timeout": "10s",
"server.shutdown_timeout": "10s",
"log.level": "info",
"log.format": "json",
"session.ttl_seconds": 3600,
"redis.enabled": false,
"redis.host": "localhost",
"redis.port": 6379,
"redis.db": 0,
"redis.max_retries": 3,
"redis.dial_timeout": "5s",
"redis.read_timeout": "3s",
"redis.write_timeout": "3s",
"redis.pool_size": 10,
"cache.enabled": false,
"cache.chat_list_ttl": "5m",
"cache.session_ttl": "5m",
}
func Load() (Config, error) {
v := viper.New()
if err := configureSource(v); err != nil {
return Config{}, err
}
v.SetEnvPrefix(envPrefix)
v.AllowEmptyEnv(true)
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
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 configureSource(v *viper.Viper) error {
for key, value := range defaults {
v.SetDefault(key, value)
}
v.SetConfigType("yaml")
if path := os.Getenv(configEnvKey); path != "" {
v.SetConfigFile(path)
} else {
env := os.Getenv(envPrefix + "_ENV")
if env == "" {
env = defaultEnv
}
v.SetConfigName(configName)
v.AddConfigPath(filepath.Join(configDir, env))
}
if err := v.ReadInConfig(); err != nil {
var notFound viper.ConfigFileNotFoundError
if errors.As(err, &notFound) {
return nil
}
return fmt.Errorf("read config: %w", err)
}
return nil
}
func (c Config) Addr() string {
return net.JoinHostPort(c.Server.Host, strconv.Itoa(c.Server.Port))
}
func (c Config) SlogLevel() slog.Level {
level, _ := logger.ParseLevel(c.Log.Level)
return level
}
func (c Config) LoggerFormat() logger.Format {
format, _ := logger.ParseFormat(c.Log.Format)
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)
}
+317
View File
@@ -0,0 +1,317 @@
package config_test
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/go-playground/validator/v10"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/logger"
)
func TestDefaults(t *testing.T) {
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "0.0.0.0", cfg.Server.Host)
assert.Equal(t, 8080, cfg.Server.Port)
assert.Equal(t, 10*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, 10*time.Second, cfg.Server.ShutdownTimeout)
assert.Equal(t, "info", cfg.Log.Level)
assert.Equal(t, "json", cfg.Log.Format)
assert.Equal(t, config.Postgres{}, cfg.Postgres, "postgres defaults live in the adapter")
}
func TestEnvOverridesDefaults(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "127.0.0.1")
t.Setenv("APP_SERVER_PORT", "9090")
t.Setenv("APP_SERVER_READ_HEADER_TIMEOUT", "3s")
t.Setenv("APP_SERVER_SHUTDOWN_TIMEOUT", "30s")
t.Setenv("APP_LOG_LEVEL", "debug")
t.Setenv("APP_LOG_FORMAT", "console")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "127.0.0.1", cfg.Server.Host)
assert.Equal(t, 9090, cfg.Server.Port)
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, 30*time.Second, cfg.Server.ShutdownTimeout)
assert.Equal(t, "debug", cfg.Log.Level)
assert.Equal(t, "console", cfg.Log.Format)
}
func TestDsnEncodesCredentials(t *testing.T) {
cfg := config.Postgres{
Host: "db",
Port: 5432,
Database: "app",
User: "user",
Password: "p@ss:w/rd",
SSLMode: "disable",
}
assert.Equal(t, "postgres://user:p%40ss%3Aw%2Frd@db:5432/app?sslmode=disable", cfg.DSN())
}
func writeConfig(t *testing.T, body string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
return path
}
func TestLoadsYAMLFile(t *testing.T) {
path := writeConfig(t, `
env: dev
server:
host: 10.0.0.1
port: 9999
read_header_timeout: 3s
shutdown_timeout: 7s
log:
level: debug
format: console
postgres:
host: db
port: 5433
database: app
user: app
password: secret
ssl_mode: disable
max_conns: 7
min_conns: 2
max_conn_lifetime: 2h
max_conn_idle_time: 10m
connect_timeout: 2s
query_timeout: 3s
`)
t.Setenv("APP_CONFIG", path)
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "10.0.0.1", cfg.Server.Host)
assert.Equal(t, 9999, cfg.Server.Port)
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, "debug", cfg.Log.Level)
assert.Equal(t, "console", cfg.Log.Format)
assert.Equal(t, "db", cfg.Postgres.Host)
assert.Equal(t, 5433, cfg.Postgres.Port)
assert.Equal(t, "app", cfg.Postgres.Database)
assert.Equal(t, int32(7), cfg.Postgres.MaxConns)
assert.Equal(t, 2*time.Second, cfg.Postgres.ConnectTimeout)
}
func TestEnvOverridesYAML(t *testing.T) {
path := writeConfig(t, `
env: dev
server:
host: 10.0.0.1
port: 9999
read_header_timeout: 3s
shutdown_timeout: 7s
log:
level: debug
format: console
postgres:
host: db
port: 5433
database: app
user: app
password: file
ssl_mode: disable
`)
t.Setenv("APP_CONFIG", path)
t.Setenv("APP_SERVER_HOST", "127.0.0.1")
t.Setenv("APP_POSTGRES_PASSWORD", "env")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "APP_* переопределяет YAML")
assert.Equal(t, 9999, cfg.Server.Port)
assert.Equal(t, "env", cfg.Postgres.Password)
}
func TestInvalidValues(t *testing.T) {
tests := map[string]map[string]string{
"пустой server.host": {"APP_SERVER_HOST": ""},
"host не адрес и не имя": {"APP_SERVER_HOST": "не адрес"},
"порт ниже диапазона": {"APP_SERVER_PORT": "0"},
"порт выше диапазона": {"APP_SERVER_PORT": "65536"},
"нулевой read header timeout": {"APP_SERVER_READ_HEADER_TIMEOUT": "0s"},
"отрицательный shutdown": {"APP_SERVER_SHUTDOWN_TIMEOUT": "-1s"},
"неизвестный log level": {"APP_LOG_LEVEL": "trace"},
"неизвестный log format": {"APP_LOG_FORMAT": "xml"},
}
for name, env := range tests {
t.Run(name, func(t *testing.T) {
for key, value := range env {
t.Setenv(key, value)
}
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
require.NotEmpty(t, validationErrs)
})
}
}
func TestInvalidPostgresValues(t *testing.T) {
path := writeConfig(t, `
env: dev
postgres:
host: db
port: 5432
database: messenger
user: messenger
ssl_mode: disable
max_conns: 10
`)
tests := map[string]map[string]string{
"неизвестный ssl mode": {"APP_POSTGRES_SSL_MODE": "bogus"},
"отрицательный max_conns": {"APP_POSTGRES_MAX_CONNS": "-1"},
}
for name, env := range tests {
t.Run(name, func(t *testing.T) {
t.Setenv("APP_CONFIG", path)
for key, value := range env {
t.Setenv(key, value)
}
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
require.NotEmpty(t, validationErrs)
})
}
}
func TestUnparsableValues(t *testing.T) {
tests := map[string]map[string]string{
"порт не число": {"APP_SERVER_PORT": "не-число"},
"timeout не duration": {"APP_SERVER_READ_HEADER_TIMEOUT": "быстро"},
}
for name, env := range tests {
t.Run(name, func(t *testing.T) {
for key, value := range env {
t.Setenv(key, value)
}
_, err := config.Load()
require.Error(t, err)
})
}
}
func TestLoggerSettings(t *testing.T) {
t.Setenv("APP_LOG_LEVEL", "warn")
t.Setenv("APP_LOG_FORMAT", "console")
cfg, err := config.Load()
require.NoError(t, err)
level, err := logger.ParseLevel(cfg.Log.Level)
require.NoError(t, err)
assert.Equal(t, level, cfg.SlogLevel())
format, err := logger.ParseFormat(cfg.Log.Format)
require.NoError(t, err)
assert.Equal(t, format, cfg.LoggerFormat())
}
func TestAddr(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "0.0.0.0")
t.Setenv("APP_SERVER_PORT", "8080")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "0.0.0.0:8080", cfg.Addr())
}
func TestAddrWithIPv6Host(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "::1")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "[::1]:8080", cfg.Addr())
}
func TestLoadIsIndependentOfProcessState(t *testing.T) {
t.Setenv("APP_SERVER_PORT", "7070")
first, err := config.Load()
require.NoError(t, err)
second, err := config.Load()
require.NoError(t, err)
assert.Equal(t, first, second)
}
func TestRedisDefaultsDisabled(t *testing.T) {
cfg, err := config.Load()
require.NoError(t, err)
assert.False(t, cfg.Redis.Enabled)
assert.Equal(t, "localhost", cfg.Redis.Host)
assert.Equal(t, 6379, cfg.Redis.Port)
assert.Equal(t, 5*time.Second, cfg.Redis.DialTimeout)
assert.False(t, cfg.Cache.Enabled)
assert.Equal(t, 5*time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 5*time.Minute, cfg.Cache.SessionTTL)
}
func TestRedisEnvOverrides(t *testing.T) {
t.Setenv("APP_REDIS_ENABLED", "true")
t.Setenv("APP_REDIS_HOST", "cache")
t.Setenv("APP_REDIS_PORT", "6380")
t.Setenv("APP_CACHE_ENABLED", "true")
t.Setenv("APP_CACHE_CHAT_LIST_TTL", "1m")
t.Setenv("APP_CACHE_SESSION_TTL", "30s")
cfg, err := config.Load()
require.NoError(t, err)
assert.True(t, cfg.Redis.Enabled)
assert.Equal(t, "cache", cfg.Redis.Host)
assert.Equal(t, 6380, cfg.Redis.Port)
assert.True(t, cfg.Cache.Enabled)
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 30*time.Second, cfg.Cache.SessionTTL)
}
func TestInvalidCacheTTL(t *testing.T) {
for _, key := range []string{"APP_CACHE_CHAT_LIST_TTL", "APP_CACHE_SESSION_TTL"} {
for _, value := range []string{"0s", "-1s"} {
t.Run(key+"/"+value, func(t *testing.T) {
t.Setenv(key, value)
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
})
}
}
}
+51
View File
@@ -0,0 +1,51 @@
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 len(d.MemberIDs) == 0 {
return fmt.Errorf("member_ids must not be empty: %w", ErrValidation)
}
seen := make(map[uuid.UUID]struct{}, len(d.MemberIDs))
for _, id := range d.MemberIDs {
if _, ok := seen[id]; ok {
return fmt.Errorf("member_ids contains duplicates: %w", ErrValidation)
}
seen[id] = struct{}{}
}
if _, ok := seen[d.CallerID]; !ok {
return fmt.Errorf("member_ids must contain the caller: %w", ErrValidation)
}
return nil
}
+17
View File
@@ -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
}
+13
View File
@@ -0,0 +1,13 @@
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")
ErrConflict = errors.New("conflict")
ErrUnauthenticated = errors.New("unauthenticated")
)
+25
View File
@@ -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)
}
+8
View File
@@ -0,0 +1,8 @@
package domain
const DefaultPageLimit = 50
type Page[T any] struct {
Items []T
Next *Cursor
}
+19
View File
@@ -0,0 +1,19 @@
package domain
import (
"time"
"github.com/google/uuid"
)
type Session struct {
Token string
ExpiresAt time.Time
User User
}
type NewSession struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
}
+14
View File
@@ -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
}
+44
View File
@@ -0,0 +1,44 @@
package domain
import (
"fmt"
"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
Password string
}
func (d UserDraft) Validate() error {
if err := validateNotBlank("display_name", d.DisplayName); err != nil {
return err
}
if length := len([]rune(d.Password)); length < 12 || length > 128 {
return fmt.Errorf("password length must be between 12 and 128 code points: %w", ErrValidation)
}
return nil
}
type NewUser struct {
Username string
DisplayName string
PasswordHash string
}
type UserCredentials struct {
User User
PasswordHash string
}
+107
View File
@@ -0,0 +1,107 @@
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: "Алиса", Password: "very-secret-password"}
assert.NoError(t, draft.Validate())
}
func TestUserDraftRejectsShortPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestUserDraftRejectsTooLongPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 129)}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestUserDraftAcceptsMinimalPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 12)}
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(), "контракт запрещает только полностью пробельный текст")
}
+28
View File
@@ -0,0 +1,28 @@
package health
import (
"context"
"fmt"
)
type Pinger interface {
Ping(ctx context.Context) error
}
type Checker struct {
pingers []Pinger
}
func New(pingers ...Pinger) *Checker {
return &Checker{pingers: pingers}
}
func (c *Checker) Ping(ctx context.Context) error {
for _, pinger := range c.pingers {
if err := pinger.Ping(ctx); err != nil {
return fmt.Errorf("ping %T: %w", pinger, err)
}
}
return nil
}
+33
View File
@@ -0,0 +1,33 @@
package health_test
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/health"
)
type stubPinger struct {
err error
}
func (s stubPinger) Ping(context.Context) error { return s.err }
func TestCheckerPassesWhenAllHealthy(t *testing.T) {
t.Parallel()
checker := health.New(stubPinger{}, stubPinger{})
require.NoError(t, checker.Ping(context.Background()))
}
func TestCheckerReturnsFirstFailure(t *testing.T) {
t.Parallel()
sentinel := errors.New("dependency down")
checker := health.New(stubPinger{}, stubPinger{err: sentinel}, stubPinger{err: errors.New("later")})
require.ErrorIs(t, checker.Ping(context.Background()), sentinel)
}
+8
View File
@@ -0,0 +1,8 @@
package logger
import "errors"
var (
ErrUnknownLevel = errors.New("unknown log level")
ErrUnknownFormat = errors.New("unknown log format")
)
+138
View File
@@ -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
}
}
+193
View File
@@ -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)
})
}
}
+25
View File
@@ -0,0 +1,25 @@
package cache
import (
"context"
"errors"
"time"
)
var ErrCacheMiss = errors.New("cache miss")
type Cache interface {
Get(ctx context.Context, key string) ([]byte, error)
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
Delete(ctx context.Context, keys ...string) error
Ping(ctx context.Context) error
Close() error
}
type NoOpCache struct{}
func (NoOpCache) Get(context.Context, string) ([]byte, error) { return nil, ErrCacheMiss }
func (NoOpCache) Set(context.Context, string, []byte, time.Duration) error { return nil }
func (NoOpCache) Delete(context.Context, ...string) error { return nil }
func (NoOpCache) Ping(context.Context) error { return nil }
func (NoOpCache) Close() error { return nil }
+101
View File
@@ -0,0 +1,101 @@
package cache
import (
"context"
"errors"
"fmt"
"net"
"strconv"
"time"
"github.com/redis/go-redis/v9"
)
type RedisConfig struct {
Host string
Port int
Password string
DB int
MaxRetries int
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
PoolSize int
}
type RedisCache struct {
client *redis.Client
}
func NewRedis(cfg RedisConfig) (*RedisCache, error) {
client := redis.NewClient(&redis.Options{
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
Password: cfg.Password,
DB: cfg.DB,
MaxRetries: cfg.MaxRetries,
DialTimeout: cfg.DialTimeout,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
PoolSize: cfg.PoolSize,
})
ctx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
defer cancel()
if err := client.Ping(ctx).Err(); err != nil {
_ = client.Close()
return nil, fmt.Errorf("ping redis: %w", err)
}
return &RedisCache{client: client}, nil
}
func (r *RedisCache) Get(ctx context.Context, key string) ([]byte, error) {
value, err := r.client.Get(ctx, key).Bytes()
if errors.Is(err, redis.Nil) {
return nil, ErrCacheMiss
}
if err != nil {
return nil, fmt.Errorf("redis get %q: %w", key, err)
}
return value, nil
}
func (r *RedisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
if err := r.client.Set(ctx, key, value, ttl).Err(); err != nil {
return fmt.Errorf("redis set %q: %w", key, err)
}
return nil
}
func (r *RedisCache) Delete(ctx context.Context, keys ...string) error {
if len(keys) == 0 {
return nil
}
if err := r.client.Del(ctx, keys...).Err(); err != nil {
return fmt.Errorf("redis delete: %w", err)
}
return nil
}
func (r *RedisCache) Ping(ctx context.Context) error {
if err := r.client.Ping(ctx).Err(); err != nil {
return fmt.Errorf("redis ping: %w", err)
}
return nil
}
func (r *RedisCache) Close() error {
if err := r.client.Close(); err != nil {
return fmt.Errorf("redis close: %w", err)
}
return nil
}
+79
View File
@@ -0,0 +1,79 @@
package cache
import (
"context"
"errors"
"time"
"golang.org/x/sync/singleflight"
)
type SingleflightCache struct {
cache Cache
group singleflight.Group
}
func WithSingleflight(cache Cache) *SingleflightCache {
return &SingleflightCache{cache: cache}
}
func (s *SingleflightCache) GetOrLoad(
ctx context.Context,
key string,
ttl time.Duration,
loader func(ctx context.Context) ([]byte, error),
) ([]byte, error) {
value, err := s.cache.Get(ctx, key)
if err == nil {
return value, nil
}
if !errors.Is(err, ErrCacheMiss) {
return loader(ctx)
}
result, err, _ := s.group.Do(key, func() (any, error) {
loadCtx := context.WithoutCancel(ctx)
if cached, err := s.cache.Get(loadCtx, key); err == nil {
return cached, nil
}
loaded, loadErr := loader(loadCtx)
if loadErr != nil {
return nil, loadErr
}
_ = s.cache.Set(loadCtx, key, loaded, ttl)
return loaded, nil
})
if err != nil {
return nil, err
}
loaded, ok := result.([]byte)
if !ok {
return nil, errors.New("cache: unexpected singleflight result")
}
return loaded, nil
}
func (s *SingleflightCache) Get(ctx context.Context, key string) ([]byte, error) {
return s.cache.Get(ctx, key)
}
func (s *SingleflightCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
return s.cache.Set(ctx, key, value, ttl)
}
func (s *SingleflightCache) Delete(ctx context.Context, keys ...string) error {
return s.cache.Delete(ctx, keys...)
}
func (s *SingleflightCache) Ping(ctx context.Context) error {
return s.cache.Ping(ctx)
}
func (s *SingleflightCache) Close() error {
return s.cache.Close()
}
+165
View File
@@ -0,0 +1,165 @@
package cache_test
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/cache"
)
type memoryCache struct {
mu sync.Mutex
data map[string][]byte
}
func newMemoryCache() *memoryCache {
return &memoryCache{data: make(map[string][]byte)}
}
func (m *memoryCache) Get(_ context.Context, key string) ([]byte, error) {
m.mu.Lock()
defer m.mu.Unlock()
value, ok := m.data[key]
if !ok {
return nil, cache.ErrCacheMiss
}
return value, nil
}
func (m *memoryCache) Set(_ context.Context, key string, value []byte, _ time.Duration) error {
m.mu.Lock()
defer m.mu.Unlock()
m.data[key] = value
return nil
}
func (m *memoryCache) Delete(_ context.Context, keys ...string) error {
m.mu.Lock()
defer m.mu.Unlock()
for _, key := range keys {
delete(m.data, key)
}
return nil
}
func (m *memoryCache) Ping(context.Context) error { return nil }
func (m *memoryCache) Close() error { return nil }
func TestNoOpCacheAlwaysMisses(t *testing.T) {
t.Parallel()
noop := cache.NoOpCache{}
_, err := noop.Get(context.Background(), "key")
require.ErrorIs(t, err, cache.ErrCacheMiss)
require.NoError(t, noop.Set(context.Background(), "key", []byte("v"), time.Minute))
}
func TestGetOrLoadCachesResult(t *testing.T) {
t.Parallel()
sf := cache.WithSingleflight(newMemoryCache())
ctx := context.Background()
var calls atomic.Int32
loader := func(context.Context) ([]byte, error) {
calls.Add(1)
return []byte("payload"), nil
}
first, err := sf.GetOrLoad(ctx, "key", time.Minute, loader)
require.NoError(t, err)
require.Equal(t, []byte("payload"), first)
second, err := sf.GetOrLoad(ctx, "key", time.Minute, loader)
require.NoError(t, err)
require.Equal(t, []byte("payload"), second)
require.Equal(t, int32(1), calls.Load(), "loader must run once")
}
func TestGetOrLoadDeduplicatesConcurrentMisses(t *testing.T) {
t.Parallel()
sf := cache.WithSingleflight(newMemoryCache())
ctx := context.Background()
var calls atomic.Int32
loader := func(context.Context) ([]byte, error) {
calls.Add(1)
time.Sleep(50 * time.Millisecond)
return []byte("payload"), nil
}
const workers = 50
var (
wg sync.WaitGroup
failures atomic.Int32
)
wg.Add(workers)
for range workers {
go func() {
defer wg.Done()
value, err := sf.GetOrLoad(ctx, "shared", time.Minute, loader)
if err != nil || string(value) != "payload" {
failures.Add(1)
}
}()
}
wg.Wait()
require.Zero(t, failures.Load())
require.Equal(t, int32(1), calls.Load(), "singleflight must collapse concurrent misses")
}
func TestLeaderCancellationDoesNotCancelSharedLoad(t *testing.T) {
t.Parallel()
sf := cache.WithSingleflight(newMemoryCache())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
started := make(chan struct{})
release := make(chan struct{})
result := make(chan error, 1)
go func() {
_, err := sf.GetOrLoad(ctx, "cancelled-leader", time.Minute,
func(loadCtx context.Context) ([]byte, error) {
close(started)
<-release
if err := loadCtx.Err(); err != nil {
return nil, err
}
return []byte("payload"), nil
})
result <- err
}()
<-started
cancel()
close(release)
require.NoError(t, <-result)
value, err := sf.GetOrLoad(t.Context(), "cancelled-leader", time.Minute,
func(context.Context) ([]byte, error) {
return []byte("unexpected reload"), nil
})
require.NoError(t, err)
require.Equal(t, "payload", string(value))
}
+52
View File
@@ -0,0 +1,52 @@
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonTime = 1
argonMemory = 64 * 1024
argonThreads = 4
argonKeyLen = 32
argonSaltLen = 16
)
func Hash(plain string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
hash := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return "argon2id$" +
base64.RawStdEncoding.EncodeToString(salt) + "$" +
base64.RawStdEncoding.EncodeToString(hash), nil
}
func Verify(plain, encoded string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 3 || parts[0] != "argon2id" {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
if err != nil {
return false
}
expected, err := base64.RawStdEncoding.DecodeString(parts[2])
if err != nil || len(salt) != argonSaltLen || len(expected) != argonKeyLen {
return false
}
actual := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return subtle.ConstantTimeCompare(actual, expected) == 1
}
@@ -0,0 +1,33 @@
package password_test
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/password"
)
func TestHashVerifyRoundTrip(t *testing.T) {
encoded, err := password.Hash("very-secret-password")
require.NoError(t, err)
require.True(t, password.Verify("very-secret-password", encoded))
require.False(t, password.Verify("wrong-password-value", encoded))
}
func TestHashIsSalted(t *testing.T) {
first, err := password.Hash("very-secret-password")
require.NoError(t, err)
second, err := password.Hash("very-secret-password")
require.NoError(t, err)
require.NotEqual(t, first, second)
}
func TestVerifyRejectsMalformedHash(t *testing.T) {
require.False(t, password.Verify("very-secret-password", ""))
require.False(t, password.Verify("very-secret-password", "plain-text"))
require.False(t, password.Verify("very-secret-password", strings.Repeat("x", 64)))
}
+40
View File
@@ -0,0 +1,40 @@
package token
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
)
const size = 32
var ErrInvalid = errors.New("invalid token")
type Token struct{}
func New() Token {
return Token{}
}
func (Token) Generate() (string, []byte, error) {
raw := make([]byte, size)
if _, err := rand.Read(raw); err != nil {
return "", nil, err
}
sum := sha256.Sum256(raw)
return base64.RawURLEncoding.EncodeToString(raw), sum[:], nil
}
func (Token) Hash(raw string) ([]byte, error) {
decoded, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil || len(decoded) != size {
return nil, ErrInvalid
}
sum := sha256.Sum256(decoded)
return sum[:], nil
}
+44
View File
@@ -0,0 +1,44 @@
package token_test
import (
"crypto/sha256"
"testing"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/token"
)
func TestGenerateProducesUniqueOpaqueTokens(t *testing.T) {
tokens := token.New()
first, firstHash, err := tokens.Generate()
require.NoError(t, err)
require.NotEmpty(t, first)
require.Len(t, firstHash, sha256.Size)
second, secondHash, err := tokens.Generate()
require.NoError(t, err)
require.NotEqual(t, first, second)
require.NotEqual(t, firstHash, secondHash)
}
func TestHashMatchesGeneratedHash(t *testing.T) {
tokens := token.New()
raw, hash, err := tokens.Generate()
require.NoError(t, err)
actual, err := tokens.Hash(raw)
require.NoError(t, err)
require.Equal(t, hash, actual)
}
func TestHashRejectsMalformed(t *testing.T) {
tokens := token.New()
for _, raw := range []string{"", "not-base64!", "c2hvcnQ"} {
_, err := tokens.Hash(raw)
require.ErrorIs(t, err, token.ErrInvalid, raw)
}
}
+265
View File
@@ -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
}
+69
View File
@@ -0,0 +1,69 @@
package chat
import (
"context"
"fmt"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
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
}
+140
View File
@@ -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
}
+59
View File
@@ -0,0 +1,59 @@
package message
import (
"context"
"fmt"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
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
}
+143
View File
@@ -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,310 @@
// 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, session domain.NewSession) (domain.Session, error) {
ret := _mock.Called(ctx, session)
if len(ret) == 0 {
panic("no return value specified for Create")
}
var r0 domain.Session
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) (domain.Session, error)); ok {
return returnFunc(ctx, session)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) domain.Session); ok {
r0 = returnFunc(ctx, session)
} else {
r0 = ret.Get(0).(domain.Session)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewSession) error); ok {
r1 = returnFunc(ctx, session)
} 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
// - session domain.NewSession
func (_e *MockRepository_Expecter) Create(ctx any, session any) *MockRepository_Create_Call {
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, session)}
}
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, session domain.NewSession)) *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.NewSession
if args[1] != nil {
arg1 = args[1].(domain.NewSession)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Create_Call) Return(session1 domain.Session, err error) *MockRepository_Create_Call {
_c.Call.Return(session1, err)
return _c
}
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, session domain.NewSession) (domain.Session, error)) *MockRepository_Create_Call {
_c.Call.Return(run)
return _c
}
// Credentials provides a mock function for the type MockRepository
func (_mock *MockRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
ret := _mock.Called(ctx, username)
if len(ret) == 0 {
panic("no return value specified for Credentials")
}
var r0 domain.UserCredentials
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.UserCredentials, error)); ok {
return returnFunc(ctx, username)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.UserCredentials); ok {
r0 = returnFunc(ctx, username)
} else {
r0 = ret.Get(0).(domain.UserCredentials)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
r1 = returnFunc(ctx, username)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_Credentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Credentials'
type MockRepository_Credentials_Call struct {
*mock.Call
}
// Credentials is a helper method to define mock.On call
// - ctx context.Context
// - username string
func (_e *MockRepository_Expecter) Credentials(ctx any, username any) *MockRepository_Credentials_Call {
return &MockRepository_Credentials_Call{Call: _e.mock.On("Credentials", ctx, username)}
}
func (_c *MockRepository_Credentials_Call) Run(run func(ctx context.Context, username string)) *MockRepository_Credentials_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Credentials_Call) Return(userCredentials domain.UserCredentials, err error) *MockRepository_Credentials_Call {
_c.Call.Return(userCredentials, err)
return _c
}
func (_c *MockRepository_Credentials_Call) RunAndReturn(run func(ctx context.Context, username string) (domain.UserCredentials, error)) *MockRepository_Credentials_Call {
_c.Call.Return(run)
return _c
}
// Resolve provides a mock function for the type MockRepository
func (_mock *MockRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
ret := _mock.Called(ctx, tokenHash)
if len(ret) == 0 {
panic("no return value specified for Resolve")
}
var r0 domain.Session
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) (domain.Session, error)); ok {
return returnFunc(ctx, tokenHash)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) domain.Session); ok {
r0 = returnFunc(ctx, tokenHash)
} else {
r0 = ret.Get(0).(domain.Session)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok {
r1 = returnFunc(ctx, tokenHash)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
type MockRepository_Resolve_Call struct {
*mock.Call
}
// Resolve is a helper method to define mock.On call
// - ctx context.Context
// - tokenHash []byte
func (_e *MockRepository_Expecter) Resolve(ctx any, tokenHash any) *MockRepository_Resolve_Call {
return &MockRepository_Resolve_Call{Call: _e.mock.On("Resolve", ctx, tokenHash)}
}
func (_c *MockRepository_Resolve_Call) Run(run func(ctx context.Context, tokenHash []byte)) *MockRepository_Resolve_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 []byte
if args[1] != nil {
arg1 = args[1].([]byte)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Resolve_Call) Return(session domain.Session, err error) *MockRepository_Resolve_Call {
_c.Call.Return(session, err)
return _c
}
func (_c *MockRepository_Resolve_Call) RunAndReturn(run func(ctx context.Context, tokenHash []byte) (domain.Session, error)) *MockRepository_Resolve_Call {
_c.Call.Return(run)
return _c
}
// Revoke provides a mock function for the type MockRepository
func (_mock *MockRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
ret := _mock.Called(ctx, userID, tokenHash)
if len(ret) == 0 {
panic("no return value specified for Revoke")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []byte) error); ok {
r0 = returnFunc(ctx, userID, tokenHash)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockRepository_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
type MockRepository_Revoke_Call struct {
*mock.Call
}
// Revoke is a helper method to define mock.On call
// - ctx context.Context
// - userID uuid.UUID
// - tokenHash []byte
func (_e *MockRepository_Expecter) Revoke(ctx any, userID any, tokenHash any) *MockRepository_Revoke_Call {
return &MockRepository_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, tokenHash)}
}
func (_c *MockRepository_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte)) *MockRepository_Revoke_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 []byte
if args[2] != nil {
arg2 = args[2].([]byte)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_Revoke_Call) Return(err error) *MockRepository_Revoke_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockRepository_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte) error) *MockRepository_Revoke_Call {
_c.Call.Return(run)
return _c
}
+168
View File
@@ -0,0 +1,168 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
mock "github.com/stretchr/testify/mock"
)
// NewMockTokens creates a new instance of MockTokens. 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 NewMockTokens(t interface {
mock.TestingT
Cleanup(func())
}) *MockTokens {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockTokens{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockTokens is an autogenerated mock type for the Tokens type
type MockTokens struct {
mock.Mock
}
type MockTokens_Expecter struct {
mock *mock.Mock
}
func (_m *MockTokens) EXPECT() *MockTokens_Expecter {
return &MockTokens_Expecter{mock: &_m.Mock}
}
// Generate provides a mock function for the type MockTokens
func (_mock *MockTokens) Generate() (string, []byte, error) {
ret := _mock.Called()
if len(ret) == 0 {
panic("no return value specified for Generate")
}
var r0 string
var r1 []byte
var r2 error
if returnFunc, ok := ret.Get(0).(func() (string, []byte, error)); ok {
return returnFunc()
}
if returnFunc, ok := ret.Get(0).(func() string); ok {
r0 = returnFunc()
} else {
r0 = ret.Get(0).(string)
}
if returnFunc, ok := ret.Get(1).(func() []byte); ok {
r1 = returnFunc()
} else {
if ret.Get(1) != nil {
r1 = ret.Get(1).([]byte)
}
}
if returnFunc, ok := ret.Get(2).(func() error); ok {
r2 = returnFunc()
} else {
r2 = ret.Error(2)
}
return r0, r1, r2
}
// MockTokens_Generate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Generate'
type MockTokens_Generate_Call struct {
*mock.Call
}
// Generate is a helper method to define mock.On call
func (_e *MockTokens_Expecter) Generate() *MockTokens_Generate_Call {
return &MockTokens_Generate_Call{Call: _e.mock.On("Generate")}
}
func (_c *MockTokens_Generate_Call) Run(run func()) *MockTokens_Generate_Call {
_c.Call.Run(func(args mock.Arguments) {
run()
})
return _c
}
func (_c *MockTokens_Generate_Call) Return(s string, bytes []byte, err error) *MockTokens_Generate_Call {
_c.Call.Return(s, bytes, err)
return _c
}
func (_c *MockTokens_Generate_Call) RunAndReturn(run func() (string, []byte, error)) *MockTokens_Generate_Call {
_c.Call.Return(run)
return _c
}
// Hash provides a mock function for the type MockTokens
func (_mock *MockTokens) Hash(raw string) ([]byte, error) {
ret := _mock.Called(raw)
if len(ret) == 0 {
panic("no return value specified for Hash")
}
var r0 []byte
var r1 error
if returnFunc, ok := ret.Get(0).(func(string) ([]byte, error)); ok {
return returnFunc(raw)
}
if returnFunc, ok := ret.Get(0).(func(string) []byte); ok {
r0 = returnFunc(raw)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]byte)
}
}
if returnFunc, ok := ret.Get(1).(func(string) error); ok {
r1 = returnFunc(raw)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockTokens_Hash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Hash'
type MockTokens_Hash_Call struct {
*mock.Call
}
// Hash is a helper method to define mock.On call
// - raw string
func (_e *MockTokens_Expecter) Hash(raw any) *MockTokens_Hash_Call {
return &MockTokens_Hash_Call{Call: _e.mock.On("Hash", raw)}
}
func (_c *MockTokens_Hash_Call) Run(run func(raw string)) *MockTokens_Hash_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 string
if args[0] != nil {
arg0 = args[0].(string)
}
run(
arg0,
)
})
return _c
}
func (_c *MockTokens_Hash_Call) Return(bytes []byte, err error) *MockTokens_Hash_Call {
_c.Call.Return(bytes, err)
return _c
}
func (_c *MockTokens_Hash_Call) RunAndReturn(run func(raw string) ([]byte, error)) *MockTokens_Hash_Call {
_c.Call.Return(run)
return _c
}
+95
View File
@@ -0,0 +1,95 @@
package session
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
)
type Repository interface {
Credentials(ctx context.Context, username string) (domain.UserCredentials, error)
Create(ctx context.Context, session domain.NewSession) (domain.Session, error)
Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error)
Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error
}
type Tokens interface {
Generate() (string, []byte, error)
Hash(raw string) ([]byte, error)
}
type Service struct {
sessions Repository
tokens Tokens
ttl time.Duration
}
func NewService(sessions Repository, tokens Tokens, ttl time.Duration) *Service {
return &Service{sessions: sessions, tokens: tokens, ttl: ttl}
}
func (s *Service) Authenticate(ctx context.Context, username, plain string) (domain.User, error) {
credentials, err := s.sessions.Credentials(ctx, username)
if err != nil {
return domain.User{}, fmt.Errorf("authenticate: %w", err)
}
if !password.Verify(plain, credentials.PasswordHash) {
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
}
return credentials.User, nil
}
func (s *Service) Resolve(ctx context.Context, raw string) (domain.User, error) {
hash, err := s.tokens.Hash(raw)
if err != nil {
return domain.User{}, fmt.Errorf("resolve session: %w", domain.ErrUnauthenticated)
}
session, err := s.sessions.Resolve(ctx, hash)
if err != nil {
return domain.User{}, fmt.Errorf("resolve session: %w", err)
}
return session.User, nil
}
func (s *Service) Create(ctx context.Context, user domain.User) (domain.Session, error) {
raw, hash, err := s.tokens.Generate()
if err != nil {
return domain.Session{}, fmt.Errorf("generate token: %w", err)
}
session, err := s.sessions.Create(ctx, domain.NewSession{
TokenHash: hash,
UserID: user.ID,
ExpiresAt: time.Now().UTC().Add(s.ttl),
})
if err != nil {
return domain.Session{}, fmt.Errorf("create session: %w", err)
}
session.Token = raw
session.User = user
return session, nil
}
func (s *Service) Revoke(ctx context.Context, userID uuid.UUID, raw string) error {
hash, err := s.tokens.Hash(raw)
if err != nil {
return fmt.Errorf("revoke session: %w", domain.ErrUnauthenticated)
}
if err := s.sessions.Revoke(ctx, userID, hash); err != nil {
return fmt.Errorf("revoke session: %w", err)
}
return nil
}
+146
View File
@@ -0,0 +1,146 @@
package session_test
import (
"bytes"
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
"mtusi-messenger/internal/service/session"
"mtusi-messenger/internal/service/session/mocks"
)
type ServiceSuite struct {
suite.Suite
sessions *mocks.MockRepository
tokens *mocks.MockTokens
service *session.Service
ttl time.Duration
user domain.User
}
func TestServiceSuite(t *testing.T) {
t.Parallel()
suite.Run(t, new(ServiceSuite))
}
func (s *ServiceSuite) SetupTest() {
s.sessions = mocks.NewMockRepository(s.T())
s.tokens = mocks.NewMockTokens(s.T())
s.ttl = time.Hour
s.service = session.NewService(s.sessions, s.tokens, s.ttl)
s.user = domain.User{
ID: uuid.New(),
Username: "alice",
DisplayName: "Алиса",
CreatedAt: time.Now().UTC(),
}
}
func (s *ServiceSuite) TestResolveHashesTokenBeforeStorage() {
hash := []byte("hashed-token")
stored := domain.Session{ExpiresAt: time.Now().Add(time.Hour), User: s.user}
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
s.sessions.EXPECT().Resolve(mock.Anything, hash).Return(stored, nil).Once()
got, err := s.service.Resolve(s.T().Context(), "raw-token")
s.Require().NoError(err)
s.Equal(s.user, got)
}
func (s *ServiceSuite) TestResolveRejectsMalformedTokenWithoutStorage() {
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
_, err := s.service.Resolve(s.T().Context(), "garbage")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *ServiceSuite) TestCreateGeneratesTokenAndReturnsIt() {
hash := []byte("hashed-token")
expiresAt := time.Now().Add(s.ttl)
s.tokens.EXPECT().Generate().Return("raw-token", hash, nil).Once()
s.sessions.EXPECT().
Create(mock.Anything, mock.MatchedBy(func(candidate domain.NewSession) bool {
return bytes.Equal(candidate.TokenHash, hash) &&
candidate.UserID == s.user.ID &&
candidate.ExpiresAt.After(time.Now())
})).
Return(domain.Session{ExpiresAt: expiresAt}, nil).
Once()
got, err := s.service.Create(s.T().Context(), s.user)
s.Require().NoError(err)
s.Equal("raw-token", got.Token)
s.Equal(s.user, got.User)
s.Equal(expiresAt, got.ExpiresAt)
}
func (s *ServiceSuite) TestCreatePropagatesTokenGenerationError() {
s.tokens.EXPECT().Generate().Return("", nil, errors.New("no entropy")).Once()
_, err := s.service.Create(s.T().Context(), s.user)
s.Require().Error(err)
}
func (s *ServiceSuite) TestRevokeHashesTokenBeforeStorage() {
hash := []byte("hashed-token")
userID := uuid.New()
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
s.sessions.EXPECT().Revoke(mock.Anything, userID, hash).Return(nil).Once()
s.Require().NoError(s.service.Revoke(s.T().Context(), userID, "raw-token"))
}
func (s *ServiceSuite) TestRevokeRejectsMalformedToken() {
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
err := s.service.Revoke(s.T().Context(), uuid.New(), "garbage")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *ServiceSuite) TestAuthenticateVerifiesPassword() {
hash, err := password.Hash("secret-password-123")
s.Require().NoError(err)
s.sessions.EXPECT().
Credentials(mock.Anything, "alice").
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
Once()
got, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
s.Require().NoError(err)
s.Equal(s.user, got)
}
func (s *ServiceSuite) TestAuthenticateRejectsWrongPassword() {
hash, err := password.Hash("secret-password-123")
s.Require().NoError(err)
s.sessions.EXPECT().
Credentials(mock.Anything, "alice").
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
Once()
_, err = s.service.Authenticate(s.T().Context(), "alice", "wrong-password-value")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *ServiceSuite) TestAuthenticatePropagatesUnknownUser() {
s.sessions.EXPECT().
Credentials(mock.Anything, "nobody").
Return(domain.UserCredentials{}, domain.ErrUnauthenticated).
Once()
_, err := s.service.Authenticate(s.T().Context(), "nobody", "secret-password-123")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
+181
View File
@@ -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.NewUser) (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.NewUser) (domain.User, error)); ok {
return returnFunc(ctx, draft)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) domain.User); ok {
r0 = returnFunc(ctx, draft)
} else {
r0 = ret.Get(0).(domain.User)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewUser) 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.NewUser
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.NewUser)) *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.NewUser
if args[1] != nil {
arg1 = args[1].(domain.NewUser)
}
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.NewUser) (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
}
+55
View File
@@ -0,0 +1,55 @@
package user
import (
"context"
"fmt"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
)
type Repository interface {
Create(ctx context.Context, draft domain.NewUser) (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
}
hash, err := password.Hash(draft.Password)
if err != nil {
return domain.User{}, fmt.Errorf("hash password: %w", err)
}
user, err := s.users.Create(ctx, domain.NewUser{
Username: draft.Username,
DisplayName: draft.DisplayName,
PasswordHash: hash,
})
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
}
+104
View File
@@ -0,0 +1,104 @@
package user_test
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"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) TestRegisterHashesPasswordAndReturnsStoredUser() {
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
stored := domain.User{
ID: uuid.New(),
Username: draft.Username,
DisplayName: draft.DisplayName,
CreatedAt: s.now,
}
s.users.EXPECT().
Create(s.T().Context(), mock.MatchedBy(func(candidate domain.NewUser) bool {
return candidate.Username == draft.Username &&
candidate.DisplayName == draft.DisplayName &&
candidate.PasswordHash != "" &&
candidate.PasswordHash != draft.Password
})).
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: " ", Password: "very-secret-password"}
_, err := s.service.Register(s.T().Context(), draft)
s.Require().ErrorIs(err, domain.ErrValidation)
}
func (s *ServiceSuite) TestRegisterRejectsShortPasswordWithoutRepositoryCall() {
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
_, err := s.service.Register(s.T().Context(), draft)
s.Require().ErrorIs(err, domain.ErrValidation)
}
func (s *ServiceSuite) TestRegisterPropagatesUsernameConflict() {
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
s.users.EXPECT().
Create(s.T().Context(), mock.Anything).
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,163 @@
//go:build integration
package postgres_test
import (
"context"
"fmt"
"sort"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
storageredis "mtusi-messenger/internal/storage/redis"
)
func TestCacheLatencyExperiment(t *testing.T) {
suite := new(BaseSuite)
suite.SetT(t)
suite.SetupTest()
defer suite.TearDownTest()
ctx := context.Background()
redisConfig := cache.RedisConfig{
Host: envOr("TEST_REDIS_HOST", "localhost"),
Port: envInt("TEST_REDIS_PORT", 6379),
Password: envOr("TEST_REDIS_PASSWORD", ""),
DB: envInt("TEST_REDIS_DB", 1),
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: 5,
}
redisCache, err := cache.NewRedis(redisConfig)
require.NoError(t, err)
defer func() { _ = redisCache.Close() }()
alice := suite.createUser("latency_alice")
for range 20 {
suite.createChat(alice)
}
source := &countingChatSource{source: suite.store.Chats()}
for range 50 {
_, err := source.ListVisible(ctx, alice.ID, nil, 50)
require.NoError(t, err)
}
source.loads.Store(0)
baseline := measureLatency(ctx, t, source, alice.ID, 1000)
cached := storageredis.NewChatRepository(
source,
cache.WithSingleflight(redisCache),
time.Minute,
nil,
)
source.loads.Store(0)
cachedStats := measureCachedLatency(ctx, t, cached, alice.ID, 1000)
cachedStats.Loads = int(source.loads.Load())
require.Equal(t, 1000, baseline.Loads)
require.Equal(t, 1, cachedStats.Loads)
t.Logf("baseline: %s", formatLatency(baseline))
t.Logf("redis cache: %s", formatLatency(cachedStats))
}
type countingChatSource struct {
source interface {
ListVisible(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)
}
loads atomic.Int32
}
func (s *countingChatSource) Create(context.Context, domain.ChatDraft) (domain.Chat, error) {
return domain.Chat{}, nil
}
func (s *countingChatSource) GetVisible(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error) {
return domain.Chat{}, domain.ErrNotFound
}
func (s *countingChatSource) ListVisible(
ctx context.Context,
callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Chat], error) {
s.loads.Add(1)
return s.source.ListVisible(ctx, callerID, after, limit)
}
func measureLatency(
ctx context.Context,
t *testing.T,
source *countingChatSource,
callerID uuid.UUID,
requests int,
) latencyStats {
t.Helper()
values := make([]time.Duration, 0, requests)
for range requests {
started := time.Now()
_, err := source.ListVisible(ctx, callerID, nil, 50)
require.NoError(t, err)
values = append(values, time.Since(started))
}
return makeLatencyStats(values, int(source.loads.Load()))
}
func measureCachedLatency(
ctx context.Context,
t *testing.T,
repository *storageredis.ChatRepository,
callerID uuid.UUID,
requests int,
) latencyStats {
t.Helper()
values := make([]time.Duration, 0, requests)
for range requests {
started := time.Now()
_, err := repository.ListVisible(ctx, callerID, nil, 50)
require.NoError(t, err)
values = append(values, time.Since(started))
}
return makeLatencyStats(values, 0)
}
type latencyStats struct {
Requests int
Loads int
P50 time.Duration
P95 time.Duration
P99 time.Duration
}
func makeLatencyStats(values []time.Duration, loads int) latencyStats {
sort.Slice(values, func(i, j int) bool { return values[i] < values[j] })
percentile := func(percent int) time.Duration {
index := (len(values)*percent + 99) / 100
if index > 0 {
index--
}
return values[index]
}
return latencyStats{
Requests: len(values), Loads: loads,
P50: percentile(50), P95: percentile(95), P99: percentile(99),
}
}
func formatLatency(value latencyStats) string {
return fmt.Sprintf(
"requests=%d source_loads=%d p50=%s p95=%s p99=%s",
value.Requests, value.Loads, value.P50, value.P95, value.P99,
)
}
@@ -0,0 +1,197 @@
//go:build integration
package postgres_test
import (
"context"
"fmt"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
storageredis "mtusi-messenger/internal/storage/redis"
)
func TestCachePerformanceExperiment(t *testing.T) {
suite := new(BaseSuite)
suite.SetT(t)
suite.SetupTest()
defer suite.TearDownTest()
ctx := context.Background()
redisConfig := cache.RedisConfig{
Host: envOr("TEST_REDIS_HOST", "localhost"),
Port: envInt("TEST_REDIS_PORT", 6379),
Password: envOr("TEST_REDIS_PASSWORD", ""),
DB: envInt("TEST_REDIS_DB", 1),
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: 10,
}
redisCache, err := cache.NewRedis(redisConfig)
require.NoError(t, err)
defer func() { _ = redisCache.Close() }()
alice := suite.createUser("perf_alice")
bob := suite.createUser("perf_bob")
carol := suite.createUser("perf_carol")
for i := range 150 {
title := fmt.Sprintf("Chat %d with Alice", i+1)
members := []uuid.UUID{alice.ID}
if i%3 == 0 {
members = append(members, bob.ID)
}
if i%5 == 0 {
members = append(members, carol.ID)
}
_, err := suite.store.Chats().Create(ctx, domain.ChatDraft{
Title: title,
MemberIDs: members,
})
require.NoError(t, err)
}
source := &perfChatSource{source: suite.store.Chats()}
cached := storageredis.NewChatRepository(
source,
cache.WithSingleflight(redisCache),
time.Minute,
nil,
)
baselineStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
_, err := source.ListVisible(ctx, alice.ID, nil, 50)
return err
}, 50, 200)
baselineStats.SQLQueries = int(source.loads.Load())
source.loads.Store(0)
cachedStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
_, err := cached.ListVisible(ctx, alice.ID, nil, 50)
return err
}, 50, 200)
cachedStats.SQLQueries = int(source.loads.Load())
source.loads.Store(0)
_, err = cached.ListVisible(ctx, alice.ID, nil, 50)
require.NoError(t, err)
cachedHotStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
_, err := cached.ListVisible(ctx, alice.ID, nil, 50)
return err
}, 50, 200)
cachedHotStats.SQLQueries = int(source.loads.Load())
t.Logf("baseline (no cache): %s", formatPerfStats(baselineStats))
t.Logf("redis cache (cold): %s", formatPerfStats(cachedStats))
t.Logf("redis cache (hot): %s", formatPerfStats(cachedHotStats))
}
type perfChatSource struct {
source interface {
ListVisible(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)
}
loads atomic.Int32
}
func (s *perfChatSource) Create(context.Context, domain.ChatDraft) (domain.Chat, error) {
return domain.Chat{}, nil
}
func (s *perfChatSource) GetVisible(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error) {
return domain.Chat{}, domain.ErrNotFound
}
func (s *perfChatSource) ListVisible(
ctx context.Context,
callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Chat], error) {
s.loads.Add(1)
return s.source.ListVisible(ctx, callerID, after, limit)
}
type perfStats struct {
TotalRequests int
Concurrency int
SQLQueries int
Duration time.Duration
RPS float64
P50 time.Duration
P95 time.Duration
P99 time.Duration
}
func benchmarkConcurrent(
ctx context.Context,
t *testing.T,
operation func(context.Context) error,
concurrency int,
requestsPerWorker int,
) perfStats {
t.Helper()
totalRequests := concurrency * requestsPerWorker
latencies := make([]time.Duration, totalRequests)
var wg sync.WaitGroup
var failures atomic.Int32
started := time.Now()
for worker := range concurrency {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
offset := workerID * requestsPerWorker
for i := range requestsPerWorker {
reqStart := time.Now()
err := operation(ctx)
if err != nil {
failures.Add(1)
}
latencies[offset+i] = time.Since(reqStart)
}
}(worker)
}
wg.Wait()
require.Zero(t, failures.Load(), "some requests failed")
duration := time.Since(started)
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
percentile := func(p int) time.Duration {
index := (len(latencies)*p + 99) / 100
if index > 0 {
index--
}
return latencies[index]
}
return perfStats{
TotalRequests: totalRequests,
Concurrency: concurrency,
Duration: duration,
RPS: float64(totalRequests) / duration.Seconds(),
P50: percentile(50),
P95: percentile(95),
P99: percentile(99),
}
}
func formatPerfStats(s perfStats) string {
return fmt.Sprintf(
"requests=%d concurrency=%d sql=%d duration=%s rps=%.0f p50=%s p95=%s p99=%s",
s.TotalRequests, s.Concurrency, s.SQLQueries, s.Duration.Round(time.Millisecond),
s.RPS, s.P50, s.P95, s.P99,
)
}
@@ -0,0 +1,135 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type ChatRepository struct {
store *Store
}
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
var created domain.Chat
if err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
missing, err := queries.ListMissingUserIDs(ctx, draft.MemberIDs)
if err != nil {
return fmt.Errorf("check chat members: %w", mapError(err))
}
if len(missing) > 0 {
return domain.ErrUnknownMember
}
row, err := queries.CreateChat(ctx, draft.Title)
if err != nil {
return fmt.Errorf("create chat: %w", mapError(err))
}
if err := queries.AddChatMembers(ctx, sqlcgen.AddChatMembersParams{
ChatID: row.ID,
UserIds: draft.MemberIDs,
}); err != nil {
return fmt.Errorf("add chat members: %w", mapError(err))
}
created = mapChat(row.ID, row.Title, row.CreatedAt, draft.MemberIDs)
return nil
}); err != nil {
return domain.Chat{}, err
}
return created, nil
}
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetChatForMember(ctx, sqlcgen.GetChatForMemberParams{
UserID: callerID,
ID: chatID,
})
if err != nil {
mapped := mapError(err)
if errors.Is(mapped, domain.ErrNotFound) {
return domain.Chat{}, fmt.Errorf("%w: chat %s for user %s", domain.ErrNotFound, chatID, callerID)
}
return domain.Chat{}, fmt.Errorf("get chat: %w", mapped)
}
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds), nil
}
func (r *ChatRepository) ListVisible(
ctx context.Context,
callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Chat], error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
limit = clampLimit(limit)
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
var rows []domain.Chat
if after == nil {
pageRows, err := r.store.queries.ListChatsForMember(ctx, sqlcgen.ListChatsForMemberParams{
UserID: callerID,
RowLimit: fetch,
})
if err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
}
rows = mapAll(pageRows, mapChatRow)
} else {
pageRows, err := r.store.queries.ListChatsForMemberAfter(ctx, sqlcgen.ListChatsForMemberAfterParams{
UserID: callerID,
AfterCreatedAt: after.CreatedAt,
AfterID: after.ID,
RowLimit: fetch,
})
if err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
}
rows = mapAll(pageRows, mapChatRowAfter)
}
return buildPage(rows, limit, func(chat domain.Chat) domain.Cursor {
return domain.Cursor{Scope: callerID, CreatedAt: chat.CreatedAt, ID: chat.ID}
}), nil
}
func mapChatRow(row sqlcgen.ListChatsForMemberRow) domain.Chat {
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
}
func mapChatRowAfter(row sqlcgen.ListChatsForMemberAfterRow) domain.Chat {
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
}
func mapChat(id uuid.UUID, title string, createdAt time.Time, memberIDs []uuid.UUID) domain.Chat {
return domain.Chat{
ID: id,
Title: title,
MemberIDs: memberIDs,
CreatedAt: toUTCTime(createdAt),
}
}
@@ -0,0 +1,157 @@
//go:build integration
package postgres_test
import (
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
)
type ChatRepositorySuite struct {
BaseSuite
}
func TestChatRepositorySuite(t *testing.T) {
suite.Run(t, new(ChatRepositorySuite))
}
func (s *ChatRepositorySuite) TestCreateRejectsUnknownMemberAtomically() {
alice := s.createUser("alice")
_, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
Title: "С неизвестным участником",
MemberIDs: []uuid.UUID{alice.ID, uuid.New()},
CallerID: alice.ID,
})
s.Require().ErrorIs(err, domain.ErrUnknownMember)
var chats int
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM chats").Scan(&chats))
s.Zero(chats, "неуспешное создание чата не оставляет строк")
var members int
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM chat_members").Scan(&members))
s.Zero(members)
}
func (s *ChatRepositorySuite) TestCreateRejectsDuplicateMembers() {
alice := s.createUser("alice")
_, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
Title: "Дубликаты",
MemberIDs: []uuid.UUID{alice.ID, alice.ID},
CallerID: alice.ID,
})
s.Require().ErrorIs(err, domain.ErrConflict)
}
func (s *ChatRepositorySuite) TestCreateStoresAllMembers() {
alice := s.createUser("alice")
bob := s.createUser("bob")
eve := s.createUser("eve")
chat := s.createChat(alice, bob, eve)
s.Equal(uuid.Version(7), chat.ID.Version())
s.False(chat.CreatedAt.IsZero())
visible, err := s.store.Chats().GetVisible(s.T().Context(), chat.ID, bob.ID)
s.Require().NoError(err)
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID, eve.ID}, visible.MemberIDs)
}
func (s *ChatRepositorySuite) TestVisibility() {
alice := s.createUser("alice")
bob := s.createUser("bob")
eve := s.createUser("eve")
chat := s.createChat(alice, bob)
visible, err := s.store.Chats().GetVisible(s.T().Context(), chat.ID, bob.ID)
s.Require().NoError(err)
s.Equal(chat.ID, visible.ID)
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID}, visible.MemberIDs)
_, err = s.store.Chats().GetVisible(s.T().Context(), chat.ID, eve.ID)
s.Require().ErrorIs(err, domain.ErrNotFound)
page, err := s.store.Chats().ListVisible(s.T().Context(), eve.ID, nil, 50)
s.Require().NoError(err)
s.Empty(page.Items)
page, err = s.store.Chats().ListVisible(s.T().Context(), alice.ID, nil, 50)
s.Require().NoError(err)
s.Require().Len(page.Items, 1)
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID}, page.Items[0].MemberIDs)
s.Nil(page.Next)
}
func (s *ChatRepositorySuite) TestListPagination() {
alice := s.createUser("alice")
const total = 5
for range total {
s.createChat(alice)
}
seen := make(map[uuid.UUID]struct{}, total)
var cursor *domain.Cursor
for {
page, err := s.store.Chats().ListVisible(s.T().Context(), alice.ID, cursor, 2)
s.Require().NoError(err)
s.Require().NotEmpty(page.Items)
for _, chat := range page.Items {
_, duplicate := seen[chat.ID]
s.Require().False(duplicate)
seen[chat.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, total)
}
func (s *ChatRepositorySuite) TestListPaginationWithSharedTimestamp() {
alice := s.createUser("alice")
for range 5 {
s.createChat(alice)
}
_, err := s.pool.Exec(s.T().Context(), "UPDATE chats SET created_at = '2026-01-01 00:00:00+00'")
s.Require().NoError(err)
seen := make(map[uuid.UUID]struct{}, 5)
var cursor *domain.Cursor
for {
page, err := s.store.Chats().ListVisible(s.T().Context(), alice.ID, cursor, 2)
s.Require().NoError(err)
for _, chat := range page.Items {
_, duplicate := seen[chat.ID]
s.Require().False(duplicate)
seen[chat.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, 5)
}
+74
View File
@@ -0,0 +1,74 @@
package postgres
import (
"errors"
"time"
"mtusi-messenger/internal/config"
)
const (
defaultHost = "localhost"
defaultPort = 5432
defaultDatabase = "messenger"
defaultUser = "messenger"
defaultSSLMode = "disable"
defaultMaxConns = int32(10)
defaultMinConns = int32(1)
defaultMaxConnLifetime = time.Hour
defaultMaxConnIdleTime = 30 * time.Minute
defaultConnectTimeout = 5 * time.Second
defaultQueryTimeout = 5 * time.Second
)
func normalize(cfg config.Postgres) (config.Postgres, error) {
if cfg.Host == "" {
cfg.Host = defaultHost
}
if cfg.Port == 0 {
cfg.Port = defaultPort
}
if cfg.Database == "" {
cfg.Database = defaultDatabase
}
if cfg.User == "" {
cfg.User = defaultUser
}
if cfg.SSLMode == "" {
cfg.SSLMode = defaultSSLMode
}
if cfg.MaxConns == 0 {
cfg.MaxConns = defaultMaxConns
}
if cfg.MinConns == 0 {
cfg.MinConns = defaultMinConns
}
if cfg.MaxConnLifetime == 0 {
cfg.MaxConnLifetime = defaultMaxConnLifetime
}
if cfg.MaxConnIdleTime == 0 {
cfg.MaxConnIdleTime = defaultMaxConnIdleTime
}
if cfg.ConnectTimeout == 0 {
cfg.ConnectTimeout = defaultConnectTimeout
}
if cfg.QueryTimeout == 0 {
cfg.QueryTimeout = defaultQueryTimeout
}
if cfg.MinConns > cfg.MaxConns {
return cfg, errors.New("postgres: min_conns must not exceed max_conns")
}
return cfg, nil
}
+49
View File
@@ -0,0 +1,49 @@
package postgres
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/config"
)
func TestNormalizeAppliesDefaults(t *testing.T) {
cfg, err := normalize(config.Postgres{})
require.NoError(t, err)
require.Equal(t, "localhost", cfg.Host)
require.Equal(t, 5432, cfg.Port)
require.Equal(t, "messenger", cfg.Database)
require.Equal(t, "messenger", cfg.User)
require.Equal(t, "disable", cfg.SSLMode)
require.Equal(t, int32(10), cfg.MaxConns)
require.Equal(t, int32(1), cfg.MinConns)
require.Equal(t, time.Hour, cfg.MaxConnLifetime)
require.Equal(t, 5*time.Second, cfg.ConnectTimeout)
}
func TestNormalizeKeepsProvidedValues(t *testing.T) {
cfg, err := normalize(config.Postgres{
Host: "db",
Port: 6543,
Database: "app",
User: "app",
SSLMode: "require",
MaxConns: 7,
MinConns: 2,
})
require.NoError(t, err)
require.Equal(t, "db", cfg.Host)
require.Equal(t, 6543, cfg.Port)
require.Equal(t, "app", cfg.Database)
require.Equal(t, "require", cfg.SSLMode)
require.Equal(t, int32(7), cfg.MaxConns)
}
func TestNormalizeRejectsMinGreaterThanMax(t *testing.T) {
_, err := normalize(config.Postgres{MinConns: 5, MaxConns: 2})
require.Error(t, err)
}
+42
View File
@@ -0,0 +1,42 @@
package postgres
import (
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"mtusi-messenger/internal/domain"
)
const (
pgUniqueViolation = "23505"
pgCheckViolation = "23514"
)
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation
}
func mapError(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return domain.ErrNotFound
}
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
switch pgErr.Code {
case pgUniqueViolation:
return domain.ErrConflict
case pgCheckViolation:
return domain.ErrValidation
}
}
return err
}
@@ -0,0 +1,225 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: chats.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const addChatMembers = `-- name: AddChatMembers :exec
INSERT INTO chat_members (chat_id, user_id)
SELECT $1, members.member_id
FROM unnest($2::uuid[]) AS members(member_id)
`
type AddChatMembersParams struct {
ChatID uuid.UUID
UserIds []uuid.UUID
}
func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams) error {
_, err := q.db.Exec(ctx, addChatMembers, arg.ChatID, arg.UserIds)
return err
}
const createChat = `-- name: CreateChat :one
INSERT INTO chats (title)
VALUES ($1)
RETURNING id, title, created_at
`
func (q *Queries) CreateChat(ctx context.Context, title string) (Chat, error) {
row := q.db.QueryRow(ctx, createChat, title)
var i Chat
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
return i, err
}
const getChatForMember = `-- name: GetChatForMember :one
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible
ON visible.chat_id = c.id AND visible.user_id = $1
WHERE c.id = $2
`
type GetChatForMemberParams struct {
UserID uuid.UUID
ID uuid.UUID
}
type GetChatForMemberRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) GetChatForMember(ctx context.Context, arg GetChatForMemberParams) (GetChatForMemberRow, error) {
row := q.db.QueryRow(ctx, getChatForMember, arg.UserID, arg.ID)
var i GetChatForMemberRow
err := row.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
)
return i, err
}
const listChatsForMember = `-- name: ListChatsForMember :many
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id
WHERE visible.user_id = $1
ORDER BY c.created_at, c.id
LIMIT $2
`
type ListChatsForMemberParams struct {
UserID uuid.UUID
RowLimit int32
}
type ListChatsForMemberRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChatsForMember(ctx context.Context, arg ListChatsForMemberParams) ([]ListChatsForMemberRow, error) {
rows, err := q.db.Query(ctx, listChatsForMember, arg.UserID, arg.RowLimit)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsForMemberRow{}
for rows.Next() {
var i ListChatsForMemberRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listChatsForMemberAfter = `-- name: ListChatsForMemberAfter :many
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id
WHERE visible.user_id = $1
AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
ORDER BY c.created_at, c.id
LIMIT $4
`
type ListChatsForMemberAfterParams struct {
UserID uuid.UUID
AfterCreatedAt time.Time
AfterID uuid.UUID
RowLimit int32
}
type ListChatsForMemberAfterRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChatsForMemberAfter(ctx context.Context, arg ListChatsForMemberAfterParams) ([]ListChatsForMemberAfterRow, error) {
rows, err := q.db.Query(ctx, listChatsForMemberAfter,
arg.UserID,
arg.AfterCreatedAt,
arg.AfterID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsForMemberAfterRow{}
for rows.Next() {
var i ListChatsForMemberAfterRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMissingUserIDs = `-- name: ListMissingUserIDs :many
SELECT input.id::uuid AS missing_id
FROM unnest($1::uuid[]) AS input(id)
LEFT JOIN users u ON u.id = input.id
WHERE u.id IS NULL
`
func (q *Queries) ListMissingUserIDs(ctx context.Context, userIds []uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, listMissingUserIDs, userIds)
if err != nil {
return nil, err
}
defer rows.Close()
items := []uuid.UUID{}
for rows.Next() {
var missing_id uuid.UUID
if err := rows.Scan(&missing_id); err != nil {
return nil, err
}
items = append(items, missing_id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package sqlcgen
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
@@ -0,0 +1,160 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: messages.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const createMessage = `-- name: CreateMessage :one
INSERT INTO messages (chat_id, sender_id, text)
SELECT $1, $2, $3
WHERE EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
RETURNING id, chat_id, sender_id, text, created_at
`
type CreateMessageParams struct {
ChatID uuid.UUID
SenderID uuid.UUID
Text string
}
func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {
row := q.db.QueryRow(ctx, createMessage, arg.ChatID, arg.SenderID, arg.Text)
var i Message
err := row.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
)
return i, err
}
const isChatMember = `-- name: IsChatMember :one
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
) AS is_member
`
type IsChatMemberParams struct {
ChatID uuid.UUID
UserID uuid.UUID
}
func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) {
row := q.db.QueryRow(ctx, isChatMember, arg.ChatID, arg.UserID)
var is_member bool
err := row.Scan(&is_member)
return is_member, err
}
const listMessagesForChat = `-- name: ListMessagesForChat :many
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM messages m
JOIN chat_members cm
ON cm.chat_id = m.chat_id
AND cm.user_id = $1
WHERE m.chat_id = $2
ORDER BY m.created_at, m.id
LIMIT $3
`
type ListMessagesForChatParams struct {
CallerID uuid.UUID
ChatID uuid.UUID
RowLimit int32
}
func (q *Queries) ListMessagesForChat(ctx context.Context, arg ListMessagesForChatParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessagesForChat, arg.CallerID, arg.ChatID, arg.RowLimit)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Message{}
for rows.Next() {
var i Message
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMessagesForChatAfter = `-- name: ListMessagesForChatAfter :many
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM messages m
JOIN chat_members cm
ON cm.chat_id = m.chat_id
AND cm.user_id = $1
WHERE m.chat_id = $2
AND (m.created_at, m.id) > ($3::timestamptz, $4::uuid)
ORDER BY m.created_at, m.id
LIMIT $5
`
type ListMessagesForChatAfterParams struct {
CallerID uuid.UUID
ChatID uuid.UUID
AfterCreatedAt time.Time
AfterID uuid.UUID
RowLimit int32
}
func (q *Queries) ListMessagesForChatAfter(ctx context.Context, arg ListMessagesForChatAfterParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessagesForChatAfter,
arg.CallerID,
arg.ChatID,
arg.AfterCreatedAt,
arg.AfterID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Message{}
for rows.Next() {
var i Message
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,46 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package sqlcgen
import (
"time"
"github.com/google/uuid"
)
type Chat struct {
ID uuid.UUID
Title string
CreatedAt time.Time
}
type ChatMember struct {
ChatID uuid.UUID
UserID uuid.UUID
CreatedAt time.Time
}
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
type Session struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
CreatedAt time.Time
}
type User struct {
ID uuid.UUID
Username string
PasswordHash string
DisplayName string
CreatedAt time.Time
}
@@ -0,0 +1,85 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: sessions.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const createSession = `-- name: CreateSession :one
INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES ($1, $2, $3)
RETURNING token_hash, user_id, expires_at
`
type CreateSessionParams struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
}
type CreateSessionRow struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
}
func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (CreateSessionRow, error) {
row := q.db.QueryRow(ctx, createSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
var i CreateSessionRow
err := row.Scan(&i.TokenHash, &i.UserID, &i.ExpiresAt)
return i, err
}
const deleteSession = `-- name: DeleteSession :exec
DELETE FROM sessions
WHERE token_hash = $1
AND user_id = $2
`
type DeleteSessionParams struct {
TokenHash []byte
UserID uuid.UUID
}
func (q *Queries) DeleteSession(ctx context.Context, arg DeleteSessionParams) error {
_, err := q.db.Exec(ctx, deleteSession, arg.TokenHash, arg.UserID)
return err
}
const getSessionUser = `-- name: GetSessionUser :one
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1
AND s.expires_at > now()
`
type GetSessionUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
PasswordHash string
ExpiresAt time.Time
}
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSessionUserRow, error) {
row := q.db.QueryRow(ctx, getSessionUser, tokenHash)
var i GetSessionUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.PasswordHash,
&i.ExpiresAt,
)
return i, err
}
@@ -0,0 +1,100 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: users.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const createUser = `-- name: CreateUser :one
INSERT INTO users (username, display_name, password_hash)
VALUES ($1, $2, $3)
RETURNING id, username, display_name, created_at, password_hash
`
type CreateUserParams struct {
Username string
DisplayName string
PasswordHash string
}
type CreateUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
PasswordHash string
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
row := q.db.QueryRow(ctx, createUser, arg.Username, arg.DisplayName, arg.PasswordHash)
var i CreateUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.PasswordHash,
)
return i, err
}
const getUserByID = `-- name: GetUserByID :one
SELECT id, username, display_name, created_at, password_hash
FROM users
WHERE id = $1
`
type GetUserByIDRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
PasswordHash string
}
func (q *Queries) GetUserByID(ctx context.Context, id uuid.UUID) (GetUserByIDRow, error) {
row := q.db.QueryRow(ctx, getUserByID, id)
var i GetUserByIDRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.PasswordHash,
)
return i, err
}
const getUserByUsername = `-- name: GetUserByUsername :one
SELECT id, username, display_name, created_at, password_hash
FROM users
WHERE username = $1
`
type GetUserByUsernameRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
PasswordHash string
}
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (GetUserByUsernameRow, error) {
row := q.db.QueryRow(ctx, getUserByUsername, username)
var i GetUserByUsernameRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.PasswordHash,
)
return i, err
}
+278
View File
@@ -0,0 +1,278 @@
//go:build integration
package postgres_test
import (
"context"
"database/sql"
"fmt"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/pressly/goose/v3"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
"mtusi-messenger/internal/storage/postgres"
"mtusi-messenger/internal/storage/postgres/migrations"
_ "github.com/jackc/pgx/v5/stdlib"
)
const templateDB = "messenger_template"
var adminPool *pgxpool.Pool
func envOr(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func envInt(key string, fallback int) int {
value := os.Getenv(key)
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
func testConfig() config.Postgres {
return config.Postgres{
Host: envOr("TEST_POSTGRES_HOST", "localhost"),
Port: envInt("TEST_POSTGRES_PORT", 5432),
Database: envOr("TEST_POSTGRES_DATABASE", "messenger"),
User: envOr("TEST_POSTGRES_USER", "messenger"),
Password: envOr("TEST_POSTGRES_PASSWORD", "messenger"),
SSLMode: envOr("TEST_POSTGRES_SSL_MODE", "disable"),
MaxConns: 5,
MinConns: 1,
MaxConnLifetime: time.Hour,
MaxConnIdleTime: 30 * time.Minute,
ConnectTimeout: 5 * time.Second,
QueryTimeout: 5 * time.Second,
}
}
func dsnFor(database string) string {
cfg := testConfig()
cfg.Database = database
return cfg.DSN()
}
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
adminPool, err = pgxpool.New(ctx, dsnFor(testConfig().Database))
if err != nil {
fmt.Fprintln(os.Stderr, "admin pool:", err)
os.Exit(1)
}
if err := waitForDatabase(ctx, adminPool); err != nil {
fmt.Fprintln(os.Stderr, "database is not ready:", err)
os.Exit(1)
}
if err := recreateTemplate(ctx); err != nil {
fmt.Fprintln(os.Stderr, "create template:", err)
os.Exit(1)
}
code := m.Run()
adminPool.Close()
os.Exit(code)
}
func waitForDatabase(ctx context.Context, pool *pgxpool.Pool) error {
var lastErr error
for range 60 {
err := pool.Ping(ctx)
if err == nil {
return nil
}
lastErr = err
time.Sleep(500 * time.Millisecond)
}
return lastErr
}
func adminExec(ctx context.Context, query string) error {
conn, err := adminPool.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
_, err = conn.Conn().PgConn().Exec(ctx, query).ReadAll()
return err
}
const templateLockKey int64 = 0x6d657373656e6765
func withAdvisoryLock(ctx context.Context, shared bool, fn func() error) error {
conn, err := adminPool.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
lock, unlock := "pg_advisory_lock", "pg_advisory_unlock"
if shared {
lock, unlock = "pg_advisory_lock_shared", "pg_advisory_unlock_shared"
}
if _, err := conn.Exec(ctx, "SELECT "+lock+"($1)", templateLockKey); err != nil {
return err
}
defer func() { _, _ = conn.Exec(context.WithoutCancel(ctx), "SELECT "+unlock+"($1)", templateLockKey) }()
return fn()
}
func recreateTemplate(ctx context.Context) error {
return withAdvisoryLock(ctx, false, func() error {
if err := adminExec(ctx, "DROP DATABASE IF EXISTS "+templateDB+" WITH (FORCE)"); err != nil {
return err
}
if err := adminExec(ctx, "CREATE DATABASE "+templateDB); err != nil {
return err
}
db, err := sql.Open("pgx", dsnFor(templateDB))
if err != nil {
return err
}
defer func() { _ = db.Close() }()
if err := db.PingContext(ctx); err != nil {
return err
}
goose.SetBaseFS(migrations.FS)
if err := goose.SetDialect("postgres"); err != nil {
return err
}
return goose.Up(db, ".")
})
}
type BaseSuite struct {
suite.Suite
store *postgres.Store
pool *pgxpool.Pool
db string
}
func (s *BaseSuite) SetupTest() {
ctx := s.T().Context()
s.db = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
s.Require().NoError(withAdvisoryLock(ctx, true, func() error {
return adminExec(ctx, "CREATE DATABASE "+s.db+" TEMPLATE "+templateDB)
}))
var err error
s.pool, err = pgxpool.New(ctx, dsnFor(s.db))
s.Require().NoError(err)
s.store = openStore(s.T(), s.db, nil)
}
func (s *BaseSuite) TearDownTest() {
if s.store != nil {
s.store.Close()
}
if s.pool != nil {
s.pool.Close()
}
if s.db != "" {
s.Require().NoError(adminExec(s.T().Context(), "DROP DATABASE "+s.db+" WITH (FORCE)"))
}
}
func openStore(t *testing.T, database string, override func(*config.Postgres)) *postgres.Store {
t.Helper()
cfg := testConfig()
cfg.Database = database
if override != nil {
override(&cfg)
}
store, err := postgres.New(t.Context(), cfg)
require.NoError(t, err)
return store
}
func (s *BaseSuite) createUser(username string) domain.User {
s.T().Helper()
hash, err := password.Hash("strong-test-password")
s.Require().NoError(err)
user, err := s.store.Users().Create(s.T().Context(), domain.NewUser{
Username: username,
DisplayName: "Пользователь " + username,
PasswordHash: hash,
})
s.Require().NoError(err)
return user
}
func (s *BaseSuite) createChat(owner domain.User, members ...domain.User) domain.Chat {
s.T().Helper()
ids := []uuid.UUID{owner.ID}
for _, member := range members {
ids = append(ids, member.ID)
}
chat, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
Title: "Чат",
MemberIDs: ids,
CallerID: owner.ID,
})
s.Require().NoError(err)
return chat
}
+21
View File
@@ -0,0 +1,21 @@
package postgres
import "time"
func toUTCTime(t time.Time) time.Time {
if t.Location() == time.UTC {
return t
}
return t.UTC()
}
func mapAll[S, D any](rows []S, mapRow func(S) D) []D {
mapped := make([]D, 0, len(rows))
for _, row := range rows {
mapped = append(mapped, mapRow(row))
}
return mapped
}
@@ -0,0 +1,118 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type MessageRepository struct {
store *Store
}
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.CreateMessage(ctx, sqlcgen.CreateMessageParams{
ChatID: draft.ChatID,
SenderID: draft.SenderID,
Text: draft.Text,
})
if err != nil {
return domain.Message{}, fmt.Errorf("create message: %w", mapError(err))
}
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), nil
}
func (r *MessageRepository) ListVisible(
ctx context.Context,
chatID, callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Message], error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
limit = clampLimit(limit)
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
messages, err := r.fetch(ctx, chatID, callerID, after, fetch)
if err != nil {
return domain.Page[domain.Message]{}, err
}
if len(messages) == 0 {
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
ChatID: chatID,
UserID: callerID,
})
if err != nil {
return domain.Page[domain.Message]{}, fmt.Errorf("check chat membership: %w", mapError(err))
}
if !member {
return domain.Page[domain.Message]{}, fmt.Errorf(
"%w: chat %s for user %s",
domain.ErrNotFound, chatID, callerID,
)
}
}
return buildPage(messages, limit, func(message domain.Message) domain.Cursor {
return domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID}
}), nil
}
func (r *MessageRepository) fetch(
ctx context.Context,
chatID, callerID uuid.UUID,
after *domain.Cursor,
fetch int32,
) ([]domain.Message, error) {
if after == nil {
rows, err := r.store.queries.ListMessagesForChat(ctx, sqlcgen.ListMessagesForChatParams{
ChatID: chatID,
CallerID: callerID,
RowLimit: fetch,
})
if err != nil {
return nil, fmt.Errorf("list messages: %w", mapError(err))
}
return mapAll(rows, mapMessageRow), nil
}
rows, err := r.store.queries.ListMessagesForChatAfter(ctx, sqlcgen.ListMessagesForChatAfterParams{
ChatID: chatID,
CallerID: callerID,
AfterCreatedAt: after.CreatedAt,
AfterID: after.ID,
RowLimit: fetch,
})
if err != nil {
return nil, fmt.Errorf("list messages: %w", mapError(err))
}
return mapAll(rows, mapMessageRow), nil
}
func mapMessageRow(row sqlcgen.Message) domain.Message {
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
}
func mapMessage(id, chatID, senderID uuid.UUID, text string, createdAt time.Time) domain.Message {
return domain.Message{
ID: id,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: toUTCTime(createdAt),
}
}
@@ -0,0 +1,157 @@
//go:build integration
package postgres_test
import (
"fmt"
"sync"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
)
type MessageRepositorySuite struct {
BaseSuite
}
func TestMessageRepositorySuite(t *testing.T) {
suite.Run(t, new(MessageRepositorySuite))
}
func (s *MessageRepositorySuite) TestCreateAndPagination() {
alice := s.createUser("alice")
bob := s.createUser("bob")
chat := s.createChat(alice, bob)
const total = 5
for i := range total {
message, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: alice.ID,
Text: fmt.Sprintf("сообщение %d", i),
})
s.Require().NoError(err)
s.Equal(uuid.Version(7), message.ID.Version())
s.False(message.CreatedAt.IsZero())
}
seen := make(map[uuid.UUID]struct{}, total)
var cursor *domain.Cursor
for {
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, cursor, 2)
s.Require().NoError(err)
s.Require().NotEmpty(page.Items)
for _, message := range page.Items {
_, duplicate := seen[message.ID]
s.Require().False(duplicate, "keyset-пагинация не повторяет сообщения")
seen[message.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, total)
}
func (s *MessageRepositorySuite) TestPaginationWithSharedTimestamp() {
alice := s.createUser("alice")
chat := s.createChat(alice)
for range 5 {
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID, SenderID: alice.ID, Text: "same timestamp",
})
s.Require().NoError(err)
}
_, err := s.pool.Exec(s.T().Context(), "UPDATE messages SET created_at = '2026-01-01 00:00:00+00'")
s.Require().NoError(err)
seen := make(map[uuid.UUID]struct{}, 5)
var cursor *domain.Cursor
for {
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, cursor, 2)
s.Require().NoError(err)
for _, message := range page.Items {
_, duplicate := seen[message.ID]
s.Require().False(duplicate)
seen[message.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, 5)
}
func (s *MessageRepositorySuite) TestAccessIsRestricted() {
alice := s.createUser("alice")
bob := s.createUser("bob")
chat := s.createChat(alice)
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: bob.ID,
Text: "чужое",
})
s.Require().ErrorIs(err, domain.ErrNotFound, "не участник не может писать в чат")
_, err = s.store.Messages().ListVisible(s.T().Context(), chat.ID, bob.ID, nil, 50)
s.Require().ErrorIs(err, domain.ErrNotFound, "не участник не может читать историю")
}
func (s *MessageRepositorySuite) TestListingForMissingChatReturnsNotFound() {
alice := s.createUser("alice")
_, err := s.store.Messages().ListVisible(s.T().Context(), uuid.New(), alice.ID, nil, 50)
s.Require().ErrorIs(err, domain.ErrNotFound)
}
func (s *MessageRepositorySuite) TestFinishedMessageSurvivesConcurrentReads() {
alice := s.createUser("alice")
chat := s.createChat(alice)
const total = 20
var wg sync.WaitGroup
wg.Go(func() {
for i := range total {
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: alice.ID,
Text: fmt.Sprintf("message %d", i),
})
if err != nil {
return
}
}
})
for range total {
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, nil, 100)
s.Require().NoError(err)
s.LessOrEqual(len(page.Items), total)
}
wg.Wait()
}
@@ -0,0 +1,63 @@
-- +goose Up
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT uuidv7(),
username text NOT NULL,
password_hash text NOT NULL,
display_name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_not_blank CHECK (btrim(display_name) <> ''),
CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE chats (
id uuid PRIMARY KEY DEFAULT uuidv7(),
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT chats_title_not_blank CHECK (btrim(title) <> '')
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE messages (
id uuid PRIMARY KEY DEFAULT uuidv7(),
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> ''),
CONSTRAINT messages_text_length CHECK (char_length(text) <= 4000)
);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX messages_chat_id_created_at_id_idx
ON messages (chat_id, created_at, id);
CREATE INDEX chat_members_user_id_chat_id_idx
ON chat_members (user_id, chat_id);
CREATE INDEX chats_created_at_id_idx
ON chats (created_at, id);
-- +goose Down
DROP TABLE sessions;
DROP TABLE messages;
DROP TABLE chat_members;
DROP TABLE chats;
DROP TABLE users;
@@ -0,0 +1,6 @@
package migrations
import "embed"
//go:embed *.sql
var FS embed.FS
+25
View File
@@ -0,0 +1,25 @@
package postgres
import "mtusi-messenger/internal/domain"
const (
minPageSize = 1
maxPageSize = 100
)
func clampLimit(limit int) int {
return min(max(limit, minPageSize), maxPageSize)
}
func buildPage[T any](items []T, limit int, cursor func(item T) domain.Cursor) domain.Page[T] {
if len(items) > limit {
next := cursor(items[limit-1])
return domain.Page[T]{
Items: append([]T(nil), items[:limit]...),
Next: &next,
}
}
return domain.Page[T]{Items: append([]T(nil), items...)}
}
@@ -0,0 +1,63 @@
-- name: CreateChat :one
INSERT INTO chats (title)
VALUES (sqlc.arg(title))
RETURNING id, title, created_at;
-- name: AddChatMembers :exec
INSERT INTO chat_members (chat_id, user_id)
SELECT sqlc.arg(chat_id), members.member_id
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS members(member_id);
-- name: ListMissingUserIDs :many
SELECT input.id::uuid AS missing_id
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS input(id)
LEFT JOIN users u ON u.id = input.id
WHERE u.id IS NULL;
-- name: GetChatForMember :one
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible
ON visible.chat_id = c.id AND visible.user_id = sqlc.arg(user_id)
WHERE c.id = sqlc.arg(id);
-- name: ListChatsForMember :many
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id
WHERE visible.user_id = sqlc.arg(user_id)
ORDER BY c.created_at, c.id
LIMIT sqlc.arg(row_limit);
-- name: ListChatsForMemberAfter :many
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id
WHERE visible.user_id = sqlc.arg(user_id)
AND (c.created_at, c.id) > (sqlc.arg(after_created_at)::timestamptz, sqlc.arg(after_id)::uuid)
ORDER BY c.created_at, c.id
LIMIT sqlc.arg(row_limit);
@@ -0,0 +1,39 @@
-- name: CreateMessage :one
INSERT INTO messages (chat_id, sender_id, text)
SELECT sqlc.arg(chat_id), sqlc.arg(sender_id), sqlc.arg(text)
WHERE EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = sqlc.arg(chat_id)
AND user_id = sqlc.arg(sender_id)
)
RETURNING id, chat_id, sender_id, text, created_at;
-- name: IsChatMember :one
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = sqlc.arg(chat_id)
AND user_id = sqlc.arg(user_id)
) AS is_member;
-- name: ListMessagesForChat :many
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM messages m
JOIN chat_members cm
ON cm.chat_id = m.chat_id
AND cm.user_id = sqlc.arg(caller_id)
WHERE m.chat_id = sqlc.arg(chat_id)
ORDER BY m.created_at, m.id
LIMIT sqlc.arg(row_limit);
-- name: ListMessagesForChatAfter :many
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM messages m
JOIN chat_members cm
ON cm.chat_id = m.chat_id
AND cm.user_id = sqlc.arg(caller_id)
WHERE m.chat_id = sqlc.arg(chat_id)
AND (m.created_at, m.id) > (sqlc.arg(after_created_at)::timestamptz, sqlc.arg(after_id)::uuid)
ORDER BY m.created_at, m.id
LIMIT sqlc.arg(row_limit);
@@ -0,0 +1,16 @@
-- name: CreateSession :one
INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES (sqlc.arg(token_hash), sqlc.arg(user_id), sqlc.arg(expires_at))
RETURNING token_hash, user_id, expires_at;
-- name: GetSessionUser :one
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = sqlc.arg(token_hash)
AND s.expires_at > now();
-- name: DeleteSession :exec
DELETE FROM sessions
WHERE token_hash = sqlc.arg(token_hash)
AND user_id = sqlc.arg(user_id);

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