Author SHA1 Message Date
d1frend a7d6487e2d на 5 2026-10-25 21:46:21 +03:00
d1frend 5300a1a1e0 оценка 4 2026-10-23 16:20:43 +03:00
d1frend 34618bd423 фронт и secure browser session 2026-10-23 14:48:57 +03:00
d1frend bd28f1ae26 на оценку 3 2026-10-21 13:51:35 +03:00
d1frend 3f69970b05 refactor: разделил приложение на domain application adapters и HTTP DTO 2026-10-20 21:44:59 +03:00
d1frend 13ee5a0e56 перенос лабы 2 2026-10-18 15:05:51 +03:00
143 changed files with 20282 additions and 25 deletions
+3
View File
@@ -16,5 +16,8 @@ backups
.venv
__pycache__
node_modules
**/node_modules
frontend/dist
frontend/.vite
evidence
.DS_Store
+44 -5
View File
@@ -1,13 +1,52 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md.
# Compose publishes only the load balancer; API replicas stay on its network.
APP_HOST=0.0.0.0
APP_PORT=8080
APP_ENV=lab
# INSTANCE_ID is intentionally unset: each container uses its own hostname.
# INSTANCE_ID=api-replica-01
POSTGRES_USER=messenger
POSTGRES_DB=messenger
POSTGRES_CPU_LIMIT=1.00
POSTGRES_MEMORY_LIMIT=512M
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
# Keep false only for local HTTP. Set true when the public entrypoint uses HTTPS.
SESSION_COOKIE_SECURE=false
CURSOR_SIGNING_KEY_FILE=/run/secrets/cursor_signing_key
API_REPLICAS=2
API_CPU_LIMIT=0.50
API_MEMORY_LIMIT=256M
IDEMPOTENCY_TTL_SECONDS=86400
# File paths contain no secret values. Create the referenced local secret files
# according to REPORT.md; never commit their contents.
DATABASE_URL_FILE=/run/secrets/database_url
DB_MAX_CONNS=10
DB_MIN_CONNS=2
DB_MAX_CONN_LIFETIME=30m
DB_MAX_CONN_IDLE_TIME=5m
DB_HEALTH_CHECK_PERIOD=30s
DB_CONNECT_TIMEOUT=5s
DB_QUERY_TIMEOUT=3s
READINESS_TIMEOUT=2s
SHUTDOWN_DRAIN_DELAY=2s
SHUTDOWN_TIMEOUT=10s
# Redis stores a disposable shared chat cache; PostgreSQL remains authoritative.
# The Go config accepts CACHE_URL or CACHE_URL_FILE, but never both. The
# transferred Compose baseline currently passes CACHE_URL directly.
CACHE_URL=redis://redis:6379/0
# CACHE_URL_FILE=/run/secrets/cache_url
CACHE_TTL=5m
CACHE_OPERATION_TIMEOUT=250ms
CACHE_POOL_SIZE=10
# Optional Redis Insight profile from the transferred baseline.
REDIS_INSIGHT_PORT=5540
+33
View File
@@ -0,0 +1,33 @@
FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS builder
WORKDIR /build
COPY go.mod go.sum ./
RUN go mod download
COPY cmd/ ./cmd/
COPY internal/ ./internal/
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go
FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
RUN addgroup -g 1000 appgroup && \
adduser -u 1000 -G appgroup -s /bin/sh -D appuser
WORKDIR /app
COPY --from=builder /build/server /app/server
RUN chown -R appuser:appgroup /app
USER appuser:appgroup
EXPOSE 8080
HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=10 \
CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1
ENTRYPOINT ["/app/server"]
+128 -3
View File
@@ -1,13 +1,104 @@
GO ?= go
PYTHON ?= python3
COMPOSE ?= docker compose
ENV_FILE ?= .env
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
GRADE4_OUTPUT ?= evidence/grade4/results.json
GRADE5_OUTPUT ?= evidence/grade5/results.json
READINESS_OUTPUT ?= evidence/readiness-routing.json
.PHONY: help check validate test load test-persistence test-failover
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
COMPOSE_CMD = $(COMPOSE) --env-file "$(ENV_FILE)"
.PHONY: \
help \
init-env \
fmt \
fmt-check \
build \
go-test \
go-race \
go-vet \
go-check \
check \
validate \
test \
load \
test-persistence \
test-failover \
test-readiness-routing \
rolling-update \
grade4-experiment \
grade5-experiment \
compose-config \
compose-build \
compose-up \
compose-down \
compose-ps \
compose-logs
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "init-env: create local .env from .env.example if missing"
@echo "fmt: format Go source files"
@echo "fmt-check: report unformatted Go source files"
@echo "build: compile the API"
@echo "go-test: run Go tests"
@echo "go-race: run Go tests with race detector"
@echo "go-vet: run static Go analysis"
@echo "go-check: run formatting, tests, race detector and vet"
@echo "check: run offline skeleton checks"
@echo "validate: validate the OpenAPI contract"
@echo "test: run public smoke test against the LB entrypoint"
@echo "load: run synthetic writes against the LB entrypoint"
@echo "test-persistence: run persistence test with ACTION_SCRIPT"
@echo "test-failover: run replica failover test with ACTION_SCRIPT"
@echo "test-readiness-routing: isolate PostgreSQL from one API and verify active LB health checks"
@echo "rolling-update: replace API replicas one by one with surge capacity"
@echo "grade4-experiment: run failovers, idempotency and rolling update with evidence"
@echo "grade5-experiment: measure fixed-budget scaling, saturation and one improvement"
@echo "compose-config: validate resolved Compose configuration"
@echo "compose-build: build application images"
@echo "compose-up: start the stack"
@echo "compose-down: stop the stack without deleting volumes"
@echo "compose-ps: show stack containers"
@echo "compose-logs: follow stack logs"
init-env:
@if [ -f "$(ENV_FILE)" ]; then \
echo "$(ENV_FILE) already exists; leaving it unchanged"; \
else \
cp .env.example "$(ENV_FILE)"; \
echo "Created $(ENV_FILE) from .env.example"; \
fi
fmt:
$(GO) fmt ./...
fmt-check:
@files="$$(find cmd internal student_tests -type f -name '*.go' -print)"; \
unformatted="$$(gofmt -l $$files)"; \
if [ -n "$$unformatted" ]; then \
echo "Unformatted Go files:"; \
echo "$$unformatted"; \
exit 1; \
fi
build:
$(GO) build ./cmd/server
go-test:
$(GO) test ./...
go-race:
$(GO) test -race ./...
go-vet:
$(GO) vet ./...
go-check: fmt-check go-test go-race go-vet
check:
$(PYTHON) scripts/check_contract.py
@@ -28,3 +119,37 @@ test-persistence:
test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-readiness-routing:
$(PYTHON) scripts/test_readiness_routing.py --env-file "$(ENV_FILE)" --output "$(READINESS_OUTPUT)"
rolling-update:
ENV_FILE="$(ENV_FILE)" ./scripts/rolling-update.sh
grade4-experiment:
$(PYTHON) scripts/grade4_experiment.py --base-url "$(BASE_URL)" --env-file "$(ENV_FILE)" --output "$(GRADE4_OUTPUT)"
$(PYTHON) scripts/render_grade4.py "$(GRADE4_OUTPUT)"
grade5-experiment:
$(PYTHON) scripts/grade5_experiment.py --base-url "$(BASE_URL)" --env-file "$(ENV_FILE)" --output "$(GRADE5_OUTPUT)"
$(PYTHON) scripts/render_grade5.py "$(GRADE5_OUTPUT)"
compose-config:
@test -f "$(ENV_FILE)" || \
(echo "$(ENV_FILE) is missing; run: make init-env"; exit 2)
$(COMPOSE_CMD) config --quiet
compose-build:
$(COMPOSE_CMD) build
compose-up:
$(COMPOSE_CMD) up -d --build
compose-down:
$(COMPOSE_CMD) down
compose-ps:
$(COMPOSE_CMD) ps
compose-logs:
$(COMPOSE_CMD) logs --follow
+346 -17
View File
@@ -1,37 +1,366 @@
# Отчёт — лабораторная 3
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор, группа: Чурилин, БВТ2301
- Текущий завершённый уровень: оценка «5», трек 1 «Цена масштабирования»
- Итоговая цель: выполнена; уровень «4» и законченный исследовательский трек
- Commit/PR: заполняется автором после локального коммита и публикации
- Использованные источники и библиотеки: преподавательские README/OpenAPI/tests,
документация Go, pgx, PostgreSQL, Docker Compose, HAProxy, Nginx, React, TypeScript,
Vite, TanStack Query, React Router, Lucide и Vitest. Для разбора архитектуры,
рефакторинга, реализации и проверок использовался OpenAI Codex; решения
проверены тестами и описанными ниже воспроизводимыми сценариями.
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Локальные секреты не входят в Git. Перед первым запуском оператор создаёт каталог
`secrets/`, генерирует пароль PostgreSQL и общий для всех API-реплик ключ подписи
курсоров длиной не менее 32 байт. Значение `database_url` должно использовать имя
Compose-сервиса `postgres`, а не `localhost`. Пример генерации синтетических
локальных значений без их вывода в терминал:
```bash
mkdir -p secrets
openssl rand -hex 32 > secrets/postgres_password.txt
openssl rand -base64 48 > secrets/cursor_signing_key.txt
printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable' \
"$(cat secrets/postgres_password.txt)" > secrets/database_url.txt
chmod 600 secrets/*.txt
cp .env.example .env
```
Единственная публичная точка входа — `http://localhost:8080`; контейнеры API не
публикуют порты на host. Последовательность запуска и проверки:
```bash
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait
make test
make test-readiness-routing
make test-failover ACTION_SCRIPT=./scripts/stop-one.sh
docker compose --env-file .env up -d --wait api
make test-persistence ACTION_SCRIPT=./scripts/restart.sh
make grade4-experiment
make grade5-experiment
```
По этому же адресу HAProxy направляет обычные browser-запросы во внутренний
Nginx, который отдаёт production-сборку React. Переход на
`http://localhost:8080` открывает Messenger, а `/api/v1/*` и health endpoints
остаются доступны автоматическим проверкам. Отдельный Node.js на машине для
обычного запуска не нужен: multi-stage image сам выполняет `npm ci`, Vitest,
TypeScript build и копирует статические файлы в Nginx. Для production с HTTPS
нужно установить `SESSION_COOKIE_SECURE=true`; локально по HTTP значение остаётся
`false`.
`stop-one.sh` оставляет выбранную тестом реплику остановленной. Команда `up` в
примере явно возвращает желаемые две реплики перед следующей проверкой.
Обычная остановка не удаляет named volumes:
```bash
docker compose --env-file .env down
```
Для демонстрации балансировки одним и тем же клиентом можно многократно вызвать
любой API endpoint через `localhost:8080` и сравнить `X-Instance-Id`. В проверке
20 последовательных health-запросов наблюдались оба процесса: 10 ответов от
одной реплики и 10 от другой. Запрос `/health/ready` непосредственно из Windows
PowerShell вернул HTTP 200 и `X-Instance-Id`, поэтому браузер Windows и будущий
frontend смогут использовать тот же `http://localhost:8080`.
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Перенесённая основа lab2 разделена на явные слои:
- `internal/domain` — сущности и бизнес-инварианты без HTTP/JSON-зависимостей;
- `internal/application` — сценарии, команды и узкие порты репозиториев;
- `internal/adapter/postgres`, `memory`, `redis`, `cache` — реализации внешних
зависимостей и кэширующий декоратор;
- `internal/transport/http/dto` — wire-модели HTTP-контракта и преобразование
domain → response DTO;
- `internal/transport/http/handlers` — тонкие обработчики, по одному
нетривиальному endpoint на файл;
- `cmd/server` — composition root, единственное место сборки зависимостей.
PostgreSQL остаётся источником истины для пользователей, сессий, чатов и
сообщений. Redis содержит только удаляемую производную копию неизменяемых данных
чата; его отказ не делает API неготовым и не отменяет подтверждённую запись в
PostgreSQL.
Compose запускает один сервис `api` с `API_REPLICAS=2`. Реплики не имеют host
ports и разделяют PostgreSQL, включая таблицу сессий. HAProxy — единственная
публичная точка входа; он использует `leastconn`, Docker DNS resolver и активные
HTTP-проверки `/health/ready` раз в секунду. Реплика исключается после двух
неуспешных readiness-проверок и возвращается после двух успешных. Поэтому живой,
но потерявший PostgreSQL и ставший неготовым процесс перестаёт получать трафик;
Docker healthcheck не является единственным механизмом обнаружения. Sticky
sessions не применяются. Nginx остаётся отдельным внутренним контейнером и
обслуживает только статические файлы React.
Произвольные POST балансировщик автоматически не повторяет. Исключение сделано
только для маршрута отправки сообщения: обязательный `Idempotency-Key` позволяет
HAProxy безопасно повторить запрос на другой реплике при connection failure,
empty response, timeout или 502/503/504 во время обнаружения отказа и drain.
Для этого маршрута тело запроса буферизуется отдельным backend; регистрации
пользователя и создание чата контрактом не идемпотентны, поэтому retry для них
запрещён. Клиент также сохраняет ключ для повтора после неопределённого результата.
Миграции вынесены в одноразовый сервис `migrate`, завершение которого является
предусловием запуска API. Поэтому две реплики не конкурируют за изменение схемы.
Пагинационный курсор теперь формируется в application-слое из канонических
полей границы `(created_at, id, scope_id)` и подписывается HMAC-SHA-256. Подпись
не скрывает payload, но обнаруживает подмену. В scope входит пользователь для
списка чатов и чат для истории сообщений. Все реплики обязаны использовать один
`CURSOR_SIGNING_KEY` или `CURSOR_SIGNING_KEY_FILE`; в Compose используется Docker
secret `cursor_signing_key`. Репозитории получают только уже проверенную
типизированную границу и ничего не знают о формате HTTP-курсора.
`.env.example` перечисляет реально читаемые приложением параметры PostgreSQL,
пула, readiness/shutdown, Redis-кэша, числа реплик, TTL идемпотентности и ключа
курсора. Там же задаются CPU/RAM API и задержка drain перед shutdown.
`API_REPLICAS` используется Compose, а `IDEMPOTENCY_TTL_SECONDS` читает
Go-приложение и не допускает значение меньше 86400 секунд. Секретных значений в
шаблоне нет: там указаны только пути внутри контейнера.
Каждый процесс определяет стабильный `instance_id` один раз при загрузке
конфигурации. По умолчанию используется hostname контейнера; это одновременно
даёт уникальность между Compose-репликами и позволяет инфраструктурному hook
сопоставить `X-Instance-Id` с конкретным контейнером. Опциональный `INSTANCE_ID`
проверяется по безопасному для HTTP-заголовка шаблону. Сам middleware является
внешним относительно router/recovery, поэтому заголовок присутствует также на
health, 404/405 и восстановленных 500-ответах.
POST сообщения принимает только ASCII-ключ по шаблону
`[A-Za-z0-9._:-]{1,128}`. HTTP-слой нормализует UUID чата и формирует канонический
path, application-слой хэширует SHA-256 не исходные bytes JSON, а типизированное
семантическое представление запроса. Поэтому форматирование и порядок JSON-полей
не влияют на повтор; задел под `attachment_ids` уже канонизирует отсутствующий
список как пустой.
Область уникальности в `message_idempotency` состоит из пользователя, метода,
канонического пути и ключа. В одной PostgreSQL-транзакции сначала захватывается
эта область через primary key, затем создаётся Message. Отложенный foreign key
позволяет заранее записать будущий `message_id`, но проверяется при commit. При
гонке вторая реплика ждёт разрешения уникального конфликта и затем либо возвращает
то же сообщение, либо отвечает 409 при другом request hash. Любая ошибка до
commit откатывает и бизнес-эффект, и запись ключа, поэтому transient 5xx не
фиксируется как успешный результат. Перед replay снова выполняются обычная
проверка bearer-сессии и проверка членства в чате.
### Frontend и браузерная сессия
Клиент находится в `frontend/` и собран на React + TypeScript + Vite. TanStack
Query отвечает за серверное состояние и периодическое обновление списков,
React Router — за маршруты login/register, выбранного чата и профиля. UI сделан
адаптивным: на широком экране одновременно видны навигация, список и разговор,
а на узком список и чат переключаются как отдельные мобильные экраны. Фон чата
добавлен из предоставленного изображения; нейтральная графитово-белая палитра,
мягкая системная типографика и скруглённая геометрия компонентов подобраны
самостоятельно, без копирования Telegram.
Токен не хранится в `localStorage` и недоступен JavaScript. Успешный login
по-прежнему возвращает преподавательский JSON с bearer token, но дополнительно
ставит host-only cookie `mtusi_session` с `Path=/`, `HttpOnly` и
`SameSite=Strict`. Флаг `Secure` управляется `SESSION_COOKIE_SECURE`: `false`
нужен только локальному HTTP, на HTTPS должен быть `true`.
Контрактные `/api/v1/*` сознательно остались Bearer-only. HAProxy предоставляет
отдельный браузерный адаптер `/web-api/v1/*`: берёт token из HttpOnly-cookie,
формирует `Authorization: Bearer ...`, удаляет исходный `Cookie` и проксирует на
обычный `/api/v1/*`. Поэтому преподавательские тесты и внешние API-клиенты не
получили скрытый альтернативный способ авторизации. Same-origin deployment,
`SameSite=Strict`, JSON-only изменяющие запросы и отсутствие CORS для сторонних
origin уменьшают CSRF-поверхность. Logout удаляет серверную сессию и истекает
cookie.
Список чатов показывает только данные, реально существующие в контракте: title
и число участников. Превью последнего сообщения и unread counter не имитируются,
поскольку backend их пока не отдаёт. При неопределённой ошибке отправки клиент
сохраняет текст вместе с `Idempotency-Key`; повтор использует тот же ключ.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Воспроизводимая конфигурация и качество Go | `make check && make go-check && make validate PYTHON=../mtusi2026lab2/.venv/bin/python` | форматирование, tests, race detector, vet, Compose config и OpenAPI validation завершились без ошибок | `evidence/lab3-summary.md` |
| Две API-реплики за одним LB | `docker compose --env-file .env up -d --build --wait`; 20 health-запросов через `:8080` | наружу опубликован только HAProxy; два разных `X-Instance-Id`, по 10 ответов от каждого | `compose.yaml`, `infrastructure/haproxy/haproxy.cfg`, `evidence/lab3-summary.md` |
| Публичный smoke lab3 | `make test` | `tests/smoke.py` завершился `PASS: lab3 public API scenario` | `evidence/lab3-summary.md` |
| Общая сессия без sticky routing | smoke, затем failover и persistence через тот же bearer token | обе реплики обслуживали запросы; сессия работает после остановки API и рестартов | `evidence/lab3-summary.md` |
| Идемпотентность сообщения | `go test ./student_tests -run Idempotency`; 32 конкурентных POST с одним ключом через LB | один Message и ровно одна строка в PostgreSQL; другой payload даёт 409 | `student_tests/idempotency_test.go`, `evidence/lab3-summary.md` |
| Failover каждой API-реплики | два последовательных запуска `make test-failover ACTION_SCRIPT=./scripts/stop-one.sh` с восстановлением между ними | реально остановлены `api-2`, затем `api-1`; получено 142/143 успешных записи, 0 ошибок, восстановление 0.963/0.750 с | `scripts/stop-one.sh`, `evidence/lab3-summary.md` |
| Persistence после рестартов | `make test-persistence ACTION_SCRIPT=./scripts/restart.sh` | PASS; прежняя сессия и данные доступны после рестарта PostgreSQL, Redis, API и LB | `scripts/restart.sh`, `evidence/lab3-summary.md` |
| Миграции перед API | `docker compose --env-file .env ps -a` и логи `migrate` | миграции 1 и 2 применены; one-shot контейнер завершился с кодом 0; API healthy | `migrations/000002_message_idempotency.up.sql`, `evidence/lab3-summary.md` |
| React frontend и HttpOnly BFF | `docker compose build frontend load-balancer`; browser QA; cookie-only curl-сценарий | Vitest/TypeScript/Vite build PASS; register/login 201; прямой `/api` 401; `/web-api` 200; logout 204, после logout 401; browser console без warning/error | `frontend/`, `infrastructure/nginx/`, `infrastructure/haproxy/` |
| Согласованные health и shutdown | SIGTERM каждой реплики под нагрузкой | API сразу закрывает availability gate, 2 с дренирует запросы и укладывается в 10 с shutdown; `/health/live` остаётся доступен | `internal/transport/http/middleware/availability.go`, `evidence/grade4/` |
| CPU/RAM и изоляция портов | `docker inspect`; `docker compose ps` | API: 0,5 CPU/256 MiB на реплику; наружу опубликован только HAProxy `127.0.0.1:8080`; `container_name` отсутствует | `compose.yaml`, `evidence/grade4/results.json` |
| Readiness-aware routing | `make test-readiness-routing` | одной API-реплике заблокирован PostgreSQL: HAProxy исключил её за 2,861 с; 40 health-запросов получили 200, 20 регистраций — 201; после снятия fault реплика вернулась | `scripts/test_readiness_routing.py`, `evidence/readiness-routing.json` |
| Последовательный failover уровня 4 | `make grade4-experiment` | обе исходные реплики остановлены по очереди и восстановлены; recovery 2,893/2,938 с; во всех фазах 0 ошибочных запросов | `evidence/grade4/README.md`, `throughput-errors.svg`, `timeline.svg` |
| Rolling update под нагрузкой | surge до 3 реплик, замена двух старых по одной, возврат к 2 | 22 212 успешных запросов, 0 ошибок; все новые реплики проходят healthcheck и DNS-settle | `scripts/rolling-update.sh`, `evidence/grade4/` |
| Фиксированный бюджет 1/2/4 API | `make grade5-experiment`; 32 closed-loop клиента | при суммарных 1 CPU, 512 MiB и 16 соединениях получено 578,242 / 529,499 / 353,955 RPS; четыре процесса при том же бюджете дали на 38,79% меньше одной реплики | `evidence/grade5/02-fixed-total.svg`, `measurements.csv` |
| Рост ресурсов 1/2/4 API | тот же workload; по 0,5 CPU, 256 MiB и 8 соединений на реплику | 533,656 / 563,460 / 438,868 RPS; нелинейная серия показывает отсутствие пропорционального выигрыша при общей БД в 1 CPU | `evidence/grade5/03-resource-growth.svg`, `results.json` |
| Saturation point и bottleneck | concurrency 1/2/4/8/16/32, по 10 с после warm-up | первый сигнал насыщения — 8: относительно 4 клиентов RPS вырос только на 8,03%, p95 — в 1,92 раза; PostgreSQL в профиле четырёх реплик достиг 101,91% одного CPU | `evidence/grade5/01-saturation.svg`, `04-bottleneck.svg` |
| Подтверждённое улучшение | четыре API без изменений; PostgreSQL 1 → 2 CPU | RPS 438,868 → 587,574 (+33,88%), ошибок 0, p95 снизился на 14,12%; следующим ограничением стал HAProxy с лимитом 0,25 CPU | `evidence/grade5/05-improvement.svg`, `resources.csv` |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Итоговый эксперимент уровня 4 выполнен 23.10.2026 на Windows + WSL2:
Docker Engine 29.7.2, Compose 5.5.0, 8 логических CPU и 3813,6 MiB RAM,
commit-base `34618bd4237bbb8bf6a3a303056fc95d799577f9` с незакоммиченными
изменениями текущего уровня. В Compose каждой API-реплике выделено 0,5 CPU и
256 MiB; HAProxy — 0,25 CPU/128 MiB; frontend Nginx — 0,10 CPU/64 MiB;
PostgreSQL — 1 CPU/512 MiB; Redis — 0,25 CPU/128 MiB.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
Команда `make grade4-experiment` создаёт синтетических пользователей и чат,
делает 12 warm-up записей, затем запускает 8 closed-loop клиентов без повторов
на стороне клиента. Baseline длится 12 с. В каждом failover воздействие
начинается через 3 с, предыдущая реплика восстанавливается перед остановкой
следующей, после действия нагрузка продолжается ещё 8 с. Rolling update
временно увеличивает сервис до трёх реплик, ждёт healthcheck и два периода
Docker DNS, заменяет старые контейнеры по одному и возвращает масштаб к двум.
Минимальный подтверждённый размер набора после прогона — 43 810 сообщений.
| Фаза | Успешно / ошибок | RPS | Доля ошибок | p50 / p95 / p99, мс | Восстановление |
| --- | ---: | ---: | ---: | ---: | ---: |
| baseline | 5762 / 0 | 479,581 | 0% | 9,178 / 56,402 / 79,978 | — |
| остановка реплики 1 | 7853 / 0 | 537,548 | 0% | 8,812 / 50,050 / 66,373 | 2,893 с |
| остановка реплики 2 | 7970 / 0 | 533,154 | 0% | 8,726 / 48,789 / 64,333 | 2,938 с |
| rolling update | 22 212 / 0 | 428,860 | 0% | 10,560 / 58,713 / 83,982 | непрерывная нагрузка |
На baseline средняя выборка одного API-контейнера составила 27,144% CPU и
31,008 MiB RAM, максимум — 30,93% и 66,17 MiB. PostgreSQL оказался самым
нагруженным компонентом: среднее 89,392% CPU при лимите одного ядра, максимум
110,59%; HAProxy использовал в среднем 26,262% CPU. Это не capacity-тест и не доказательство
saturation point, но важный ориентир для исследования уровня 5.
HAProxy обновляет Docker DNS раз в 1 с и исключает peer после двух неуспешных
активных `/health/ready`-проверок. Измеренные 2,893 и 2,938 с укладываются в
требование 10 с. Отдельный тест потери доступа одной реплики к PostgreSQL
подтвердил исключение неготового backend за 2,861 с без 5xx: 40 health-запросов
получили 200, а 20 регистраций — 201. Во всех четырёх фазах grade-4 эксперимента
ошибок нет. Параллельные 32 POST с одним ключом прошли через обе реплики и
вернули один Message ID.
Исходные агрегаты, environment/limits, посекундные таблицы и четыре SVG-графика
лежат в `evidence/grade4/`. Percentile рассчитаны только по успешным ответам;
профиль closed-loop имеет coordinated omission. CPU для API агрегируется как
средняя/максимальная выборка отдельного контейнера, а не сумма двух реплик.
## Исследование уровня 5: цена масштабирования
Трек 1 выполнен командой `make grade5-experiment` 23.10.2026 на том же
однохостовом стенде Windows + WSL2: Docker Engine 29.7.2, Compose 5.5.0,
8 логических CPU и 3813,6 MiB RAM. Базовым commit до изменений уровня 5 был
`5300a1a`; измерения ожидаемо зафиксировали dirty working tree, поскольку сам
скрипт и параметризация лимитов ещё не были закоммичены. Все запросы проходили
через единственную публичную точку HAProxy, создавали сообщения с уникальными
`Idempotency-Key` и не повторялись нагрузочным клиентом автоматически.
### Методика и воспроизводимость
Каждая измеряемая фаза длилась 10 секунд. После каждой смены профиля выполнялся
двухсекундный warm-up, затем контейнеры и реально применённые `NanoCpus`, RAM и
`DB_MAX_CONNS` проверялись через `docker inspect`. Скрипт сохраняет посекундные
request buckets и каждую выборку `docker stats`; CPU/RAM API сначала суммируются
по всем репликам в одной временной точке и только затем усредняются. Это устраняет
ошибку, при которой средняя загрузка одного из четырёх контейнеров выдавалась бы
за стоимость всего API-сервиса.
В серии с фиксированным бюджетом сохранялись суммарные 1 CPU, 512 MiB RAM и
16 соединений пула API:
| Реплики | CPU на реплику | RAM на реплику | `DB_MAX_CONNS` на реплику | Суммарный пул |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 1,00 | 512 MiB | 16 | 16 |
| 2 | 0,50 | 256 MiB | 8 | 16 |
| 4 | 0,25 | 128 MiB | 4 | 16 |
В серии роста каждая реплика получала 0,5 CPU, 256 MiB и 8 соединений, поэтому
суммарный API-бюджет менялся от 0,5 CPU/256 MiB/8 соединений до
2 CPU/1024 MiB/32 соединений. Во всех основных профилях PostgreSQL оставался на
1 CPU/512 MiB, HAProxy — 0,25 CPU/128 MiB, frontend Nginx — 0,10 CPU/64 MiB,
Redis — 0,25 CPU/128 MiB. Сравнение
1/2/4 выполнялось при одинаковом concurrency 32. До и после эксперимента
зафиксированы размер набора и базы: 225 626 → 299 524 сообщений и
175 406 103 → 228 793 367 байт. После любого исхода `finally` возвращает стенд к
двум API по 0,5 CPU/256 MiB, пулу 10 на реплику и PostgreSQL с 1 CPU; успешное
восстановление также записано в `results.json`.
### Насыщение и цена реплик
Для поиска saturation point две API-реплики с суммарным 1 CPU и пулом 16
нагружались последовательностью concurrency 1/2/4/8/16/32:
| Concurrency | RPS | p95, мс | PostgreSQL CPU avg/max | Ошибки |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 230,369 | 5,065 | 23,900% / 29,41% | 0 |
| 2 | 320,190 | 7,196 | 54,987% / 62,60% | 0 |
| 4 | 435,822 | 29,304 | 63,093% / 81,80% | 0 |
| 8 | 470,828 | 56,230 | 65,945% / 92,98% | 0 |
| 16 | 472,892 | 73,628 | 65,080% / 88,93% | 0 |
| 32 | 564,012 | 94,785 | 83,825% / 107,62% | 0 |
Заранее зафиксированное правило считает первым saturation signal шаг, где прирост
RPS меньше 10%, а p95 одновременно вырастает не менее чем в 1,5 раза. Это
произошло при переходе 4 → 8: throughput вырос только на 8,03%, а p95 — в
1,92 раза. При 16 клиентах прирост относительно 8 почти отсутствует (+0,44%),
а p95 продолжает расти; при 32 клиентах RPS увеличивается ценой ещё большей
очереди. Поэтому concurrency 8 — первый воспроизводимый saturation signal по
заранее заданному правилу, а не утверждение об абсолютном максимуме системы.
При фиксированном суммарном бюджете 1/2/4 реплики дали соответственно
578,242 / 529,499 / 353,955 RPS. Четыре процесса при том же общем бюджете дали
на 38,79% меньше одной реплики: дробление ресурсов добавило scheduling и pool
overhead, но не увеличило общую ёмкость. В серии роста ресурсов получены
533,656 / 563,460 / 438,868 RPS. Разброс и нестрогая монотонность честно
сохранены: это один прогон на одном Docker-host, где контейнеры конкурируют за
общий scheduler и одну БД. Главный результат здесь не выбор «лучшего» количества
реплик, а отсутствие пропорционального роста: четырёхкратный API-бюджет дал на
17,76% меньше throughput одной реплики в этом конкретном прогоне.
Доминирующее ограничение локализовано в PostgreSQL. В базовом профиле четырёх
реплик API суммарно использовал в среднем 35,690% CPU из доступных 200%, HAProxy —
15,595% из 25%, тогда как PostgreSQL использовал 84,847% в среднем и достигал
101,91% лимита одного ядра. Само по себе это корреляция, поэтому выполнено
контрольное изменение только одного параметра.
### Подтверждённое улучшение
Для тех же четырёх API по 0,5 CPU/256 MiB, того же пула и concurrency 32 лимит
PostgreSQL увеличен с 1 до 2 CPU. RPS вырос с 438,868 до 587,574 — на 33,88%;
ошибок в обеих фазах не было, p95 снизился с 109,446 до 93,991 мс (-14,12%).
Таким образом, снятие именно ограничения CPU БД существенно увеличило throughput
и улучшило tail latency, что подтверждает исходную гипотезу.
После улучшения PostgreSQL использовал в среднем 95,573% из доступных 200%, а
HAProxy — 22,350% при лимите 0,25 CPU и достигал 26,73%. То есть следующее
ограничение ожидаемо сместилось к публичному
балансировщику. Увеличивать API дальше без пересмотра лимита или топологии LB уже
нерационально — это и есть практическая «цена масштабирования».
Полный JSON с окружением, профилями, фактически применёнными лимитами и сырыми
выборками находится в `evidence/grade5/results.json`; агрегаты — в
`measurements.csv`, посекундные запросы — в `timeseries.csv`, ресурсы — в
`resources.csv`. Пять SVG показывают saturation curve, обе серии 1/2/4,
локализацию bottleneck и контрольное улучшение.
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Топология однохостовая: HAProxy и PostgreSQL остаются single points of failure.
Репликация БД и несколько балансировщиков в требования уровня «4» не входят.
- Redis содержит только кэш, поэтому его потеря допустима. Отдельная
персистентность Redis для корректности API не требуется.
- Истёкшие записи идемпотентности удаляются лениво при повторном обращении к той
же области ключа. Индекс по `expires_at` оставлен для будущей периодической
очистки без изменения схемы.
- Исследование уровня «5» выполняет по одному измеряемому прогону на профиль.
Для production capacity planning нужны несколько повторов, доверительные
интервалы и отдельный генератор нагрузки вне измеряемого Docker-host.
- Rolling-сценарий заменяет бинарник без изменения схемы. Миграции выполняются
однократно до API; для будущей несовместимой схемы потребуется expand/contract,
поэтому одновременная работа разных schema-version сейчас не заявляется.
- Текущий API не содержит endpoint поиска пользователей, аватаров, изменения
имени/пароля и агрегатов last message/unread. Поэтому UI принимает UUID
участников при создании чата, а профиль честно показывает только доступные
поля. Эти функции требуют сначала расширить и зафиксировать API-контракт.
- Однохостовая среда WSL2 не доказывает устойчивость к потере Docker-host;
измерен только отказ и замена процесса API.
+224
View File
@@ -0,0 +1,224 @@
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
cacheadapter "mtusi2026lab3/internal/adapter/cache"
"mtusi2026lab3/internal/adapter/postgres"
redisadapter "mtusi2026lab3/internal/adapter/redis"
"mtusi2026lab3/internal/application"
"mtusi2026lab3/internal/config"
"mtusi2026lab3/internal/database"
"mtusi2026lab3/internal/transport/http/handlers"
"mtusi2026lab3/internal/transport/http/middleware"
)
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
startupContext, startupCancel := context.WithTimeout(
context.Background(),
cfg.DatabaseConnectTimeout,
)
databasePool, err := database.Open(startupContext, cfg)
startupCancel()
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer databasePool.Close()
postgresStore := postgres.NewPostgreSQLStore(
databasePool,
cfg.DatabaseQueryTimeout,
)
var applicationStore application.Repository = postgresStore
if cfg.RedisURL != "" {
redisChatCache, cacheError := redisadapter.NewRedisChatCache(
cfg.RedisURL,
cfg.RedisCacheTTL,
cfg.RedisOperationTimeout,
cfg.RedisPoolSize,
)
if cacheError != nil {
log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError)
}
defer func() {
if closeError := redisChatCache.Close(); closeError != nil {
log.Printf("[WARN] Redis client close failed: %v", closeError)
}
}()
cacheContext, cacheCancel := context.WithTimeout(
context.Background(),
cfg.RedisOperationTimeout,
)
if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil {
log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError)
} else {
log.Println("[INFO] Redis chat cache is available")
}
cacheCancel()
applicationStore = cacheadapter.NewCachedRepository(
postgresStore,
redisChatCache,
log.Default(),
)
}
cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey)
if err != nil {
log.Fatalf("[FATAL] Invalid cursor configuration: %v", err)
}
service, err := application.NewService(
applicationStore,
cursorCodec,
cfg.SessionTTL,
application.WithIdempotencyTTL(cfg.IdempotencyTTL),
)
if err != nil {
log.Fatalf("[FATAL] Application initialization failed: %v", err)
}
handler := handlers.NewHandler(
service,
handlers.WithReadiness(
databasePool,
cfg.ReadinessTimeout,
),
handlers.WithSessionCookieSecure(cfg.SessionCookieSecure),
)
mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", handler.HealthLive)
mux.HandleFunc("GET /health/ready", handler.HealthReady)
mux.HandleFunc(
"POST /api/v1/auth/sessions",
handler.CreateSession,
)
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
requireAuth := func(next http.HandlerFunc) http.HandlerFunc {
return middleware.RequireAuth(service, next)
}
mux.HandleFunc(
"GET /api/v1/users/me",
requireAuth(handler.GetMe),
)
mux.HandleFunc(
"DELETE /api/v1/auth/sessions/current",
requireAuth(handler.DeleteCurrentSession),
)
mux.HandleFunc(
"POST /api/v1/chats",
requireAuth(handler.CreateChat),
)
mux.HandleFunc(
"GET /api/v1/chats",
requireAuth(handler.ListChats),
)
mux.HandleFunc(
"GET /api/v1/chats/{chat_id}",
requireAuth(handler.GetChat),
)
mux.HandleFunc(
"POST /api/v1/chats/{chat_id}/messages",
requireAuth(handler.CreateMessage),
)
mux.HandleFunc(
"GET /api/v1/chats/{chat_id}/messages",
requireAuth(handler.GetMessages),
)
var rootHandler http.Handler = mux
rootHandler = middleware.Recovery(rootHandler)
rootHandler = middleware.Logger(rootHandler)
availabilityGate := middleware.NewAvailabilityGate()
rootHandler = availabilityGate.Middleware(rootHandler)
rootHandler = middleware.RequestID(rootHandler)
rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler)
server := &http.Server{
Addr: cfg.HTTPAddress(),
Handler: rootHandler,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
serverErrors := make(chan error, 1)
go func() {
log.Printf(
"[INFO] Server instance %s starting on %s",
cfg.InstanceID,
server.Addr,
)
serverErrors <- server.ListenAndServe()
}()
shutdownSignals := make(chan os.Signal, 1)
signal.Notify(
shutdownSignals,
os.Interrupt,
syscall.SIGTERM,
)
defer signal.Stop(shutdownSignals)
select {
case serverError := <-serverErrors:
if !errors.Is(serverError, http.ErrServerClosed) {
log.Fatalf("[FATAL] Server crashed: %v", serverError)
}
case signalValue := <-shutdownSignals:
log.Printf(
"[INFO] Signal %v received. Starting graceful shutdown...",
signalValue,
)
availabilityGate.BeginDrain()
log.Printf(
"[INFO] Readiness disabled; draining new traffic for %s",
cfg.ShutdownDrainDelay,
)
time.Sleep(cfg.ShutdownDrainDelay)
shutdownContext, shutdownCancel := context.WithTimeout(
context.Background(),
cfg.ShutdownTimeout,
)
defer shutdownCancel()
if err := server.Shutdown(shutdownContext); err != nil {
log.Printf(
"[WARN] Graceful shutdown failed: %v. Forcing close.",
err,
)
_ = server.Close()
}
log.Println("[INFO] Server stopped gracefully.")
}
}
+251
View File
@@ -0,0 +1,251 @@
services:
load-balancer:
build:
context: .
dockerfile: infrastructure/haproxy/Dockerfile
image: mtusi2026lab3-load-balancer
ports:
- "127.0.0.1:${APP_PORT:-8080}:8080"
depends_on:
api:
condition: service_healthy
frontend:
condition: service_healthy
healthcheck:
test:
[
"CMD-SHELL",
"wget -qO- http://127.0.0.1:8080/health/ready || exit 1",
]
interval: 5s
timeout: 3s
retries: 10
start_period: 3s
stop_grace_period: 10s
restart: unless-stopped
deploy:
resources:
limits:
cpus: "0.25"
memory: 128M
frontend:
build:
context: .
dockerfile: infrastructure/nginx/Dockerfile
image: mtusi2026lab3-web
expose:
- "8080"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/ >/dev/null || exit 1"]
interval: 5s
timeout: 3s
retries: 10
start_period: 3s
stop_grace_period: 10s
restart: unless-stopped
deploy:
resources:
limits:
cpus: "0.10"
memory: 64M
postgres:
image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
environment:
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_DB: ${POSTGRES_DB:-messenger}
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test:
[
"CMD-SHELL",
"pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}",
]
interval: 5s
timeout: 3s
retries: 10
start_period: 5s
restart: unless-stopped
deploy:
resources:
limits:
cpus: "${POSTGRES_CPU_LIMIT:-1.00}"
memory: ${POSTGRES_MEMORY_LIMIT:-512M}
redis:
image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0
command:
[
"redis-server",
"--save",
"",
"--appendonly",
"no",
"--maxmemory",
"64mb",
"--maxmemory-policy",
"allkeys-lru",
]
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 10
start_period: 3s
stop_grace_period: 10s
restart: unless-stopped
deploy:
resources:
limits:
cpus: "0.25"
memory: 128M
migrate:
image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7
entrypoint: ["/bin/sh", "-ec"]
command:
- >
exec migrate
-path=/migrations
-database="$$(cat /run/secrets/database_url)"
up
secrets:
- database_url
volumes:
- ./migrations:/migrations:ro
depends_on:
postgres:
condition: service_healthy
restart: "no"
deploy:
resources:
limits:
cpus: "0.25"
memory: 64M
api:
build:
context: .
dockerfile: Dockerfile
environment:
APP_HOST: ${APP_HOST:-0.0.0.0}
APP_PORT: ${APP_PORT:-8080}
APP_ENV: ${APP_ENV:-lab}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
SESSION_STORE: ${SESSION_STORE:-postgres}
SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false}
CURSOR_SIGNING_KEY_FILE: ${CURSOR_SIGNING_KEY_FILE:-/run/secrets/cursor_signing_key}
CACHE_URL: ${CACHE_URL:-redis://redis:6379/0}
CACHE_TTL: ${CACHE_TTL:-5m}
CACHE_OPERATION_TIMEOUT: ${CACHE_OPERATION_TIMEOUT:-250ms}
CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-10}
DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url}
DB_MAX_CONNS: ${DB_MAX_CONNS:-10}
DB_MIN_CONNS: ${DB_MIN_CONNS:-2}
DB_MAX_CONN_LIFETIME: ${DB_MAX_CONN_LIFETIME:-30m}
DB_MAX_CONN_IDLE_TIME: ${DB_MAX_CONN_IDLE_TIME:-5m}
DB_HEALTH_CHECK_PERIOD: ${DB_HEALTH_CHECK_PERIOD:-30s}
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s}
DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s}
READINESS_TIMEOUT: ${READINESS_TIMEOUT:-2s}
SHUTDOWN_DRAIN_DELAY: ${SHUTDOWN_DRAIN_DELAY:-2s}
SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10s}
secrets:
- database_url
- cursor_signing_key
expose:
- "8080"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
migrate:
condition: service_completed_successfully
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits:
cpus: "${API_CPU_LIMIT:-0.50}"
memory: ${API_MEMORY_LIMIT:-256M}
healthcheck:
test:
[
"CMD-SHELL",
"wget -qO- http://127.0.0.1:$${APP_PORT:-8080}/health/ready || exit 1",
]
interval: 5s
timeout: 3s
retries: 10
start_period: 5s
stop_grace_period: 15s
restart: unless-stopped
redis-insight:
image: redis/redisinsight:3.8.0@sha256:b5e19ee240abef6edb435871b90ff8a210995422e8e018ab61c0339d318a1f84
profiles: ["tools"]
ports:
- "127.0.0.1:${REDIS_INSIGHT_PORT:-5540}:5540"
volumes:
- redis_insight_data:/data
depends_on:
redis:
condition: service_healthy
restart: unless-stopped
deploy:
resources:
limits:
cpus: "0.50"
memory: 256M
postgres-restore:
image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
profiles: ["recovery"]
environment:
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_DB: ${POSTGRES_RESTORE_DB:-messenger_restore_admin}
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
volumes:
- postgres_restore_data:/var/lib/postgresql/data
healthcheck:
test:
[
"CMD-SHELL",
"pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_RESTORE_DB:-messenger_restore_admin}",
]
interval: 5s
timeout: 3s
retries: 10
start_period: 5s
restart: "no"
deploy:
resources:
limits:
cpus: "1.00"
memory: 512M
volumes:
postgres_data:
redis_insight_data:
postgres_restore_data:
secrets:
postgres_password:
file: ./secrets/postgres_password.txt
database_url:
file: ./secrets/database_url.txt
cursor_signing_key:
file: ./secrets/cursor_signing_key.txt
+9
View File
@@ -3,3 +3,12 @@
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
## Сохранённые эксперименты
- `grade4/` — failover обеих API-реплик и rolling update под нагрузкой;
- `grade5/` — трек «Цена масштабирования»: saturation sweep, сравнение 1/2/4
реплик с фиксированным и растущим бюджетом, сырые JSON/CSV, пять SVG-графиков
и подтверждённое улучшение PostgreSQL CPU;
- `readiness-routing.json` — результат изоляции PostgreSQL от одной живой
API-реплики: время исключения backend, статусы запросов и восстановление.
+39
View File
@@ -0,0 +1,39 @@
# Lab 3 grade-4 experiment
Generated: 2026-10-23T15:23:05.031807+00:00.
## Method
- concurrency: 8;
- baseline duration: 12 s;
- load: closed-loop POST messages through the public HAProxy gateway;
- failover: both original API containers stopped and restored in turn;
- rolling update: one surge replica, old replicas replaced one by one;
- percentiles cover successful responses; failures are separate.
## Results
| Phase | RPS | Errors | p50 ms | p95 ms | p99 ms | Recovery s |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| baseline | 479.581 | 0 (0.000%) | 9.178 | 56.402 | 79.978 | n/a |
| failover-1 | 537.548 | 0 (0.000%) | 8.812 | 50.05 | 66.373 | 2.893 |
| failover-2 | 533.154 | 0 (0.000%) | 8.726 | 48.789 | 64.333 | 2.938 |
| rolling-update | 428.86 | 0 (0.000%) | 10.56 | 58.713 | 83.982 | n/a |
## Parallel idempotency
32 requests produced 1 unique message ID across 2 API instances.
## Graphs
![Throughput and errors](throughput-errors.svg)
![Latency](latency.svg)
![Timeline](timeline.svg)
![Resources](resources.svg)
## Scope
Single-host process failure and rolling replacement only. PostgreSQL and HAProxy remain single points of failure.
+69
View File
@@ -0,0 +1,69 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1100" height="560" viewBox="0 0 1100 560">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.bar { fill: #cfd2d6; }
.bar2 { fill: #73777f; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.error { fill: #8f949c; stroke: #f4f5f6; stroke-width: 1; }
.event { stroke: #a2a5aa; stroke-width: 2; stroke-dasharray: 6 5; }
</style>
<text x="48" y="42" class="title">Grade 4: successful latency percentiles</text>
<line x1="80" y1="450.0" x2="1040" y2="450.0" class="grid"/>
<text x="68" y="454.0" text-anchor="end" class="small">0</text>
<line x1="80" y1="378.0" x2="1040" y2="378.0" class="grid"/>
<text x="68" y="382.0" text-anchor="end" class="small">17</text>
<line x1="80" y1="306.0" x2="1040" y2="306.0" class="grid"/>
<text x="68" y="310.0" text-anchor="end" class="small">34</text>
<line x1="80" y1="234.0" x2="1040" y2="234.0" class="grid"/>
<text x="68" y="238.0" text-anchor="end" class="small">50</text>
<line x1="80" y1="162.0" x2="1040" y2="162.0" class="grid"/>
<text x="68" y="166.0" text-anchor="end" class="small">67</text>
<line x1="80" y1="90.0" x2="1040" y2="90.0" class="grid"/>
<text x="68" y="94.0" text-anchor="end" class="small">84</text>
<rect x="128.0" y="410.7" width="42.0" height="39.3" rx="7" class="bar"/>
<text x="149.0" y="403.7" text-anchor="middle" class="small">9</text>
<text x="149.0" y="470" text-anchor="middle" class="small">p50</text>
<rect x="178.0" y="208.2" width="42.0" height="241.8" rx="7" class="bar2"/>
<text x="199.0" y="201.2" text-anchor="middle" class="small">56</text>
<text x="199.0" y="470" text-anchor="middle" class="small">p95</text>
<rect x="228.0" y="107.2" width="42.0" height="342.8" rx="7" class="bar2"/>
<text x="249.0" y="100.2" text-anchor="middle" class="small">80</text>
<text x="249.0" y="470" text-anchor="middle" class="small">p99</text>
<text x="200.0" y="498" text-anchor="middle" class="label">baseline</text>
<rect x="368.0" y="412.2" width="42.0" height="37.8" rx="7" class="bar"/>
<text x="389.0" y="405.2" text-anchor="middle" class="small">9</text>
<text x="389.0" y="470" text-anchor="middle" class="small">p50</text>
<rect x="418.0" y="235.5" width="42.0" height="214.5" rx="7" class="bar2"/>
<text x="439.0" y="228.5" text-anchor="middle" class="small">50</text>
<text x="439.0" y="470" text-anchor="middle" class="small">p95</text>
<rect x="468.0" y="165.5" width="42.0" height="284.5" rx="7" class="bar2"/>
<text x="489.0" y="158.5" text-anchor="middle" class="small">66</text>
<text x="489.0" y="470" text-anchor="middle" class="small">p99</text>
<text x="440.0" y="498" text-anchor="middle" class="label">failover-1</text>
<rect x="608.0" y="412.6" width="42.0" height="37.4" rx="7" class="bar"/>
<text x="629.0" y="405.6" text-anchor="middle" class="small">9</text>
<text x="629.0" y="470" text-anchor="middle" class="small">p50</text>
<rect x="658.0" y="240.9" width="42.0" height="209.1" rx="7" class="bar2"/>
<text x="679.0" y="233.9" text-anchor="middle" class="small">49</text>
<text x="679.0" y="470" text-anchor="middle" class="small">p95</text>
<rect x="708.0" y="174.2" width="42.0" height="275.8" rx="7" class="bar2"/>
<text x="729.0" y="167.2" text-anchor="middle" class="small">64</text>
<text x="729.0" y="470" text-anchor="middle" class="small">p99</text>
<text x="680.0" y="498" text-anchor="middle" class="label">failover-2</text>
<rect x="848.0" y="404.7" width="42.0" height="45.3" rx="7" class="bar"/>
<text x="869.0" y="397.7" text-anchor="middle" class="small">11</text>
<text x="869.0" y="470" text-anchor="middle" class="small">p50</text>
<rect x="898.0" y="198.3" width="42.0" height="251.7" rx="7" class="bar2"/>
<text x="919.0" y="191.3" text-anchor="middle" class="small">59</text>
<text x="919.0" y="470" text-anchor="middle" class="small">p95</text>
<rect x="948.0" y="90.0" width="42.0" height="360.0" rx="7" class="bar2"/>
<text x="969.0" y="83.0" text-anchor="middle" class="small">84</text>
<text x="969.0" y="470" text-anchor="middle" class="small">p99</text>
<text x="920.0" y="498" text-anchor="middle" class="label">rolling-update</text>
<text x="24" y="270.0" transform="rotate(-90 24 270.0)" class="label">Successful latency, ms</text>
</svg>

After

Width:  |  Height:  |  Size: 4.4 KiB

+48
View File
@@ -0,0 +1,48 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1100" height="600" viewBox="0 0 1100 600">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.bar { fill: #cfd2d6; }
.bar2 { fill: #73777f; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.error { fill: #8f949c; stroke: #f4f5f6; stroke-width: 1; }
.event { stroke: #a2a5aa; stroke-width: 2; stroke-dasharray: 6 5; }
</style>
<text x="48" y="42" class="title">Grade 4: peak container resources</text>
<text x="80" y="72" class="label">Peak CPU, %</text>
<rect x="98.9" y="288.9" width="46.2" height="161.1" rx="9" class="bar"/>
<text x="122.0" y="280.9" text-anchor="middle" class="small">49.5</text>
<text x="122.0" y="475" text-anchor="middle" class="small">api</text>
<rect x="182.9" y="423.8" width="46.2" height="26.2" rx="9" class="bar"/>
<text x="206.0" y="415.8" text-anchor="middle" class="small">8.1</text>
<text x="206.0" y="475" text-anchor="middle" class="small">frontend</text>
<rect x="266.9" y="354.2" width="46.2" height="95.8" rx="9" class="bar"/>
<text x="290.0" y="346.2" text-anchor="middle" class="small">29.4</text>
<text x="290.0" y="475" text-anchor="middle" class="small">load-balancer</text>
<rect x="350.9" y="90.0" width="46.2" height="360.0" rx="9" class="bar"/>
<text x="374.0" y="82.0" text-anchor="middle" class="small">110.6</text>
<text x="374.0" y="475" text-anchor="middle" class="small">postgres</text>
<rect x="434.9" y="428.6" width="46.2" height="21.4" rx="9" class="bar"/>
<text x="458.0" y="420.6" text-anchor="middle" class="small">6.6</text>
<text x="458.0" y="475" text-anchor="middle" class="small">redis</text>
<text x="600" y="72" class="label">Peak memory, MiB</text>
<rect x="618.9" y="321.9" width="46.2" height="128.1" rx="9" class="bar"/>
<text x="642.0" y="313.9" text-anchor="middle" class="small">66.2</text>
<text x="642.0" y="475" text-anchor="middle" class="small">api</text>
<rect x="702.9" y="426.4" width="46.2" height="23.6" rx="9" class="bar"/>
<text x="726.0" y="418.4" text-anchor="middle" class="small">12.2</text>
<text x="726.0" y="475" text-anchor="middle" class="small">frontend</text>
<rect x="786.9" y="412.0" width="46.2" height="38.0" rx="9" class="bar"/>
<text x="810.0" y="404.0" text-anchor="middle" class="small">19.6</text>
<text x="810.0" y="475" text-anchor="middle" class="small">load-balancer</text>
<rect x="870.9" y="90.0" width="46.2" height="360.0" rx="9" class="bar"/>
<text x="894.0" y="82.0" text-anchor="middle" class="small">185.9</text>
<text x="894.0" y="475" text-anchor="middle" class="small">postgres</text>
<rect x="954.9" y="417.8" width="46.2" height="32.2" rx="9" class="bar"/>
<text x="978.0" y="409.8" text-anchor="middle" class="small">16.6</text>
<text x="978.0" y="475" text-anchor="middle" class="small">redis</text>
</svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

+680
View File
@@ -0,0 +1,680 @@
{
"schema_version": 1,
"environment": {
"utc_started_at": "2026-10-23T15:23:05.031807+00:00",
"git_commit": "5300a1a1e0e5497f2d30097bb1542b2743a8aad5",
"working_tree_dirty": true,
"logical_cpu_count": 8,
"host_memory_mib": 3813.6,
"docker_engine": "29.7.2",
"docker_compose": "5.5.0",
"container_limits": [
{
"service": "api",
"nano_cpus": 500000000,
"memory_limit_bytes": 268435456
},
{
"service": "api",
"nano_cpus": 500000000,
"memory_limit_bytes": 268435456
},
{
"service": "frontend",
"nano_cpus": 100000000,
"memory_limit_bytes": 67108864
},
{
"service": "load-balancer",
"nano_cpus": 250000000,
"memory_limit_bytes": 134217728
},
{
"service": "postgres",
"nano_cpus": 1000000000,
"memory_limit_bytes": 536870912
},
{
"service": "redis",
"nano_cpus": 250000000,
"memory_limit_bytes": 134217728
}
]
},
"methodology": {
"base_url": "http://localhost:8080",
"concurrency": 8,
"baseline_seconds": 12,
"action_after_seconds": 3,
"post_action_seconds": 8,
"warmup_requests": 12,
"workload": "closed-loop POST messages via the public HAProxy gateway; no automatic retries"
},
"phases": [
{
"name": "baseline",
"elapsed_seconds": 12.015,
"successful_requests": 5762,
"failed_requests": 0,
"error_ratio": 0.0,
"errors": {},
"successful_rps": 479.581,
"successful_latency_ms": {
"p50": 9.178,
"p95": 56.402,
"p99": 79.978
},
"instances": [
"a85567c48d67",
"df8a69558af0"
],
"recovery_seconds": null,
"action": null,
"per_second": {
"0": {
"successful": 434,
"failed": 0
},
"1": {
"successful": 280,
"failed": 0
},
"2": {
"successful": 372,
"failed": 0
},
"3": {
"successful": 436,
"failed": 0
},
"4": {
"successful": 541,
"failed": 0
},
"5": {
"successful": 474,
"failed": 0
},
"6": {
"successful": 526,
"failed": 0
},
"7": {
"successful": 539,
"failed": 0
},
"8": {
"successful": 554,
"failed": 0
},
"9": {
"successful": 559,
"failed": 0
},
"10": {
"successful": 448,
"failed": 0
},
"11": {
"successful": 584,
"failed": 0
},
"12": {
"successful": 15,
"failed": 0
}
},
"resources": {
"api": {
"cpu_percent_avg": 27.144,
"cpu_percent_max": 30.93,
"memory_mib_avg": 31.008,
"memory_mib_max": 66.17
},
"frontend": {
"cpu_percent_avg": 1.812,
"cpu_percent_max": 3.76,
"memory_mib_avg": 7.212,
"memory_mib_max": 10.15
},
"load-balancer": {
"cpu_percent_avg": 26.262,
"cpu_percent_max": 27.37,
"memory_mib_avg": 15.645,
"memory_mib_max": 15.97
},
"postgres": {
"cpu_percent_avg": 89.392,
"cpu_percent_max": 110.59,
"memory_mib_avg": 130.125,
"memory_mib_max": 132.2
},
"redis": {
"cpu_percent_avg": 2.488,
"cpu_percent_max": 6.58,
"memory_mib_avg": 15.072,
"memory_mib_max": 15.25
}
}
},
{
"name": "failover-1",
"elapsed_seconds": 14.609,
"successful_requests": 7853,
"failed_requests": 0,
"error_ratio": 0.0,
"errors": {},
"successful_rps": 537.548,
"successful_latency_ms": {
"p50": 8.812,
"p95": 50.05,
"p99": 66.373
},
"instances": [
"a85567c48d67",
"df8a69558af0"
],
"recovery_seconds": 2.893,
"action": {
"started_at": 3.003,
"ended_at": 5.888,
"duration_seconds": 2.885,
"exit_code": 0,
"summary": "stopped API instance df8a69558af0"
},
"per_second": {
"0": {
"successful": 551,
"failed": 0
},
"1": {
"successful": 605,
"failed": 0
},
"2": {
"successful": 558,
"failed": 0
},
"3": {
"successful": 443,
"failed": 0
},
"4": {
"successful": 575,
"failed": 0
},
"5": {
"successful": 538,
"failed": 0
},
"6": {
"successful": 593,
"failed": 0
},
"7": {
"successful": 623,
"failed": 0
},
"8": {
"successful": 507,
"failed": 0
},
"9": {
"successful": 626,
"failed": 0
},
"10": {
"successful": 608,
"failed": 0
},
"11": {
"successful": 601,
"failed": 0
},
"12": {
"successful": 556,
"failed": 0
},
"13": {
"successful": 469,
"failed": 0
}
},
"resources": {
"api": {
"cpu_percent_avg": 35.916,
"cpu_percent_max": 49.48,
"memory_mib_avg": 11.892,
"memory_mib_max": 13.27
},
"frontend": {
"cpu_percent_avg": 0.762,
"cpu_percent_max": 3.75,
"memory_mib_avg": 6.256,
"memory_mib_max": 6.434
},
"load-balancer": {
"cpu_percent_avg": 22.21,
"cpu_percent_max": 26.89,
"memory_mib_avg": 16.312,
"memory_mib_max": 16.93
},
"postgres": {
"cpu_percent_avg": 73.128,
"cpu_percent_max": 89.46,
"memory_mib_avg": 135.64,
"memory_mib_max": 141.9
},
"redis": {
"cpu_percent_avg": 0.782,
"cpu_percent_max": 3.27,
"memory_mib_avg": 15.258,
"memory_mib_max": 15.73
}
}
},
{
"name": "failover-2",
"elapsed_seconds": 14.949,
"successful_requests": 7970,
"failed_requests": 0,
"error_ratio": 0.0,
"errors": {},
"successful_rps": 533.154,
"successful_latency_ms": {
"p50": 8.726,
"p95": 48.789,
"p99": 64.333
},
"instances": [
"a85567c48d67",
"df8a69558af0"
],
"recovery_seconds": 2.938,
"action": {
"started_at": 3.006,
"ended_at": 5.933,
"duration_seconds": 2.927,
"exit_code": 0,
"summary": "stopped API instance a85567c48d67"
},
"per_second": {
"0": {
"successful": 584,
"failed": 0
},
"1": {
"successful": 613,
"failed": 0
},
"2": {
"successful": 570,
"failed": 0
},
"3": {
"successful": 465,
"failed": 0
},
"4": {
"successful": 564,
"failed": 0
},
"5": {
"successful": 605,
"failed": 0
},
"6": {
"successful": 610,
"failed": 0
},
"7": {
"successful": 579,
"failed": 0
},
"8": {
"successful": 497,
"failed": 0
},
"9": {
"successful": 575,
"failed": 0
},
"10": {
"successful": 569,
"failed": 0
},
"11": {
"successful": 600,
"failed": 0
},
"12": {
"successful": 586,
"failed": 0
},
"13": {
"successful": 553,
"failed": 0
}
},
"resources": {
"api": {
"cpu_percent_avg": 28.073,
"cpu_percent_max": 48.59,
"memory_mib_avg": 10.391,
"memory_mib_max": 13.47
},
"frontend": {
"cpu_percent_avg": 0.696,
"cpu_percent_max": 3.44,
"memory_mib_avg": 6.25,
"memory_mib_max": 6.398
},
"load-balancer": {
"cpu_percent_avg": 25.966,
"cpu_percent_max": 26.65,
"memory_mib_avg": 16.918,
"memory_mib_max": 17.25
},
"postgres": {
"cpu_percent_avg": 72.558,
"cpu_percent_max": 93.6,
"memory_mib_avg": 146.22,
"memory_mib_max": 160.2
},
"redis": {
"cpu_percent_avg": 0.168,
"cpu_percent_max": 0.2,
"memory_mib_avg": 15.646,
"memory_mib_max": 16.64
}
}
},
{
"name": "rolling-update",
"elapsed_seconds": 51.793,
"successful_requests": 22212,
"failed_requests": 0,
"error_ratio": 0.0,
"errors": {},
"successful_rps": 428.86,
"successful_latency_ms": {
"p50": 10.56,
"p95": 58.713,
"p99": 83.982
},
"instances": [
"872dbac02cd3",
"a85567c48d67",
"dac03e904506",
"df00f21e6f41",
"df8a69558af0"
],
"recovery_seconds": null,
"action": {
"started_at": 3.005,
"ended_at": 42.955,
"duration_seconds": 39.95,
"exit_code": 0,
"summary": "rolling update completed with 2 healthy API replicas"
},
"per_second": {
"0": {
"successful": 509,
"failed": 0
},
"1": {
"successful": 577,
"failed": 0
},
"2": {
"successful": 660,
"failed": 0
},
"3": {
"successful": 438,
"failed": 0
},
"4": {
"successful": 577,
"failed": 0
},
"5": {
"successful": 392,
"failed": 0
},
"6": {
"successful": 326,
"failed": 0
},
"7": {
"successful": 232,
"failed": 0
},
"8": {
"successful": 199,
"failed": 0
},
"9": {
"successful": 170,
"failed": 0
},
"10": {
"successful": 263,
"failed": 0
},
"11": {
"successful": 323,
"failed": 0
},
"12": {
"successful": 308,
"failed": 0
},
"13": {
"successful": 362,
"failed": 0
},
"14": {
"successful": 443,
"failed": 0
},
"15": {
"successful": 495,
"failed": 0
},
"16": {
"successful": 429,
"failed": 0
},
"17": {
"successful": 370,
"failed": 0
},
"18": {
"successful": 451,
"failed": 0
},
"19": {
"successful": 377,
"failed": 0
},
"20": {
"successful": 422,
"failed": 0
},
"21": {
"successful": 485,
"failed": 0
},
"22": {
"successful": 473,
"failed": 0
},
"23": {
"successful": 441,
"failed": 0
},
"24": {
"successful": 470,
"failed": 0
},
"25": {
"successful": 487,
"failed": 0
},
"26": {
"successful": 504,
"failed": 0
},
"27": {
"successful": 516,
"failed": 0
},
"28": {
"successful": 441,
"failed": 0
},
"29": {
"successful": 390,
"failed": 0
},
"30": {
"successful": 502,
"failed": 0
},
"31": {
"successful": 450,
"failed": 0
},
"32": {
"successful": 500,
"failed": 0
},
"33": {
"successful": 363,
"failed": 0
},
"34": {
"successful": 470,
"failed": 0
},
"35": {
"successful": 434,
"failed": 0
},
"36": {
"successful": 424,
"failed": 0
},
"37": {
"successful": 373,
"failed": 0
},
"38": {
"successful": 460,
"failed": 0
},
"39": {
"successful": 516,
"failed": 0
},
"40": {
"successful": 375,
"failed": 0
},
"41": {
"successful": 492,
"failed": 0
},
"42": {
"successful": 477,
"failed": 0
},
"43": {
"successful": 503,
"failed": 0
},
"44": {
"successful": 506,
"failed": 0
},
"45": {
"successful": 465,
"failed": 0
},
"46": {
"successful": 501,
"failed": 0
},
"47": {
"successful": 502,
"failed": 0
},
"48": {
"successful": 446,
"failed": 0
},
"49": {
"successful": 446,
"failed": 0
},
"50": {
"successful": 477,
"failed": 0
}
},
"resources": {
"api": {
"cpu_percent_avg": 20.954,
"cpu_percent_max": 31.69,
"memory_mib_avg": 8.855,
"memory_mib_max": 12.74
},
"frontend": {
"cpu_percent_avg": 1.326,
"cpu_percent_max": 8.06,
"memory_mib_avg": 7.43,
"memory_mib_max": 12.17
},
"load-balancer": {
"cpu_percent_avg": 24.581,
"cpu_percent_max": 29.42,
"memory_mib_avg": 17.398,
"memory_mib_max": 19.6
},
"postgres": {
"cpu_percent_avg": 77.881,
"cpu_percent_max": 102.6,
"memory_mib_avg": 170.081,
"memory_mib_max": 185.9
},
"redis": {
"cpu_percent_avg": 0.63,
"cpu_percent_max": 3.84,
"memory_mib_avg": 15.178,
"memory_mib_max": 15.91
}
}
}
],
"idempotency": {
"parallel_requests": 32,
"successful_responses": 32,
"failed_responses": 0,
"unique_message_ids": 1,
"observed_instances": [
"a85567c48d67",
"df8a69558af0"
]
},
"dataset": {
"warmup_requests": 12,
"minimum_confirmed_messages": 43810
},
"limitations": [
"single Docker host",
"closed-loop coordinated omission",
"successful-response latency percentiles only",
"PostgreSQL and HAProxy remain single points of failure"
]
}
+45
View File
@@ -0,0 +1,45 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1100" height="560" viewBox="0 0 1100 560">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.bar { fill: #cfd2d6; }
.bar2 { fill: #73777f; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.error { fill: #8f949c; stroke: #f4f5f6; stroke-width: 1; }
.event { stroke: #a2a5aa; stroke-width: 2; stroke-dasharray: 6 5; }
</style>
<text x="48" y="42" class="title">Grade 4: throughput and errors</text>
<line x1="80" y1="450.0" x2="1040" y2="450.0" class="grid"/>
<text x="68" y="454.0" text-anchor="end" class="small">0</text>
<line x1="80" y1="378.0" x2="1040" y2="378.0" class="grid"/>
<text x="68" y="382.0" text-anchor="end" class="small">108</text>
<line x1="80" y1="306.0" x2="1040" y2="306.0" class="grid"/>
<text x="68" y="310.0" text-anchor="end" class="small">215</text>
<line x1="80" y1="234.0" x2="1040" y2="234.0" class="grid"/>
<text x="68" y="238.0" text-anchor="end" class="small">323</text>
<line x1="80" y1="162.0" x2="1040" y2="162.0" class="grid"/>
<text x="68" y="166.0" text-anchor="end" class="small">430</text>
<line x1="80" y1="90.0" x2="1040" y2="90.0" class="grid"/>
<text x="68" y="94.0" text-anchor="end" class="small">538</text>
<rect x="140.0" y="128.8" width="120.0" height="321.2" rx="10" class="bar"/>
<text x="200.0" y="118.8" text-anchor="middle" class="label">479.6 RPS</text>
<text x="200.0" y="478" text-anchor="middle" class="label">baseline</text>
<text x="200.0" y="498" text-anchor="middle" class="small">errors 0.00%</text>
<rect x="380.0" y="90.0" width="120.0" height="360.0" rx="10" class="bar"/>
<text x="440.0" y="80.0" text-anchor="middle" class="label">537.5 RPS</text>
<text x="440.0" y="478" text-anchor="middle" class="label">failover-1</text>
<text x="440.0" y="498" text-anchor="middle" class="small">errors 0.00%</text>
<rect x="620.0" y="92.9" width="120.0" height="357.1" rx="10" class="bar"/>
<text x="680.0" y="82.9" text-anchor="middle" class="label">533.2 RPS</text>
<text x="680.0" y="478" text-anchor="middle" class="label">failover-2</text>
<text x="680.0" y="498" text-anchor="middle" class="small">errors 0.00%</text>
<rect x="860.0" y="162.8" width="120.0" height="287.2" rx="10" class="bar"/>
<text x="920.0" y="152.8" text-anchor="middle" class="label">428.9 RPS</text>
<text x="920.0" y="478" text-anchor="middle" class="label">rolling-update</text>
<text x="920.0" y="498" text-anchor="middle" class="small">errors 0.00%</text>
<text x="24" y="270.0" transform="rotate(-90 24 270.0)" class="label">Successful requests per second</text>
</svg>

After

Width:  |  Height:  |  Size: 2.8 KiB

+36
View File
@@ -0,0 +1,36 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1100" height="600" viewBox="0 0 1100 600">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.bar { fill: #cfd2d6; }
.bar2 { fill: #73777f; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.error { fill: #8f949c; stroke: #f4f5f6; stroke-width: 1; }
.event { stroke: #a2a5aa; stroke-width: 2; stroke-dasharray: 6 5; }
</style>
<text x="48" y="42" class="title">Grade 4: request timeline</text>
<line x1="70" y1="480.0" x2="1050" y2="480.0" class="grid"/>
<text x="58" y="484.0" text-anchor="end" class="small">0</text>
<line x1="70" y1="402.0" x2="1050" y2="402.0" class="grid"/>
<text x="58" y="406.0" text-anchor="end" class="small">132</text>
<line x1="70" y1="324.0" x2="1050" y2="324.0" class="grid"/>
<text x="58" y="328.0" text-anchor="end" class="small">264</text>
<line x1="70" y1="246.0" x2="1050" y2="246.0" class="grid"/>
<text x="58" y="250.0" text-anchor="end" class="small">396</text>
<line x1="70" y1="168.0" x2="1050" y2="168.0" class="grid"/>
<text x="58" y="172.0" text-anchor="end" class="small">528</text>
<line x1="70" y1="90.0" x2="1050" y2="90.0" class="grid"/>
<text x="58" y="94.0" text-anchor="end" class="small">660</text>
<polyline points="70.0,223.5 80.4,314.5 90.9,260.2 101.3,222.4 111.7,160.3 122.1,199.9 132.6,169.2 143.0,161.5 153.4,152.6 163.8,149.7 174.3,215.3 184.7,134.9 195.1,471.1 216.0,154.4 226.4,122.5 236.8,150.3 247.2,218.2 257.7,140.2 268.1,162.1 278.5,129.6 288.9,111.9 299.4,180.4 309.8,110.1 320.2,120.7 330.6,124.9 341.1,151.5 351.5,202.9 372.3,134.9 382.8,117.8 393.2,143.2 403.6,205.2 414.0,146.7 424.5,122.5 434.9,119.5 445.3,137.9 455.7,186.3 466.2,140.2 476.6,143.8 487.0,125.5 497.4,133.7 507.9,153.2 528.7,179.2 539.1,139.0 549.6,90.0 560.0,221.2 570.4,139.0 580.9,248.4 591.3,287.4 601.7,342.9 612.1,362.4 622.6,379.5 633.0,324.6 643.4,289.1 653.8,298.0 664.3,266.1 674.7,218.2 685.1,187.5 695.5,226.5 706.0,261.4 716.4,213.5 726.8,257.2 737.2,230.6 747.7,193.4 758.1,200.5 768.5,219.4 778.9,202.3 789.4,192.2 799.8,182.2 810.2,175.1 820.6,219.4 831.1,249.5 841.5,183.4 851.9,214.1 862.3,184.5 872.8,265.5 883.2,202.3 893.6,223.5 904.0,229.5 914.5,259.6 924.9,208.2 935.3,175.1 945.7,258.4 956.2,189.3 966.6,198.1 977.0,182.8 987.4,181.0 997.9,205.2 1008.3,184.0 1018.7,183.4 1029.1,216.5 1039.6,216.5 1050.0,198.1" class="line"/>
<line x1="247.3" y1="90" x2="247.3" y2="480" class="event"/>
<text x="253.3" y="108" class="small">failover-1 action</text>
<line x1="403.7" y1="90" x2="403.7" y2="480" class="event"/>
<text x="409.7" y="108" class="small">failover-2 action</text>
<line x1="560.1" y1="90" x2="560.1" y2="480" class="event"/>
<text x="566.1" y="108" class="small">rolling-update action</text>
<text x="70" y="512" class="label">One-second buckets; circles mark failed requests</text>
</svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

+63
View File
@@ -0,0 +1,63 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1120" height="620" viewBox="0 0 1120 620">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.subtitle { font-size: 14px; fill: #aeb2b8; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.axis { stroke: #747981; stroke-width: 1.5; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.line2 { fill: none; stroke: #92979f; stroke-width: 3; }
.point { fill: #f4f5f6; }
.point2 { fill: #92979f; }
.bar { fill: #d7d9dc; }
.bar2 { fill: #777c84; }
.bar3 { fill: #4c5057; }
.threshold { stroke: #8f949c; stroke-width: 2; stroke-dasharray: 7 5; }
</style>
<text x="50" y="44" class="title">Saturation curve</text>
<text x="50" y="70" class="subtitle">Two API replicas; 1 CPU total; 16 total DB connections; PostgreSQL limited to 1 CPU</text>
<line x1="90" y1="500.0" x2="1030" y2="500.0" class="grid"/>
<text x="78" y="504.0" text-anchor="end" class="small">0</text>
<line x1="90" y1="422.0" x2="1030" y2="422.0" class="grid"/>
<text x="78" y="426.0" text-anchor="end" class="small">124</text>
<line x1="90" y1="344.0" x2="1030" y2="344.0" class="grid"/>
<text x="78" y="348.0" text-anchor="end" class="small">248</text>
<line x1="90" y1="266.0" x2="1030" y2="266.0" class="grid"/>
<text x="78" y="270.0" text-anchor="end" class="small">372</text>
<line x1="90" y1="188.0" x2="1030" y2="188.0" class="grid"/>
<text x="78" y="192.0" text-anchor="end" class="small">496</text>
<line x1="90" y1="110.0" x2="1030" y2="110.0" class="grid"/>
<text x="78" y="114.0" text-anchor="end" class="small">620</text>
<circle cx="90.0" cy="355.2" r="6" class="point"/>
<circle cx="90.0" cy="481.1" r="6" class="point2"/>
<text x="90.0" y="528" text-anchor="middle" class="label">1</text>
<text x="90.0" y="343.2" text-anchor="middle" class="small">230</text>
<circle cx="278.0" cy="298.7" r="6" class="point"/>
<circle cx="278.0" cy="473.1" r="6" class="point2"/>
<text x="278.0" y="528" text-anchor="middle" class="label">2</text>
<text x="278.0" y="286.7" text-anchor="middle" class="small">320</text>
<circle cx="466.0" cy="226.0" r="6" class="point"/>
<circle cx="466.0" cy="390.4" r="6" class="point2"/>
<text x="466.0" y="528" text-anchor="middle" class="label">4</text>
<text x="466.0" y="214.0" text-anchor="middle" class="small">436</text>
<circle cx="654.0" cy="204.0" r="6" class="point"/>
<circle cx="654.0" cy="289.7" r="6" class="point2"/>
<text x="654.0" y="528" text-anchor="middle" class="label">8</text>
<text x="654.0" y="192.0" text-anchor="middle" class="small">471</text>
<circle cx="842.0" cy="202.7" r="6" class="point"/>
<circle cx="842.0" cy="224.6" r="6" class="point2"/>
<text x="842.0" y="528" text-anchor="middle" class="label">16</text>
<text x="842.0" y="190.7" text-anchor="middle" class="small">473</text>
<circle cx="1030.0" cy="145.5" r="6" class="point"/>
<circle cx="1030.0" cy="145.5" r="6" class="point2"/>
<text x="1030.0" y="528" text-anchor="middle" class="label">32</text>
<text x="1030.0" y="133.5" text-anchor="middle" class="small">564</text>
<polyline points="90.0,355.2 278.0,298.7 466.0,226.0 654.0,204.0 842.0,202.7 1030.0,145.5" class="line"/>
<polyline points="90.0,481.1 278.0,473.1 466.0,390.4 654.0,289.7 842.0,224.6 1030.0,145.5" class="line2"/>
<text x="90" y="562" class="label">Concurrency</text>
<text x="810" y="562" class="label">white: RPS · gray: p95 normalized</text>
<text x="30" y="305.0" transform="rotate(-90 30 305.0)" class="label">Successful requests per second</text>
</svg>

After

Width:  |  Height:  |  Size: 3.6 KiB

+49
View File
@@ -0,0 +1,49 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1120" height="620" viewBox="0 0 1120 620">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.subtitle { font-size: 14px; fill: #aeb2b8; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.axis { stroke: #747981; stroke-width: 1.5; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.line2 { fill: none; stroke: #92979f; stroke-width: 3; }
.point { fill: #f4f5f6; }
.point2 { fill: #92979f; }
.bar { fill: #d7d9dc; }
.bar2 { fill: #777c84; }
.bar3 { fill: #4c5057; }
.threshold { stroke: #8f949c; stroke-width: 2; stroke-dasharray: 7 5; }
</style>
<text x="50" y="44" class="title">Fixed total API budget</text>
<text x="50" y="70" class="subtitle">1 CPU · 512 MiB · 16 DB connections split across 1, 2 and 4 replicas</text>
<line x1="90" y1="480.0" x2="1030" y2="480.0" class="grid"/>
<text x="78" y="484.0" text-anchor="end" class="small">0</text>
<line x1="90" y1="406.0" x2="1030" y2="406.0" class="grid"/>
<text x="78" y="410.0" text-anchor="end" class="small">133</text>
<line x1="90" y1="332.0" x2="1030" y2="332.0" class="grid"/>
<text x="78" y="336.0" text-anchor="end" class="small">266</text>
<line x1="90" y1="258.0" x2="1030" y2="258.0" class="grid"/>
<text x="78" y="262.0" text-anchor="end" class="small">399</text>
<line x1="90" y1="184.0" x2="1030" y2="184.0" class="grid"/>
<text x="78" y="188.0" text-anchor="end" class="small">532</text>
<line x1="90" y1="110.0" x2="1030" y2="110.0" class="grid"/>
<text x="78" y="114.0" text-anchor="end" class="small">665</text>
<rect x="171.7" y="158.3" width="150.0" height="321.7" rx="14" class="bar"/>
<text x="246.7" y="146.3" text-anchor="middle" class="label">578.2 RPS</text>
<text x="246.7" y="510" text-anchor="middle" class="label">1 replica(s)</text>
<text x="246.7" y="532" text-anchor="middle" class="small">p95 95.8 ms</text>
<text x="246.7" y="550" text-anchor="middle" class="small">errors 0.000%</text>
<rect x="485.0" y="185.4" width="150.0" height="294.6" rx="14" class="bar"/>
<text x="560.0" y="173.4" text-anchor="middle" class="label">529.5 RPS</text>
<text x="560.0" y="510" text-anchor="middle" class="label">2 replica(s)</text>
<text x="560.0" y="532" text-anchor="middle" class="small">p95 100.1 ms</text>
<text x="560.0" y="550" text-anchor="middle" class="small">errors 0.000%</text>
<rect x="798.3" y="283.1" width="150.0" height="196.9" rx="14" class="bar"/>
<text x="873.3" y="271.1" text-anchor="middle" class="label">354.0 RPS</text>
<text x="873.3" y="510" text-anchor="middle" class="label">4 replica(s)</text>
<text x="873.3" y="532" text-anchor="middle" class="small">p95 139.4 ms</text>
<text x="873.3" y="550" text-anchor="middle" class="small">errors 0.000%</text>
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

+49
View File
@@ -0,0 +1,49 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1120" height="620" viewBox="0 0 1120 620">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.subtitle { font-size: 14px; fill: #aeb2b8; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.axis { stroke: #747981; stroke-width: 1.5; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.line2 { fill: none; stroke: #92979f; stroke-width: 3; }
.point { fill: #f4f5f6; }
.point2 { fill: #92979f; }
.bar { fill: #d7d9dc; }
.bar2 { fill: #777c84; }
.bar3 { fill: #4c5057; }
.threshold { stroke: #8f949c; stroke-width: 2; stroke-dasharray: 7 5; }
</style>
<text x="50" y="44" class="title">Growing API budget</text>
<text x="50" y="70" class="subtitle">Each replica adds 0.5 CPU · 256 MiB · 8 DB connections; PostgreSQL remains at 1 CPU</text>
<line x1="90" y1="480.0" x2="1030" y2="480.0" class="grid"/>
<text x="78" y="484.0" text-anchor="end" class="small">0</text>
<line x1="90" y1="406.0" x2="1030" y2="406.0" class="grid"/>
<text x="78" y="410.0" text-anchor="end" class="small">130</text>
<line x1="90" y1="332.0" x2="1030" y2="332.0" class="grid"/>
<text x="78" y="336.0" text-anchor="end" class="small">259</text>
<line x1="90" y1="258.0" x2="1030" y2="258.0" class="grid"/>
<text x="78" y="262.0" text-anchor="end" class="small">389</text>
<line x1="90" y1="184.0" x2="1030" y2="184.0" class="grid"/>
<text x="78" y="188.0" text-anchor="end" class="small">518</text>
<line x1="90" y1="110.0" x2="1030" y2="110.0" class="grid"/>
<text x="78" y="114.0" text-anchor="end" class="small">648</text>
<rect x="171.7" y="175.3" width="150.0" height="304.7" rx="14" class="bar"/>
<text x="246.7" y="163.3" text-anchor="middle" class="label">533.7 RPS</text>
<text x="246.7" y="510" text-anchor="middle" class="label">1 replica(s)</text>
<text x="246.7" y="532" text-anchor="middle" class="small">p95 93.5 ms</text>
<text x="246.7" y="550" text-anchor="middle" class="small">errors 0.000%</text>
<rect x="485.0" y="158.3" width="150.0" height="321.7" rx="14" class="bar"/>
<text x="560.0" y="146.3" text-anchor="middle" class="label">563.5 RPS</text>
<text x="560.0" y="510" text-anchor="middle" class="label">2 replica(s)</text>
<text x="560.0" y="532" text-anchor="middle" class="small">p95 96.4 ms</text>
<text x="560.0" y="550" text-anchor="middle" class="small">errors 0.000%</text>
<rect x="798.3" y="229.4" width="150.0" height="250.6" rx="14" class="bar"/>
<text x="873.3" y="217.4" text-anchor="middle" class="label">438.9 RPS</text>
<text x="873.3" y="510" text-anchor="middle" class="label">4 replica(s)</text>
<text x="873.3" y="532" text-anchor="middle" class="small">p95 109.4 ms</text>
<text x="873.3" y="550" text-anchor="middle" class="small">errors 0.000%</text>
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

+83
View File
@@ -0,0 +1,83 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1120" height="620" viewBox="0 0 1120 620">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.subtitle { font-size: 14px; fill: #aeb2b8; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.axis { stroke: #747981; stroke-width: 1.5; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.line2 { fill: none; stroke: #92979f; stroke-width: 3; }
.point { fill: #f4f5f6; }
.point2 { fill: #92979f; }
.bar { fill: #d7d9dc; }
.bar2 { fill: #777c84; }
.bar3 { fill: #4c5057; }
.threshold { stroke: #8f949c; stroke-width: 2; stroke-dasharray: 7 5; }
</style>
<text x="50" y="44" class="title">Where scaling stops</text>
<text x="50" y="70" class="subtitle">Aggregate service CPU during the proportional-growth series (api · postgres · HAProxy · frontend · redis)</text>
<line x1="90" y1="480.0" x2="1030" y2="480.0" class="grid"/>
<text x="78" y="484.0" text-anchor="end" class="small">0</text>
<line x1="90" y1="406.0" x2="1030" y2="406.0" class="grid"/>
<text x="78" y="410.0" text-anchor="end" class="small">20</text>
<line x1="90" y1="332.0" x2="1030" y2="332.0" class="grid"/>
<text x="78" y="336.0" text-anchor="end" class="small">39</text>
<line x1="90" y1="258.0" x2="1030" y2="258.0" class="grid"/>
<text x="78" y="262.0" text-anchor="end" class="small">59</text>
<line x1="90" y1="184.0" x2="1030" y2="184.0" class="grid"/>
<text x="78" y="188.0" text-anchor="end" class="small">79</text>
<line x1="90" y1="110.0" x2="1030" y2="110.0" class="grid"/>
<text x="78" y="114.0" text-anchor="end" class="small">98</text>
<rect x="127.6" y="336.1" width="48.0" height="143.9" rx="7" class="bar"/>
<text x="151.6" y="329.1" text-anchor="middle" class="small">38</text>
<text x="151.6" y="502" text-anchor="middle" class="small">api</text>
<rect x="184.6" y="189.6" width="48.0" height="290.4" rx="7" class="bar2"/>
<text x="208.6" y="182.6" text-anchor="middle" class="small">77</text>
<text x="208.6" y="502" text-anchor="middle" class="small">pos</text>
<rect x="241.6" y="404.6" width="48.0" height="75.4" rx="7" class="bar3"/>
<text x="265.6" y="397.6" text-anchor="middle" class="small">20</text>
<text x="265.6" y="502" text-anchor="middle" class="small">loa</text>
<rect x="298.6" y="477.4" width="48.0" height="2.6" rx="7" class="bar3"/>
<text x="322.6" y="470.4" text-anchor="middle" class="small">1</text>
<text x="322.6" y="502" text-anchor="middle" class="small">fro</text>
<rect x="355.6" y="476.4" width="48.0" height="3.6" rx="7" class="bar3"/>
<text x="379.6" y="469.4" text-anchor="middle" class="small">1</text>
<text x="379.6" y="502" text-anchor="middle" class="small">red</text>
<text x="246.7" y="532" text-anchor="middle" class="label">1 replica(s)</text>
<rect x="440.9" y="304.6" width="48.0" height="175.4" rx="7" class="bar"/>
<text x="464.9" y="297.6" text-anchor="middle" class="small">47</text>
<text x="464.9" y="502" text-anchor="middle" class="small">api</text>
<rect x="497.9" y="158.3" width="48.0" height="321.7" rx="7" class="bar2"/>
<text x="521.9" y="151.3" text-anchor="middle" class="small">86</text>
<text x="521.9" y="502" text-anchor="middle" class="small">pos</text>
<rect x="554.9" y="400.3" width="48.0" height="79.7" rx="7" class="bar3"/>
<text x="578.9" y="393.3" text-anchor="middle" class="small">21</text>
<text x="578.9" y="502" text-anchor="middle" class="small">loa</text>
<rect x="611.9" y="477.1" width="48.0" height="2.9" rx="7" class="bar3"/>
<text x="635.9" y="470.1" text-anchor="middle" class="small">1</text>
<text x="635.9" y="502" text-anchor="middle" class="small">fro</text>
<rect x="668.9" y="476.7" width="48.0" height="3.3" rx="7" class="bar3"/>
<text x="692.9" y="469.7" text-anchor="middle" class="small">1</text>
<text x="692.9" y="502" text-anchor="middle" class="small">red</text>
<text x="560.0" y="532" text-anchor="middle" class="label">2 replica(s)</text>
<rect x="754.3" y="345.8" width="48.0" height="134.2" rx="7" class="bar"/>
<text x="778.3" y="338.8" text-anchor="middle" class="small">36</text>
<text x="778.3" y="502" text-anchor="middle" class="small">api</text>
<rect x="811.3" y="161.1" width="48.0" height="318.9" rx="7" class="bar2"/>
<text x="835.3" y="154.1" text-anchor="middle" class="small">85</text>
<text x="835.3" y="502" text-anchor="middle" class="small">pos</text>
<rect x="868.3" y="421.4" width="48.0" height="58.6" rx="7" class="bar3"/>
<text x="892.3" y="414.4" text-anchor="middle" class="small">16</text>
<text x="892.3" y="502" text-anchor="middle" class="small">loa</text>
<rect x="925.3" y="477.5" width="48.0" height="2.5" rx="7" class="bar3"/>
<text x="949.3" y="470.5" text-anchor="middle" class="small">1</text>
<text x="949.3" y="502" text-anchor="middle" class="small">fro</text>
<rect x="982.3" y="476.7" width="48.0" height="3.3" rx="7" class="bar3"/>
<text x="1006.3" y="469.7" text-anchor="middle" class="small">1</text>
<text x="1006.3" y="502" text-anchor="middle" class="small">red</text>
<text x="873.3" y="532" text-anchor="middle" class="label">4 replica(s)</text>
<text x="30" y="295.0" transform="rotate(-90 30 295.0)" class="label">Average aggregate CPU, %</text>
</svg>

After

Width:  |  Height:  |  Size: 5.2 KiB

+37
View File
@@ -0,0 +1,37 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1120" height="620" viewBox="0 0 1120 620">
<rect width="100%" height="100%" fill="#0e1013"/>
<style>
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
.title { font-size: 26px; font-weight: 650; }
.subtitle { font-size: 14px; fill: #aeb2b8; }
.label { font-size: 14px; fill: #c8cbd0; }
.small { font-size: 12px; fill: #a2a5aa; }
.grid { stroke: #34373d; stroke-width: 1; }
.axis { stroke: #747981; stroke-width: 1.5; }
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
.line2 { fill: none; stroke: #92979f; stroke-width: 3; }
.point { fill: #f4f5f6; }
.point2 { fill: #92979f; }
.bar { fill: #d7d9dc; }
.bar2 { fill: #777c84; }
.bar3 { fill: #4c5057; }
.threshold { stroke: #8f949c; stroke-width: 2; stroke-dasharray: 7 5; }
</style>
<text x="50" y="44" class="title">Confirmed improvement</text>
<text x="50" y="70" class="subtitle">Four API replicas unchanged; only the PostgreSQL CPU limit changes from 1 to 2</text>
<text x="90" y="98" class="label">Successful RPS</text>
<rect x="125" y="248.4" width="120" height="211.6" rx="14" class="bar2"/>
<text x="185" y="238.4" text-anchor="middle" class="label">438.9</text>
<text x="185" y="488" text-anchor="middle" class="small">PG 1 CPU</text>
<rect x="310" y="176.7" width="120" height="283.3" rx="14" class="bar"/>
<text x="370" y="166.7" text-anchor="middle" class="label">587.6</text>
<text x="370" y="488" text-anchor="middle" class="small">PG 2 CPU</text>
<text x="630" y="98" class="label">p95 latency, ms</text>
<rect x="665" y="176.7" width="120" height="283.3" rx="14" class="bar2"/>
<text x="725" y="166.7" text-anchor="middle" class="label">109.4</text>
<text x="725" y="488" text-anchor="middle" class="small">PG 1 CPU</text>
<rect x="850" y="216.7" width="120" height="243.3" rx="14" class="bar"/>
<text x="910" y="206.7" text-anchor="middle" class="label">94.0</text>
<text x="910" y="488" text-anchor="middle" class="small">PG 2 CPU</text>
<text x="90" y="545" class="label">RPS change: +33.88% · p95 change: -14.12% · confirmed: true</text>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

+69
View File
@@ -0,0 +1,69 @@
# Lab 3 grade-5 scaling experiment
Generated: 2026-10-23T15:23:12.734339+00:00.
## Hypothesis
API replicas stop improving throughput when shared PostgreSQL CPU saturates; adding PostgreSQL CPU should improve the unchanged four-replica profile.
## Reproduction
- workload: closed-loop POST messages through the public HAProxy gateway; unique idempotency keys; no client retries;
- phase duration: 10 s;
- comparison concurrency: 32;
- saturation sweep: [1, 2, 4, 8, 16, 32];
- fixed budget: 1.00 API CPU, 512 MiB API RAM, 16 total DB pool connections;
- growth series: 0.50 API CPU, 256 MiB RAM and 8 DB pool connections per replica;
- saturation rule: RPS gain below 10% and p95 growth at least 1.5x versus the previous step;
- host: 8 logical CPU, 3813.6 MiB RAM;
- Docker 29.7.2, Compose 5.5.0;
- command: `make grade5-experiment`; warmup runs before every changed profile.
## Measurements
| Phase | Replicas | Concurrency | RPS | Errors | p50 ms | p95 ms | p99 ms | PG CPU avg | API CPU avg |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| saturation-c1 | 2 | 1 | 230.369 | 0 (0.000%) | 3.839 | 5.065 | 6.282 | 23.9 | 26.85 |
| saturation-c2 | 2 | 2 | 320.19 | 0 (0.000%) | 5.192 | 7.196 | 15.11 | 54.987 | 48.3 |
| saturation-c4 | 2 | 4 | 435.822 | 0 (0.000%) | 6.171 | 29.304 | 47.665 | 63.093 | 54.453 |
| saturation-c8 | 2 | 8 | 470.828 | 0 (0.000%) | 9.159 | 56.23 | 70.71 | 65.945 | 48.505 |
| saturation-c16 | 2 | 16 | 472.892 | 0 (0.000%) | 19.862 | 73.628 | 98.773 | 65.08 | 38.028 |
| saturation-c32 | 2 | 32 | 564.012 | 0 (0.000%) | 51.089 | 94.785 | 109.138 | 83.825 | 51.965 |
| fixed-r1 | 1 | 32 | 578.242 | 0 (0.000%) | 48.579 | 95.757 | 115.549 | 79.058 | 36.575 |
| fixed-r2 | 2 | 32 | 529.499 | 0 (0.000%) | 53.316 | 100.145 | 129.953 | 81.065 | 44.7 |
| fixed-r4 | 4 | 32 | 353.955 | 0 (0.000%) | 69.354 | 139.408 | 291.312 | 74.677 | 46.25 |
| growth-r1 | 1 | 32 | 533.656 | 0 (0.000%) | 53.378 | 93.541 | 115.58 | 77.252 | 38.273 |
| growth-r2 | 2 | 32 | 563.46 | 0 (0.000%) | 50.516 | 96.428 | 129.46 | 85.597 | 46.653 |
| growth-r4 | 4 | 32 | 438.868 | 0 (0.000%) | 68.331 | 109.446 | 199.616 | 84.847 | 35.69 |
| improved-db-cpu-r4 | 4 | 32 | 587.574 | 0 (0.000%) | 49.466 | 93.991 | 112.002 | 95.573 | 55.2 |
## Conclusion
The first saturation signal appears at concurrency 8: RPS changes by +8.03% while p95 changes by 1.92x versus concurrency 4.
Observed bottleneck classification: `postgres_cpu`.
The PostgreSQL CPU change produced +33.88% RPS and -14.12% p95; confirmed improvement: `true`.
After the improvement the remaining bottleneck classification is `load_balancer_cpu`.
## Graphs
![Saturation](01-saturation.svg)
![Fixed budget](02-fixed-total.svg)
![Growing budget](03-resource-growth.svg)
![Bottleneck](04-bottleneck.svg)
![Improvement](05-improvement.svg)
## Raw data and limits
Raw aggregates are in `measurements.csv`; one-second request buckets are in `timeseries.csv`; every resource sample is in `resources.csv`; complete metadata and applied limits are in `results.json`.
- single Docker host: replicas do not prove host-level availability
- closed-loop workload has coordinated omission
- successful-response latency percentiles are reported separately from failures
- one measured run per profile; host scheduling noise is possible
+14
View File
@@ -0,0 +1,14 @@
phase,kind,replicas,concurrency,elapsed_seconds,successful_requests,failed_requests,error_ratio,successful_rps,p50_ms,p95_ms,p99_ms,api_cpu_avg,postgres_cpu_avg,load_balancer_cpu_avg,frontend_cpu_avg,redis_cpu_avg
saturation-c1,saturation,2,1,10.731,2472,0,0.0,230.369,3.839,5.065,6.282,26.85,23.9,11.662,0.688,0.8
saturation-c2,saturation,2,2,10.915,3495,0,0.0,320.19,5.192,7.196,15.11,48.3,54.987,19.13,0.325,0.193
saturation-c4,saturation,2,4,10.832,4721,0,0.0,435.822,6.171,29.304,47.665,54.453,63.093,20.843,0.95,0.81
saturation-c8,saturation,2,8,10.821,5095,0,0.0,470.828,9.159,56.23,70.71,48.505,65.945,20.867,0.86,0.953
saturation-c16,saturation,2,16,10.876,5143,0,0.0,472.892,19.862,73.628,98.773,38.028,65.08,20.98,1.113,0.172
saturation-c32,saturation,2,32,10.808,6096,0,0.0,564.012,51.089,94.785,109.138,51.965,83.825,21.163,1.837,2.475
fixed-r1,fixed,1,32,10.88,6291,0,0.0,578.242,48.579,95.757,115.549,36.575,79.058,20.732,0.005,1.232
fixed-r2,fixed,2,32,10.905,5774,0,0.0,529.499,53.316,100.145,129.953,44.7,81.065,21.15,0.823,1.093
fixed-r4,fixed,4,32,11.917,4218,0,0.0,353.955,69.354,139.408,291.312,46.25,74.677,21.18,0.637,2.715
growth-r1,growth,1,32,10.951,5844,0,0.0,533.656,53.378,93.541,115.58,38.273,77.252,20.062,0.693,0.958
growth-r2,growth,2,32,10.796,6083,0,0.0,563.46,50.516,96.428,129.46,46.653,85.597,21.192,0.765,0.865
growth-r4,growth,4,32,10.682,4688,0,0.0,438.868,68.331,109.446,199.616,35.69,84.847,15.595,0.667,0.873
improved-db-cpu-r4,improvement,4,32,10.601,6229,0,0.0,587.574,49.466,93.991,112.002,55.2,95.573,22.35,0.83,0.458
1 phase kind replicas concurrency elapsed_seconds successful_requests failed_requests error_ratio successful_rps p50_ms p95_ms p99_ms api_cpu_avg postgres_cpu_avg load_balancer_cpu_avg frontend_cpu_avg redis_cpu_avg
2 saturation-c1 saturation 2 1 10.731 2472 0 0.0 230.369 3.839 5.065 6.282 26.85 23.9 11.662 0.688 0.8
3 saturation-c2 saturation 2 2 10.915 3495 0 0.0 320.19 5.192 7.196 15.11 48.3 54.987 19.13 0.325 0.193
4 saturation-c4 saturation 2 4 10.832 4721 0 0.0 435.822 6.171 29.304 47.665 54.453 63.093 20.843 0.95 0.81
5 saturation-c8 saturation 2 8 10.821 5095 0 0.0 470.828 9.159 56.23 70.71 48.505 65.945 20.867 0.86 0.953
6 saturation-c16 saturation 2 16 10.876 5143 0 0.0 472.892 19.862 73.628 98.773 38.028 65.08 20.98 1.113 0.172
7 saturation-c32 saturation 2 32 10.808 6096 0 0.0 564.012 51.089 94.785 109.138 51.965 83.825 21.163 1.837 2.475
8 fixed-r1 fixed 1 32 10.88 6291 0 0.0 578.242 48.579 95.757 115.549 36.575 79.058 20.732 0.005 1.232
9 fixed-r2 fixed 2 32 10.905 5774 0 0.0 529.499 53.316 100.145 129.953 44.7 81.065 21.15 0.823 1.093
10 fixed-r4 fixed 4 32 11.917 4218 0 0.0 353.955 69.354 139.408 291.312 46.25 74.677 21.18 0.637 2.715
11 growth-r1 growth 1 32 10.951 5844 0 0.0 533.656 53.378 93.541 115.58 38.273 77.252 20.062 0.693 0.958
12 growth-r2 growth 2 32 10.796 6083 0 0.0 563.46 50.516 96.428 129.46 46.653 85.597 21.192 0.765 0.865
13 growth-r4 growth 4 32 10.682 4688 0 0.0 438.868 68.331 109.446 199.616 35.69 84.847 15.595 0.667 0.873
14 improved-db-cpu-r4 improvement 4 32 10.601 6229 0 0.0 587.574 49.466 93.991 112.002 55.2 95.573 22.35 0.83 0.458
+261
View File
@@ -0,0 +1,261 @@
phase,t,service,containers,cpu_percent,memory_mib
saturation-c1,0.0,api,2,26.09,17.976
saturation-c1,0.0,frontend,1,1.61,7.578
saturation-c1,0.0,load-balancer,1,13.0,17.18
saturation-c1,0.0,postgres,1,28.57,169.0
saturation-c1,0.0,redis,1,0.15,15.28
saturation-c1,2.356,api,2,32.65,16.886
saturation-c1,2.356,frontend,1,0.02,7.617
saturation-c1,2.356,load-balancer,1,13.32,17.23
saturation-c1,2.356,postgres,1,28.96,169.5
saturation-c1,2.356,redis,1,2.75,15.4
saturation-c1,5.485,api,2,27.72,17.586
saturation-c1,5.485,frontend,1,0.0,7.383
saturation-c1,5.485,load-balancer,1,13.69,17.41
saturation-c1,5.485,postgres,1,29.41,170.1
saturation-c1,5.485,redis,1,0.15,15.28
saturation-c1,8.605,api,2,20.94,17.41
saturation-c1,8.605,frontend,1,1.12,12.06
saturation-c1,8.605,load-balancer,1,6.64,17.24
saturation-c1,8.605,postgres,1,8.66,170.5
saturation-c1,8.605,redis,1,0.15,15.53
saturation-c2,0.001,api,2,51.0,17.761
saturation-c2,0.001,frontend,1,0.03,7.617
saturation-c2,0.001,load-balancer,1,24.78,17.71
saturation-c2,0.001,postgres,1,57.44,171.2
saturation-c2,0.001,redis,1,0.17,16.03
saturation-c2,2.361,api,2,45.61,17.516
saturation-c2,2.361,frontend,1,0.03,7.367
saturation-c2,2.361,load-balancer,1,24.6,17.41
saturation-c2,2.361,postgres,1,49.85,172.6
saturation-c2,2.361,redis,1,0.18,15.28
saturation-c2,5.543,api,2,51.19,16.258
saturation-c2,5.543,frontend,1,0.02,7.367
saturation-c2,5.543,load-balancer,1,24.27,17.91
saturation-c2,5.543,postgres,1,62.6,173.0
saturation-c2,5.543,redis,1,0.21,15.28
saturation-c2,8.736,api,2,45.4,17.082
saturation-c2,8.736,frontend,1,1.22,8.121
saturation-c2,8.736,load-balancer,1,2.87,17.2
saturation-c2,8.736,postgres,1,50.06,173.8
saturation-c2,8.736,redis,1,0.21,15.78
saturation-c4,0.001,api,2,65.41,17.297
saturation-c4,0.001,frontend,1,0.03,7.367
saturation-c4,0.001,load-balancer,1,25.95,17.71
saturation-c4,0.001,postgres,1,81.8,174.4
saturation-c4,0.001,redis,1,0.19,15.28
saturation-c4,2.372,api,2,60.01,18.188
saturation-c4,2.372,frontend,1,3.75,7.965
saturation-c4,2.372,load-balancer,1,26.04,17.46
saturation-c4,2.372,postgres,1,79.42,175.4
saturation-c4,2.372,redis,1,0.16,15.53
saturation-c4,5.501,api,2,56.53,17.433
saturation-c4,5.501,frontend,1,0.02,7.367
saturation-c4,5.501,load-balancer,1,25.9,21.22
saturation-c4,5.501,postgres,1,73.71,175.7
saturation-c4,5.501,redis,1,0.18,15.28
saturation-c4,8.662,api,2,35.86,16.699
saturation-c4,8.662,frontend,1,0.0,7.367
saturation-c4,8.662,load-balancer,1,5.48,17.53
saturation-c4,8.662,postgres,1,17.44,177.2
saturation-c4,8.662,redis,1,2.71,16.1
saturation-c8,0.006,api,2,48.34,17.403
saturation-c8,0.006,frontend,1,0.0,7.367
saturation-c8,0.006,load-balancer,1,25.42,20.12
saturation-c8,0.006,postgres,1,77.51,185.1
saturation-c8,0.006,redis,1,0.18,15.28
saturation-c8,2.372,api,2,57.14,18.602
saturation-c8,2.372,frontend,1,3.44,7.734
saturation-c8,2.372,load-balancer,1,26.83,17.14
saturation-c8,2.372,postgres,1,92.98,188.5
saturation-c8,2.372,redis,1,3.34,15.28
saturation-c8,5.527,api,2,48.26,18.192
saturation-c8,5.527,frontend,1,0.0,7.363
saturation-c8,5.527,load-balancer,1,25.47,17.28
saturation-c8,5.527,postgres,1,76.05,189.4
saturation-c8,5.527,redis,1,0.15,15.28
saturation-c8,8.685,api,2,40.28,21.813
saturation-c8,8.685,frontend,1,0.0,7.363
saturation-c8,8.685,load-balancer,1,5.75,17.64
saturation-c8,8.685,postgres,1,17.24,190.4
saturation-c8,8.685,redis,1,0.14,15.28
saturation-c16,0.015,api,2,44.39,18.796
saturation-c16,0.015,frontend,1,0.0,7.363
saturation-c16,0.015,load-balancer,1,26.92,17.44
saturation-c16,0.015,postgres,1,82.81,205.9
saturation-c16,0.015,redis,1,0.17,15.28
saturation-c16,2.354,api,2,56.54,17.856
saturation-c16,2.354,frontend,1,0.03,7.375
saturation-c16,2.354,load-balancer,1,26.66,17.69
saturation-c16,2.354,postgres,1,88.93,207.7
saturation-c16,2.354,redis,1,0.19,15.75
saturation-c16,5.525,api,2,41.39,17.73
saturation-c16,5.525,frontend,1,4.4,7.379
saturation-c16,5.525,load-balancer,1,25.76,17.7
saturation-c16,5.525,postgres,1,72.49,208.6
saturation-c16,5.525,redis,1,0.18,15.25
saturation-c16,8.731,api,2,9.79,18.257
saturation-c16,8.731,frontend,1,0.02,7.375
saturation-c16,8.731,load-balancer,1,4.58,17.55
saturation-c16,8.731,postgres,1,16.09,209.7
saturation-c16,8.731,redis,1,0.15,15.33
saturation-c32,0.039,api,2,55.84,18.75
saturation-c32,0.039,frontend,1,6.63,8.125
saturation-c32,0.039,load-balancer,1,25.97,18.0
saturation-c32,0.039,postgres,1,104.2,210.6
saturation-c32,0.039,redis,1,5.85,15.05
saturation-c32,2.29,api,2,56.87,18.933
saturation-c32,2.29,frontend,1,0.0,7.625
saturation-c32,2.29,load-balancer,1,27.03,19.23
saturation-c32,2.29,postgres,1,105.41,212.1
saturation-c32,2.29,redis,1,0.19,15.55
saturation-c32,5.446,api,2,64.13,19.003
saturation-c32,5.446,frontend,1,0.7,7.375
saturation-c32,5.446,load-balancer,1,26.33,18.27
saturation-c32,5.446,postgres,1,107.62,213.1
saturation-c32,5.446,redis,1,3.7,15.27
saturation-c32,8.653,api,2,31.02,19.379
saturation-c32,8.653,frontend,1,0.02,7.625
saturation-c32,8.653,load-balancer,1,5.32,18.36
saturation-c32,8.653,postgres,1,18.07,213.5
saturation-c32,8.653,redis,1,0.16,15.26
fixed-r1,0.034,api,1,45.68,10.61
fixed-r1,0.034,frontend,1,0.02,7.359
fixed-r1,0.034,load-balancer,1,25.97,18.08
fixed-r1,0.034,postgres,1,106.86,214.7
fixed-r1,0.034,redis,1,4.41,15.3
fixed-r1,2.424,api,1,48.23,11.36
fixed-r1,2.424,frontend,1,0.0,7.699
fixed-r1,2.424,load-balancer,1,27.02,22.21
fixed-r1,2.424,postgres,1,96.33,215.7
fixed-r1,2.424,redis,1,0.14,15.44
fixed-r1,5.588,api,1,48.84,12.07
fixed-r1,5.588,frontend,1,0.0,7.359
fixed-r1,5.588,load-balancer,1,26.38,18.43
fixed-r1,5.588,postgres,1,104.71,217.4
fixed-r1,5.588,redis,1,0.19,15.92
fixed-r1,8.743,api,1,3.55,11.93
fixed-r1,8.743,frontend,1,0.0,7.508
fixed-r1,8.743,load-balancer,1,3.56,17.96
fixed-r1,8.743,postgres,1,8.33,218.1
fixed-r1,8.743,redis,1,0.19,16.07
fixed-r2,0.041,api,2,52.24,18.086
fixed-r2,0.041,frontend,1,0.0,7.359
fixed-r2,0.041,load-balancer,1,26.74,18.2
fixed-r2,0.041,postgres,1,100.69,219.4
fixed-r2,0.041,redis,1,3.81,15.18
fixed-r2,2.379,api,2,65.39,18.801
fixed-r2,2.379,frontend,1,1.92,7.859
fixed-r2,2.379,load-balancer,1,26.23,18.61
fixed-r2,2.379,postgres,1,106.33,221.3
fixed-r2,2.379,redis,1,0.16,15.16
fixed-r2,5.564,api,2,54.12,18.379
fixed-r2,5.564,frontend,1,1.37,10.54
fixed-r2,5.564,load-balancer,1,25.33,18.35
fixed-r2,5.564,postgres,1,103.06,222.7
fixed-r2,5.564,redis,1,0.2,14.93
fixed-r2,8.728,api,2,7.05,18.086
fixed-r2,8.728,frontend,1,0.0,7.363
fixed-r2,8.728,load-balancer,1,6.3,17.82
fixed-r2,8.728,postgres,1,14.18,223.3
fixed-r2,8.728,redis,1,0.2,15.43
fixed-r4,0.095,api,4,51.98,27.492
fixed-r4,0.095,frontend,1,0.0,7.363
fixed-r4,0.095,load-balancer,1,27.15,19.06
fixed-r4,0.095,postgres,1,90.1,223.1
fixed-r4,0.095,redis,1,5.94,16.87
fixed-r4,3.244,api,4,64.6,33.144
fixed-r4,3.244,frontend,1,0.02,7.359
fixed-r4,3.244,load-balancer,1,26.34,18.58
fixed-r4,3.244,postgres,1,101.51,225.1
fixed-r4,3.244,redis,1,0.2,16.96
fixed-r4,6.45,api,4,65.35,34.281
fixed-r4,6.45,frontend,1,0.02,7.359
fixed-r4,6.45,load-balancer,1,26.27,18.56
fixed-r4,6.45,postgres,1,106.68,225.7
fixed-r4,6.45,redis,1,4.55,16.7
fixed-r4,9.725,api,4,3.07,32.867
fixed-r4,9.725,frontend,1,2.51,7.762
fixed-r4,9.725,load-balancer,1,4.96,17.89
fixed-r4,9.725,postgres,1,0.42,226.7
fixed-r4,9.725,redis,1,0.17,16.95
growth-r1,0.045,api,1,44.44,9.355
growth-r1,0.045,frontend,1,0.0,7.359
growth-r1,0.045,load-balancer,1,25.9,18.3
growth-r1,0.045,postgres,1,93.36,207.6
growth-r1,0.045,redis,1,3.22,18.55
growth-r1,2.404,api,1,50.32,9.379
growth-r1,2.404,frontend,1,0.0,7.363
growth-r1,2.404,load-balancer,1,25.42,18.36
growth-r1,2.404,postgres,1,96.7,209.4
growth-r1,2.404,redis,1,0.22,18.11
growth-r1,5.579,api,1,50.68,9.66
growth-r1,5.579,frontend,1,0.03,7.613
growth-r1,5.579,load-balancer,1,25.44,18.67
growth-r1,5.579,postgres,1,105.06,210.9
growth-r1,5.579,redis,1,0.22,17.84
growth-r1,8.767,api,1,7.65,9.262
growth-r1,8.767,frontend,1,2.74,8.02
growth-r1,8.767,load-balancer,1,3.49,17.86
growth-r1,8.767,postgres,1,13.89,211.8
growth-r1,8.767,redis,1,0.17,17.93
growth-r2,0.047,api,2,52.25,17.629
growth-r2,0.047,frontend,1,0.02,7.363
growth-r2,0.047,load-balancer,1,24.23,18.59
growth-r2,0.047,postgres,1,100.9,233.3
growth-r2,0.047,redis,1,0.14,17.16
growth-r2,2.292,api,2,62.86,17.606
growth-r2,2.292,frontend,1,0.0,7.355
growth-r2,2.292,load-balancer,1,25.57,18.19
growth-r2,2.292,postgres,1,105.07,235.3
growth-r2,2.292,redis,1,0.16,17.16
growth-r2,5.459,api,2,57.29,18.789
growth-r2,5.459,frontend,1,0.04,7.363
growth-r2,5.459,load-balancer,1,25.89,18.43
growth-r2,5.459,postgres,1,104.58,235.1
growth-r2,5.459,redis,1,0.17,17.73
growth-r2,8.628,api,2,14.21,17.832
growth-r2,8.628,frontend,1,3.0,8.062
growth-r2,8.628,load-balancer,1,9.08,18.0
growth-r2,8.628,postgres,1,31.84,234.3
growth-r2,8.628,redis,1,2.99,22.08
growth-r4,0.043,api,4,25.03,29.672
growth-r4,0.043,frontend,1,0.02,7.316
growth-r4,0.043,load-balancer,1,9.16,18.25
growth-r4,0.043,postgres,1,99.03,269.2
growth-r4,0.043,redis,1,0.15,16.5
growth-r4,2.197,api,4,48.89,31.184
growth-r4,2.197,frontend,1,2.63,7.305
growth-r4,2.197,load-balancer,1,23.31,18.25
growth-r4,2.197,postgres,1,100.3,284.5
growth-r4,2.197,redis,1,2.97,20.3
growth-r4,5.406,api,4,43.96,32.164
growth-r4,5.406,frontend,1,0.0,7.305
growth-r4,5.406,load-balancer,1,19.48,17.79
growth-r4,5.406,postgres,1,101.91,290.1
growth-r4,5.406,redis,1,0.19,16.68
growth-r4,8.538,api,4,24.88,32.855
growth-r4,8.538,frontend,1,0.02,7.551
growth-r4,8.538,load-balancer,1,10.43,17.5
growth-r4,8.538,postgres,1,38.15,279.9
growth-r4,8.538,redis,1,0.18,16.91
improved-db-cpu-r4,0.054,api,4,52.63,30.188
improved-db-cpu-r4,0.054,frontend,1,0.03,7.301
improved-db-cpu-r4,0.054,load-balancer,1,24.59,18.03
improved-db-cpu-r4,0.054,postgres,1,121.18,130.1
improved-db-cpu-r4,0.054,redis,1,1.35,16.63
improved-db-cpu-r4,2.129,api,4,70.26,36.812
improved-db-cpu-r4,2.129,frontend,1,0.0,7.301
improved-db-cpu-r4,2.129,load-balancer,1,25.64,18.99
improved-db-cpu-r4,2.129,postgres,1,106.99,141.4
improved-db-cpu-r4,2.129,redis,1,0.16,16.88
improved-db-cpu-r4,5.271,api,4,65.05,33.652
improved-db-cpu-r4,5.271,frontend,1,3.29,7.43
improved-db-cpu-r4,5.271,load-balancer,1,26.73,18.41
improved-db-cpu-r4,5.271,postgres,1,102.2,145.9
improved-db-cpu-r4,5.271,redis,1,0.14,16.63
improved-db-cpu-r4,8.446,api,4,32.86,34.023
improved-db-cpu-r4,8.446,frontend,1,0.0,7.301
improved-db-cpu-r4,8.446,load-balancer,1,12.44,18.0
improved-db-cpu-r4,8.446,postgres,1,51.92,147.6
improved-db-cpu-r4,8.446,redis,1,0.18,16.88
1 phase t service containers cpu_percent memory_mib
2 saturation-c1 0.0 api 2 26.09 17.976
3 saturation-c1 0.0 frontend 1 1.61 7.578
4 saturation-c1 0.0 load-balancer 1 13.0 17.18
5 saturation-c1 0.0 postgres 1 28.57 169.0
6 saturation-c1 0.0 redis 1 0.15 15.28
7 saturation-c1 2.356 api 2 32.65 16.886
8 saturation-c1 2.356 frontend 1 0.02 7.617
9 saturation-c1 2.356 load-balancer 1 13.32 17.23
10 saturation-c1 2.356 postgres 1 28.96 169.5
11 saturation-c1 2.356 redis 1 2.75 15.4
12 saturation-c1 5.485 api 2 27.72 17.586
13 saturation-c1 5.485 frontend 1 0.0 7.383
14 saturation-c1 5.485 load-balancer 1 13.69 17.41
15 saturation-c1 5.485 postgres 1 29.41 170.1
16 saturation-c1 5.485 redis 1 0.15 15.28
17 saturation-c1 8.605 api 2 20.94 17.41
18 saturation-c1 8.605 frontend 1 1.12 12.06
19 saturation-c1 8.605 load-balancer 1 6.64 17.24
20 saturation-c1 8.605 postgres 1 8.66 170.5
21 saturation-c1 8.605 redis 1 0.15 15.53
22 saturation-c2 0.001 api 2 51.0 17.761
23 saturation-c2 0.001 frontend 1 0.03 7.617
24 saturation-c2 0.001 load-balancer 1 24.78 17.71
25 saturation-c2 0.001 postgres 1 57.44 171.2
26 saturation-c2 0.001 redis 1 0.17 16.03
27 saturation-c2 2.361 api 2 45.61 17.516
28 saturation-c2 2.361 frontend 1 0.03 7.367
29 saturation-c2 2.361 load-balancer 1 24.6 17.41
30 saturation-c2 2.361 postgres 1 49.85 172.6
31 saturation-c2 2.361 redis 1 0.18 15.28
32 saturation-c2 5.543 api 2 51.19 16.258
33 saturation-c2 5.543 frontend 1 0.02 7.367
34 saturation-c2 5.543 load-balancer 1 24.27 17.91
35 saturation-c2 5.543 postgres 1 62.6 173.0
36 saturation-c2 5.543 redis 1 0.21 15.28
37 saturation-c2 8.736 api 2 45.4 17.082
38 saturation-c2 8.736 frontend 1 1.22 8.121
39 saturation-c2 8.736 load-balancer 1 2.87 17.2
40 saturation-c2 8.736 postgres 1 50.06 173.8
41 saturation-c2 8.736 redis 1 0.21 15.78
42 saturation-c4 0.001 api 2 65.41 17.297
43 saturation-c4 0.001 frontend 1 0.03 7.367
44 saturation-c4 0.001 load-balancer 1 25.95 17.71
45 saturation-c4 0.001 postgres 1 81.8 174.4
46 saturation-c4 0.001 redis 1 0.19 15.28
47 saturation-c4 2.372 api 2 60.01 18.188
48 saturation-c4 2.372 frontend 1 3.75 7.965
49 saturation-c4 2.372 load-balancer 1 26.04 17.46
50 saturation-c4 2.372 postgres 1 79.42 175.4
51 saturation-c4 2.372 redis 1 0.16 15.53
52 saturation-c4 5.501 api 2 56.53 17.433
53 saturation-c4 5.501 frontend 1 0.02 7.367
54 saturation-c4 5.501 load-balancer 1 25.9 21.22
55 saturation-c4 5.501 postgres 1 73.71 175.7
56 saturation-c4 5.501 redis 1 0.18 15.28
57 saturation-c4 8.662 api 2 35.86 16.699
58 saturation-c4 8.662 frontend 1 0.0 7.367
59 saturation-c4 8.662 load-balancer 1 5.48 17.53
60 saturation-c4 8.662 postgres 1 17.44 177.2
61 saturation-c4 8.662 redis 1 2.71 16.1
62 saturation-c8 0.006 api 2 48.34 17.403
63 saturation-c8 0.006 frontend 1 0.0 7.367
64 saturation-c8 0.006 load-balancer 1 25.42 20.12
65 saturation-c8 0.006 postgres 1 77.51 185.1
66 saturation-c8 0.006 redis 1 0.18 15.28
67 saturation-c8 2.372 api 2 57.14 18.602
68 saturation-c8 2.372 frontend 1 3.44 7.734
69 saturation-c8 2.372 load-balancer 1 26.83 17.14
70 saturation-c8 2.372 postgres 1 92.98 188.5
71 saturation-c8 2.372 redis 1 3.34 15.28
72 saturation-c8 5.527 api 2 48.26 18.192
73 saturation-c8 5.527 frontend 1 0.0 7.363
74 saturation-c8 5.527 load-balancer 1 25.47 17.28
75 saturation-c8 5.527 postgres 1 76.05 189.4
76 saturation-c8 5.527 redis 1 0.15 15.28
77 saturation-c8 8.685 api 2 40.28 21.813
78 saturation-c8 8.685 frontend 1 0.0 7.363
79 saturation-c8 8.685 load-balancer 1 5.75 17.64
80 saturation-c8 8.685 postgres 1 17.24 190.4
81 saturation-c8 8.685 redis 1 0.14 15.28
82 saturation-c16 0.015 api 2 44.39 18.796
83 saturation-c16 0.015 frontend 1 0.0 7.363
84 saturation-c16 0.015 load-balancer 1 26.92 17.44
85 saturation-c16 0.015 postgres 1 82.81 205.9
86 saturation-c16 0.015 redis 1 0.17 15.28
87 saturation-c16 2.354 api 2 56.54 17.856
88 saturation-c16 2.354 frontend 1 0.03 7.375
89 saturation-c16 2.354 load-balancer 1 26.66 17.69
90 saturation-c16 2.354 postgres 1 88.93 207.7
91 saturation-c16 2.354 redis 1 0.19 15.75
92 saturation-c16 5.525 api 2 41.39 17.73
93 saturation-c16 5.525 frontend 1 4.4 7.379
94 saturation-c16 5.525 load-balancer 1 25.76 17.7
95 saturation-c16 5.525 postgres 1 72.49 208.6
96 saturation-c16 5.525 redis 1 0.18 15.25
97 saturation-c16 8.731 api 2 9.79 18.257
98 saturation-c16 8.731 frontend 1 0.02 7.375
99 saturation-c16 8.731 load-balancer 1 4.58 17.55
100 saturation-c16 8.731 postgres 1 16.09 209.7
101 saturation-c16 8.731 redis 1 0.15 15.33
102 saturation-c32 0.039 api 2 55.84 18.75
103 saturation-c32 0.039 frontend 1 6.63 8.125
104 saturation-c32 0.039 load-balancer 1 25.97 18.0
105 saturation-c32 0.039 postgres 1 104.2 210.6
106 saturation-c32 0.039 redis 1 5.85 15.05
107 saturation-c32 2.29 api 2 56.87 18.933
108 saturation-c32 2.29 frontend 1 0.0 7.625
109 saturation-c32 2.29 load-balancer 1 27.03 19.23
110 saturation-c32 2.29 postgres 1 105.41 212.1
111 saturation-c32 2.29 redis 1 0.19 15.55
112 saturation-c32 5.446 api 2 64.13 19.003
113 saturation-c32 5.446 frontend 1 0.7 7.375
114 saturation-c32 5.446 load-balancer 1 26.33 18.27
115 saturation-c32 5.446 postgres 1 107.62 213.1
116 saturation-c32 5.446 redis 1 3.7 15.27
117 saturation-c32 8.653 api 2 31.02 19.379
118 saturation-c32 8.653 frontend 1 0.02 7.625
119 saturation-c32 8.653 load-balancer 1 5.32 18.36
120 saturation-c32 8.653 postgres 1 18.07 213.5
121 saturation-c32 8.653 redis 1 0.16 15.26
122 fixed-r1 0.034 api 1 45.68 10.61
123 fixed-r1 0.034 frontend 1 0.02 7.359
124 fixed-r1 0.034 load-balancer 1 25.97 18.08
125 fixed-r1 0.034 postgres 1 106.86 214.7
126 fixed-r1 0.034 redis 1 4.41 15.3
127 fixed-r1 2.424 api 1 48.23 11.36
128 fixed-r1 2.424 frontend 1 0.0 7.699
129 fixed-r1 2.424 load-balancer 1 27.02 22.21
130 fixed-r1 2.424 postgres 1 96.33 215.7
131 fixed-r1 2.424 redis 1 0.14 15.44
132 fixed-r1 5.588 api 1 48.84 12.07
133 fixed-r1 5.588 frontend 1 0.0 7.359
134 fixed-r1 5.588 load-balancer 1 26.38 18.43
135 fixed-r1 5.588 postgres 1 104.71 217.4
136 fixed-r1 5.588 redis 1 0.19 15.92
137 fixed-r1 8.743 api 1 3.55 11.93
138 fixed-r1 8.743 frontend 1 0.0 7.508
139 fixed-r1 8.743 load-balancer 1 3.56 17.96
140 fixed-r1 8.743 postgres 1 8.33 218.1
141 fixed-r1 8.743 redis 1 0.19 16.07
142 fixed-r2 0.041 api 2 52.24 18.086
143 fixed-r2 0.041 frontend 1 0.0 7.359
144 fixed-r2 0.041 load-balancer 1 26.74 18.2
145 fixed-r2 0.041 postgres 1 100.69 219.4
146 fixed-r2 0.041 redis 1 3.81 15.18
147 fixed-r2 2.379 api 2 65.39 18.801
148 fixed-r2 2.379 frontend 1 1.92 7.859
149 fixed-r2 2.379 load-balancer 1 26.23 18.61
150 fixed-r2 2.379 postgres 1 106.33 221.3
151 fixed-r2 2.379 redis 1 0.16 15.16
152 fixed-r2 5.564 api 2 54.12 18.379
153 fixed-r2 5.564 frontend 1 1.37 10.54
154 fixed-r2 5.564 load-balancer 1 25.33 18.35
155 fixed-r2 5.564 postgres 1 103.06 222.7
156 fixed-r2 5.564 redis 1 0.2 14.93
157 fixed-r2 8.728 api 2 7.05 18.086
158 fixed-r2 8.728 frontend 1 0.0 7.363
159 fixed-r2 8.728 load-balancer 1 6.3 17.82
160 fixed-r2 8.728 postgres 1 14.18 223.3
161 fixed-r2 8.728 redis 1 0.2 15.43
162 fixed-r4 0.095 api 4 51.98 27.492
163 fixed-r4 0.095 frontend 1 0.0 7.363
164 fixed-r4 0.095 load-balancer 1 27.15 19.06
165 fixed-r4 0.095 postgres 1 90.1 223.1
166 fixed-r4 0.095 redis 1 5.94 16.87
167 fixed-r4 3.244 api 4 64.6 33.144
168 fixed-r4 3.244 frontend 1 0.02 7.359
169 fixed-r4 3.244 load-balancer 1 26.34 18.58
170 fixed-r4 3.244 postgres 1 101.51 225.1
171 fixed-r4 3.244 redis 1 0.2 16.96
172 fixed-r4 6.45 api 4 65.35 34.281
173 fixed-r4 6.45 frontend 1 0.02 7.359
174 fixed-r4 6.45 load-balancer 1 26.27 18.56
175 fixed-r4 6.45 postgres 1 106.68 225.7
176 fixed-r4 6.45 redis 1 4.55 16.7
177 fixed-r4 9.725 api 4 3.07 32.867
178 fixed-r4 9.725 frontend 1 2.51 7.762
179 fixed-r4 9.725 load-balancer 1 4.96 17.89
180 fixed-r4 9.725 postgres 1 0.42 226.7
181 fixed-r4 9.725 redis 1 0.17 16.95
182 growth-r1 0.045 api 1 44.44 9.355
183 growth-r1 0.045 frontend 1 0.0 7.359
184 growth-r1 0.045 load-balancer 1 25.9 18.3
185 growth-r1 0.045 postgres 1 93.36 207.6
186 growth-r1 0.045 redis 1 3.22 18.55
187 growth-r1 2.404 api 1 50.32 9.379
188 growth-r1 2.404 frontend 1 0.0 7.363
189 growth-r1 2.404 load-balancer 1 25.42 18.36
190 growth-r1 2.404 postgres 1 96.7 209.4
191 growth-r1 2.404 redis 1 0.22 18.11
192 growth-r1 5.579 api 1 50.68 9.66
193 growth-r1 5.579 frontend 1 0.03 7.613
194 growth-r1 5.579 load-balancer 1 25.44 18.67
195 growth-r1 5.579 postgres 1 105.06 210.9
196 growth-r1 5.579 redis 1 0.22 17.84
197 growth-r1 8.767 api 1 7.65 9.262
198 growth-r1 8.767 frontend 1 2.74 8.02
199 growth-r1 8.767 load-balancer 1 3.49 17.86
200 growth-r1 8.767 postgres 1 13.89 211.8
201 growth-r1 8.767 redis 1 0.17 17.93
202 growth-r2 0.047 api 2 52.25 17.629
203 growth-r2 0.047 frontend 1 0.02 7.363
204 growth-r2 0.047 load-balancer 1 24.23 18.59
205 growth-r2 0.047 postgres 1 100.9 233.3
206 growth-r2 0.047 redis 1 0.14 17.16
207 growth-r2 2.292 api 2 62.86 17.606
208 growth-r2 2.292 frontend 1 0.0 7.355
209 growth-r2 2.292 load-balancer 1 25.57 18.19
210 growth-r2 2.292 postgres 1 105.07 235.3
211 growth-r2 2.292 redis 1 0.16 17.16
212 growth-r2 5.459 api 2 57.29 18.789
213 growth-r2 5.459 frontend 1 0.04 7.363
214 growth-r2 5.459 load-balancer 1 25.89 18.43
215 growth-r2 5.459 postgres 1 104.58 235.1
216 growth-r2 5.459 redis 1 0.17 17.73
217 growth-r2 8.628 api 2 14.21 17.832
218 growth-r2 8.628 frontend 1 3.0 8.062
219 growth-r2 8.628 load-balancer 1 9.08 18.0
220 growth-r2 8.628 postgres 1 31.84 234.3
221 growth-r2 8.628 redis 1 2.99 22.08
222 growth-r4 0.043 api 4 25.03 29.672
223 growth-r4 0.043 frontend 1 0.02 7.316
224 growth-r4 0.043 load-balancer 1 9.16 18.25
225 growth-r4 0.043 postgres 1 99.03 269.2
226 growth-r4 0.043 redis 1 0.15 16.5
227 growth-r4 2.197 api 4 48.89 31.184
228 growth-r4 2.197 frontend 1 2.63 7.305
229 growth-r4 2.197 load-balancer 1 23.31 18.25
230 growth-r4 2.197 postgres 1 100.3 284.5
231 growth-r4 2.197 redis 1 2.97 20.3
232 growth-r4 5.406 api 4 43.96 32.164
233 growth-r4 5.406 frontend 1 0.0 7.305
234 growth-r4 5.406 load-balancer 1 19.48 17.79
235 growth-r4 5.406 postgres 1 101.91 290.1
236 growth-r4 5.406 redis 1 0.19 16.68
237 growth-r4 8.538 api 4 24.88 32.855
238 growth-r4 8.538 frontend 1 0.02 7.551
239 growth-r4 8.538 load-balancer 1 10.43 17.5
240 growth-r4 8.538 postgres 1 38.15 279.9
241 growth-r4 8.538 redis 1 0.18 16.91
242 improved-db-cpu-r4 0.054 api 4 52.63 30.188
243 improved-db-cpu-r4 0.054 frontend 1 0.03 7.301
244 improved-db-cpu-r4 0.054 load-balancer 1 24.59 18.03
245 improved-db-cpu-r4 0.054 postgres 1 121.18 130.1
246 improved-db-cpu-r4 0.054 redis 1 1.35 16.63
247 improved-db-cpu-r4 2.129 api 4 70.26 36.812
248 improved-db-cpu-r4 2.129 frontend 1 0.0 7.301
249 improved-db-cpu-r4 2.129 load-balancer 1 25.64 18.99
250 improved-db-cpu-r4 2.129 postgres 1 106.99 141.4
251 improved-db-cpu-r4 2.129 redis 1 0.16 16.88
252 improved-db-cpu-r4 5.271 api 4 65.05 33.652
253 improved-db-cpu-r4 5.271 frontend 1 3.29 7.43
254 improved-db-cpu-r4 5.271 load-balancer 1 26.73 18.41
255 improved-db-cpu-r4 5.271 postgres 1 102.2 145.9
256 improved-db-cpu-r4 5.271 redis 1 0.14 16.63
257 improved-db-cpu-r4 8.446 api 4 32.86 34.023
258 improved-db-cpu-r4 8.446 frontend 1 0.0 7.301
259 improved-db-cpu-r4 8.446 load-balancer 1 12.44 18.0
260 improved-db-cpu-r4 8.446 postgres 1 51.92 147.6
261 improved-db-cpu-r4 8.446 redis 1 0.18 16.88
File diff suppressed because it is too large Load Diff
+144
View File
@@ -0,0 +1,144 @@
phase,second,successful,failed
saturation-c1,0,252,0
saturation-c1,1,266,0
saturation-c1,2,257,0
saturation-c1,3,262,0
saturation-c1,4,253,0
saturation-c1,5,249,0
saturation-c1,6,228,0
saturation-c1,7,240,0
saturation-c1,8,219,0
saturation-c1,9,244,0
saturation-c1,10,2,0
saturation-c2,0,444,0
saturation-c2,1,377,0
saturation-c2,2,352,0
saturation-c2,3,297,0
saturation-c2,4,383,0
saturation-c2,5,324,0
saturation-c2,6,275,0
saturation-c2,7,323,0
saturation-c2,8,333,0
saturation-c2,9,381,0
saturation-c2,10,6,0
saturation-c4,0,526,0
saturation-c4,1,453,0
saturation-c4,2,425,0
saturation-c4,3,478,0
saturation-c4,4,510,0
saturation-c4,5,468,0
saturation-c4,6,458,0
saturation-c4,7,428,0
saturation-c4,8,490,0
saturation-c4,9,474,0
saturation-c4,10,11,0
saturation-c8,0,532,0
saturation-c8,1,476,0
saturation-c8,2,530,0
saturation-c8,3,529,0
saturation-c8,4,490,0
saturation-c8,5,527,0
saturation-c8,6,445,0
saturation-c8,7,524,0
saturation-c8,8,507,0
saturation-c8,9,519,0
saturation-c8,10,16,0
saturation-c16,0,349,0
saturation-c16,1,592,0
saturation-c16,2,541,0
saturation-c16,3,491,0
saturation-c16,4,545,0
saturation-c16,5,420,0
saturation-c16,6,499,0
saturation-c16,7,529,0
saturation-c16,8,548,0
saturation-c16,9,601,0
saturation-c16,10,28,0
saturation-c32,0,661,0
saturation-c32,1,604,0
saturation-c32,2,610,0
saturation-c32,3,589,0
saturation-c32,4,571,0
saturation-c32,5,627,0
saturation-c32,6,587,0
saturation-c32,7,619,0
saturation-c32,8,629,0
saturation-c32,9,548,0
saturation-c32,10,51,0
fixed-r1,0,511,0
fixed-r1,1,580,0
fixed-r1,2,659,0
fixed-r1,3,687,0
fixed-r1,4,588,0
fixed-r1,5,675,0
fixed-r1,6,647,0
fixed-r1,7,701,0
fixed-r1,8,690,0
fixed-r1,9,521,0
fixed-r1,10,32,0
fixed-r2,0,452,0
fixed-r2,1,545,0
fixed-r2,2,604,0
fixed-r2,3,652,0
fixed-r2,4,521,0
fixed-r2,5,627,0
fixed-r2,6,571,0
fixed-r2,7,611,0
fixed-r2,8,573,0
fixed-r2,9,586,0
fixed-r2,10,32,0
fixed-r4,0,133,0
fixed-r4,1,276,0
fixed-r4,2,461,0
fixed-r4,3,406,0
fixed-r4,4,503,0
fixed-r4,5,487,0
fixed-r4,6,377,0
fixed-r4,7,427,0
fixed-r4,8,551,0
fixed-r4,9,547,0
fixed-r4,10,50,0
growth-r1,0,527,0
growth-r1,1,596,0
growth-r1,2,604,0
growth-r1,3,616,0
growth-r1,4,516,0
growth-r1,5,508,0
growth-r1,6,606,0
growth-r1,7,620,0
growth-r1,8,628,0
growth-r1,9,591,0
growth-r1,10,32,0
growth-r2,0,461,0
growth-r2,1,662,0
growth-r2,2,670,0
growth-r2,3,655,0
growth-r2,4,640,0
growth-r2,5,495,0
growth-r2,6,635,0
growth-r2,7,626,0
growth-r2,8,598,0
growth-r2,9,609,0
growth-r2,10,32,0
growth-r4,0,106,0
growth-r4,1,514,0
growth-r4,2,587,0
growth-r4,3,506,0
growth-r4,4,423,0
growth-r4,5,409,0
growth-r4,6,459,0
growth-r4,7,462,0
growth-r4,8,618,0
growth-r4,9,549,0
growth-r4,10,55,0
improved-db-cpu-r4,0,492,0
improved-db-cpu-r4,1,583,0
improved-db-cpu-r4,2,629,0
improved-db-cpu-r4,3,681,0
improved-db-cpu-r4,4,667,0
improved-db-cpu-r4,5,632,0
improved-db-cpu-r4,6,585,0
improved-db-cpu-r4,7,677,0
improved-db-cpu-r4,8,602,0
improved-db-cpu-r4,9,629,0
improved-db-cpu-r4,10,52,0
1 phase second successful failed
2 saturation-c1 0 252 0
3 saturation-c1 1 266 0
4 saturation-c1 2 257 0
5 saturation-c1 3 262 0
6 saturation-c1 4 253 0
7 saturation-c1 5 249 0
8 saturation-c1 6 228 0
9 saturation-c1 7 240 0
10 saturation-c1 8 219 0
11 saturation-c1 9 244 0
12 saturation-c1 10 2 0
13 saturation-c2 0 444 0
14 saturation-c2 1 377 0
15 saturation-c2 2 352 0
16 saturation-c2 3 297 0
17 saturation-c2 4 383 0
18 saturation-c2 5 324 0
19 saturation-c2 6 275 0
20 saturation-c2 7 323 0
21 saturation-c2 8 333 0
22 saturation-c2 9 381 0
23 saturation-c2 10 6 0
24 saturation-c4 0 526 0
25 saturation-c4 1 453 0
26 saturation-c4 2 425 0
27 saturation-c4 3 478 0
28 saturation-c4 4 510 0
29 saturation-c4 5 468 0
30 saturation-c4 6 458 0
31 saturation-c4 7 428 0
32 saturation-c4 8 490 0
33 saturation-c4 9 474 0
34 saturation-c4 10 11 0
35 saturation-c8 0 532 0
36 saturation-c8 1 476 0
37 saturation-c8 2 530 0
38 saturation-c8 3 529 0
39 saturation-c8 4 490 0
40 saturation-c8 5 527 0
41 saturation-c8 6 445 0
42 saturation-c8 7 524 0
43 saturation-c8 8 507 0
44 saturation-c8 9 519 0
45 saturation-c8 10 16 0
46 saturation-c16 0 349 0
47 saturation-c16 1 592 0
48 saturation-c16 2 541 0
49 saturation-c16 3 491 0
50 saturation-c16 4 545 0
51 saturation-c16 5 420 0
52 saturation-c16 6 499 0
53 saturation-c16 7 529 0
54 saturation-c16 8 548 0
55 saturation-c16 9 601 0
56 saturation-c16 10 28 0
57 saturation-c32 0 661 0
58 saturation-c32 1 604 0
59 saturation-c32 2 610 0
60 saturation-c32 3 589 0
61 saturation-c32 4 571 0
62 saturation-c32 5 627 0
63 saturation-c32 6 587 0
64 saturation-c32 7 619 0
65 saturation-c32 8 629 0
66 saturation-c32 9 548 0
67 saturation-c32 10 51 0
68 fixed-r1 0 511 0
69 fixed-r1 1 580 0
70 fixed-r1 2 659 0
71 fixed-r1 3 687 0
72 fixed-r1 4 588 0
73 fixed-r1 5 675 0
74 fixed-r1 6 647 0
75 fixed-r1 7 701 0
76 fixed-r1 8 690 0
77 fixed-r1 9 521 0
78 fixed-r1 10 32 0
79 fixed-r2 0 452 0
80 fixed-r2 1 545 0
81 fixed-r2 2 604 0
82 fixed-r2 3 652 0
83 fixed-r2 4 521 0
84 fixed-r2 5 627 0
85 fixed-r2 6 571 0
86 fixed-r2 7 611 0
87 fixed-r2 8 573 0
88 fixed-r2 9 586 0
89 fixed-r2 10 32 0
90 fixed-r4 0 133 0
91 fixed-r4 1 276 0
92 fixed-r4 2 461 0
93 fixed-r4 3 406 0
94 fixed-r4 4 503 0
95 fixed-r4 5 487 0
96 fixed-r4 6 377 0
97 fixed-r4 7 427 0
98 fixed-r4 8 551 0
99 fixed-r4 9 547 0
100 fixed-r4 10 50 0
101 growth-r1 0 527 0
102 growth-r1 1 596 0
103 growth-r1 2 604 0
104 growth-r1 3 616 0
105 growth-r1 4 516 0
106 growth-r1 5 508 0
107 growth-r1 6 606 0
108 growth-r1 7 620 0
109 growth-r1 8 628 0
110 growth-r1 9 591 0
111 growth-r1 10 32 0
112 growth-r2 0 461 0
113 growth-r2 1 662 0
114 growth-r2 2 670 0
115 growth-r2 3 655 0
116 growth-r2 4 640 0
117 growth-r2 5 495 0
118 growth-r2 6 635 0
119 growth-r2 7 626 0
120 growth-r2 8 598 0
121 growth-r2 9 609 0
122 growth-r2 10 32 0
123 growth-r4 0 106 0
124 growth-r4 1 514 0
125 growth-r4 2 587 0
126 growth-r4 3 506 0
127 growth-r4 4 423 0
128 growth-r4 5 409 0
129 growth-r4 6 459 0
130 growth-r4 7 462 0
131 growth-r4 8 618 0
132 growth-r4 9 549 0
133 growth-r4 10 55 0
134 improved-db-cpu-r4 0 492 0
135 improved-db-cpu-r4 1 583 0
136 improved-db-cpu-r4 2 629 0
137 improved-db-cpu-r4 3 681 0
138 improved-db-cpu-r4 4 667 0
139 improved-db-cpu-r4 5 632 0
140 improved-db-cpu-r4 6 585 0
141 improved-db-cpu-r4 7 677 0
142 improved-db-cpu-r4 8 602 0
143 improved-db-cpu-r4 9 629 0
144 improved-db-cpu-r4 10 52 0
+104
View File
@@ -0,0 +1,104 @@
# Lab 3 verification summary
Дата проверки: 2026-10-23.
Файл содержит обезличенную сводку воспроизводимых проверок. Bearer tokens,
пароли, ключи идемпотентности, UUID пользователей/чатов/сообщений и содержимое
локальных Docker secrets намеренно не сохранены.
## Окружение
- Windows + WSL2;
- Docker Engine 29.7.2;
- Docker Compose 5.5.0;
- две Compose-реплики сервиса `api`;
- единственный опубликованный endpoint: HAProxy на `127.0.0.1:8080`;
- Nginx доступен только внутри Compose network и отдаёт статический React;
- PostgreSQL и Redis доступны только внутри Compose network.
## Статические проверки
```text
go test ./... PASS
go test -race ./... PASS
go vet ./... PASS
make check PASS
make validate PASS
docker compose config PASS
shell syntax for hooks PASS
```
`make validate` запускался с Python virtual environment, где установлены
зависимости преподавательского validator.
## Топология и smoke
- migration 1 and migration 2 applied successfully;
- one-shot service `migrate` exited with code 0;
- оба API-контейнера перешли в `healthy`;
- 20 последовательных запросов к health через LB вернули два разных
`X-Instance-Id`: распределение 10/10;
- Windows PowerShell получил HTTP 200 и `X-Instance-Id` с
`http://localhost:8080/health/ready`;
- преподавательский `python3 tests/smoke.py` завершился строкой
`PASS: lab3 public API scenario`.
## Readiness-aware routing
`make test-readiness-routing` добавил в network namespace одной API-реплики
правило, запрещающее TCP-доступ к PostgreSQL, не останавливая сам процесс. Его
`/health/ready` вернул 503; HAProxy исключил backend за 2,861 с. После этого
40 запросов `/health/live` получили 200, а 20 корректных регистраций — 201;
не готовая реплика не получила ни одного запроса. После удаления fault-правила
она вернулась в ротацию. Машиночитаемый результат сохранён в
`evidence/readiness-routing.json`.
## Failover API
Команда:
```bash
make test-failover ACTION_SCRIPT=./scripts/stop-one.sh
```
Наблюдение преподавательского теста:
```text
run 1:
observed instances before action: 2
successful writes / failures: 141 / 0
first recovery: 2.668 seconds
run 2, after restoring the desired two replicas:
observed instances before action: 2
successful writes / failures: 142 / 0
first recovery: 2.653 seconds
both results: PASS
```
После каждого запуска желаемое число реплик было восстановлено командой
`docker compose up -d --wait api`. Hook сопоставляет `TARGET_INSTANCE_ID` с
hostname контейнера и останавливает только выбранную API-реплику. Отдельный
`make grade4-experiment` целенаправленно остановил обе исходные реплики по
очереди: 7853/0 и 7970/0 успешных/ошибочных запросов, recovery 2,893/2,938 с.
## Persistence и идемпотентность
- `make test-persistence ACTION_SCRIPT=./scripts/restart.sh`: PASS; после
рестарта PostgreSQL, Redis, всех API-реплик, frontend и HAProxy прежние bearer session и
созданные данные сохранились;
- 32 конкурентных POST сообщения с одинаковыми semantic payload и
`Idempotency-Key` через HAProxy вернули один Message ID;
- прямой запрос PostgreSQL подтвердил ровно одну строку сообщения;
- повтор с тем же scope/key и другим payload возвращает HTTP 409.
## Негативные и browser-security проверки
- сырой `Authorization: Bearer` с UTF-8 `é` вернул 401, Bearer challenge и
стандартный `Error`; процесс не завершился с panic/500;
- тело JSON из одного байта `FF` вернуло 400 `invalid_request`, а
`error.request_id` совпал с `X-Request-Id`;
- login установил host-only `HttpOnly; SameSite=Strict` cookie;
- cookie без Bearer на контрактном `/api/v1/users/me` дала 401, через
`/web-api/v1/users/me` — 200;
- logout через `/web-api` вернул 204 и инвалидировал серверную сессию;
- статический frontend вернул 200 и `Content-Security-Policy`.
+11
View File
@@ -0,0 +1,11 @@
{
"target_instance": "bd53aadefab0",
"detection_seconds": 2.861,
"health_requests": {
"200": 40
},
"registration_requests": {
"201": 20
},
"recovered": true
}
+3
View File
@@ -0,0 +1,3 @@
node_modules
dist
coverage
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#11110f" />
<meta
name="description"
content="Минималистичный веб-клиент распределённого MTUCI Messenger"
/>
<title>MTUCI Messenger</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1688
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "mtusi-messenger-web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
"build": "tsc -b && vite build",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@tanstack/react-query": "^5.104.5",
"lucide-react": "^1.61.0",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router-dom": "^7.18.4"
},
"devDependencies": {
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.2",
"typescript": "^7.0.2",
"vite": "^8.3.5",
"vitest": "^5.0.5"
}
}
+158
View File
@@ -0,0 +1,158 @@
import type {
ApiErrorBody,
Chat,
CreateChatInput,
LoginInput,
Message,
Page,
RegisterInput,
Session,
User,
} from "./types";
const publicApi = "/api/v1";
const browserApi = "/web-api/v1";
export class ApiError extends Error {
readonly status: number;
readonly code?: string;
readonly requestId?: string;
constructor(status: number, body: ApiErrorBody) {
super(body.error?.message || `HTTP ${status}`);
this.name = "ApiError";
this.status = status;
this.code = body.error?.code;
this.requestId = body.error?.request_id;
}
}
type RequestOptions = Omit<RequestInit, "body"> & {
body?: unknown;
};
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const headers = new Headers(options.headers);
if (options.body !== undefined) {
headers.set("Content-Type", "application/json");
}
const response = await fetch(path, {
...options,
headers,
credentials: "same-origin",
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
if (!response.ok) {
let body: ApiErrorBody = {};
try {
body = (await response.json()) as ApiErrorBody;
} catch {
// Preserve a useful HTTP-level error when a proxy returned non-JSON.
}
throw new ApiError(response.status, body);
}
if (response.status === 204) {
return undefined as T;
}
return (await response.json()) as T;
}
function encodeBasic({ username, password }: LoginInput): string {
const bytes = new TextEncoder().encode(`${username}:${password}`);
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
async function collectPages<T>(path: string): Promise<T[]> {
const items: T[] = [];
let cursor: string | null = null;
for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
const search = new URLSearchParams({ limit: "100" });
if (cursor) {
search.set("cursor", cursor);
}
const page = await request<Page<T>>(`${path}?${search.toString()}`);
items.push(...page.items);
cursor = page.next_cursor;
if (!cursor) {
return items;
}
}
throw new Error("pagination safety limit exceeded");
}
export const api = {
register(input: RegisterInput): Promise<User> {
return request<User>(`${publicApi}/users`, {
method: "POST",
body: {
username: input.username,
display_name: input.displayName,
password: input.password,
},
});
},
login(input: LoginInput): Promise<Session> {
return request<Session>(`${publicApi}/auth/sessions`, {
method: "POST",
headers: {
Authorization: `Basic ${encodeBasic(input)}`,
},
});
},
logout(): Promise<void> {
return request<void>(`${browserApi}/auth/sessions/current`, {
method: "DELETE",
});
},
me(): Promise<User> {
return request<User>(`${browserApi}/users/me`);
},
chats(): Promise<Chat[]> {
return collectPages<Chat>(`${browserApi}/chats`);
},
chat(chatID: string): Promise<Chat> {
return request<Chat>(`${browserApi}/chats/${encodeURIComponent(chatID)}`);
},
createChat(input: CreateChatInput): Promise<Chat> {
return request<Chat>(`${browserApi}/chats`, {
method: "POST",
body: {
title: input.title,
member_ids: input.memberIds,
},
});
},
messages(chatID: string): Promise<Message[]> {
return collectPages<Message>(
`${browserApi}/chats/${encodeURIComponent(chatID)}/messages`,
);
},
sendMessage(chatID: string, text: string, idempotencyKey: string): Promise<Message> {
return request<Message>(
`${browserApi}/chats/${encodeURIComponent(chatID)}/messages`,
{
method: "POST",
headers: {
"Idempotency-Key": idempotencyKey,
},
body: { text },
},
);
},
};
+57
View File
@@ -0,0 +1,57 @@
export type User = {
id: string;
username: string;
display_name: string;
created_at: string;
};
export type Session = {
token: string;
token_type: "Bearer";
expires_at: string;
user: User;
};
export type Chat = {
id: string;
title: string;
member_ids: string[];
created_at: string;
};
export type Message = {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: string;
};
export type Page<T> = {
items: T[];
next_cursor: string | null;
};
export type ApiErrorBody = {
error?: {
code?: string;
message?: string;
request_id?: string;
};
};
export type RegisterInput = {
username: string;
displayName: string;
password: string;
};
export type CreateChatInput = {
title: string;
memberIds: string[];
};
export type LoginInput = {
username: string;
password: string;
};
+51
View File
@@ -0,0 +1,51 @@
import { Navigate, Outlet, Route, Routes, useLocation } from "react-router-dom";
import { useAuth } from "../auth/AuthProvider";
import { LoadingScreen } from "../components/LoadingScreen";
import { AuthPage } from "../pages/AuthPage";
import { MessengerPage } from "../pages/MessengerPage";
function ProtectedRoute() {
const { user, isLoading } = useAuth();
const location = useLocation();
if (isLoading) {
return <LoadingScreen />;
}
if (!user) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
}
return <Outlet />;
}
function PublicOnlyRoute() {
const { user, isLoading } = useAuth();
if (isLoading) {
return <LoadingScreen />;
}
if (user) {
return <Navigate to="/app" replace />;
}
return <Outlet />;
}
export function App() {
return (
<Routes>
<Route element={<PublicOnlyRoute />}>
<Route path="/login" element={<AuthPage initialMode="login" />} />
<Route path="/register" element={<AuthPage initialMode="register" />} />
</Route>
<Route element={<ProtectedRoute />}>
<Route path="/app" element={<MessengerPage />} />
<Route path="/app/chats/:chatId" element={<MessengerPage />} />
<Route path="/app/profile" element={<MessengerPage profileOpen />} />
</Route>
<Route path="/" element={<Navigate to="/app" replace />} />
<Route path="*" element={<Navigate to="/app" replace />} />
</Routes>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 540 KiB

+90
View File
@@ -0,0 +1,90 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
createContext,
useCallback,
useContext,
type PropsWithChildren,
} from "react";
import { api, ApiError } from "../api/client";
import type { LoginInput, RegisterInput, User } from "../api/types";
type AuthContextValue = {
user: User | null;
isLoading: boolean;
login: (input: LoginInput) => Promise<void>;
register: (input: RegisterInput) => Promise<void>;
logout: () => Promise<void>;
};
const AuthContext = createContext<AuthContextValue | null>(null);
const meQueryKey = ["current-user"] as const;
async function loadCurrentUser(): Promise<User | null> {
try {
return await api.me();
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
return null;
}
throw error;
}
}
export function AuthProvider({ children }: PropsWithChildren) {
const queryClient = useQueryClient();
const meQuery = useQuery({
queryKey: meQueryKey,
queryFn: loadCurrentUser,
retry: false,
staleTime: 30_000,
});
const login = useCallback(
async (input: LoginInput) => {
const session = await api.login(input);
queryClient.setQueryData(meQueryKey, session.user);
},
[queryClient],
);
const register = useCallback(
async (input: RegisterInput) => {
await api.register(input);
const session = await api.login({
username: input.username,
password: input.password,
});
queryClient.setQueryData(meQueryKey, session.user);
},
[queryClient],
);
const logout = useCallback(async () => {
await api.logout();
queryClient.setQueryData(meQueryKey, null);
queryClient.removeQueries({ queryKey: ["chats"] });
}, [queryClient]);
return (
<AuthContext.Provider
value={{
user: meQuery.data ?? null,
isLoading: meQuery.isLoading,
login,
register,
logout,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthContextValue {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within AuthProvider");
}
return context;
}
+26
View File
@@ -0,0 +1,26 @@
import { initials } from "../lib/format";
type AvatarProps = {
label: string;
seed?: string;
size?: "small" | "medium" | "large";
};
function tone(seed: string): number {
let hash = 0;
for (const character of seed) {
hash = (hash * 31 + character.codePointAt(0)!) >>> 0;
}
return hash % 5;
}
export function Avatar({ label, seed = label, size = "medium" }: AvatarProps) {
return (
<span
aria-hidden="true"
className={`avatar avatar--${size} avatar--tone-${tone(seed)}`}
>
{initials(label)}
</span>
);
}
+121
View File
@@ -0,0 +1,121 @@
import { MessageSquarePlus, Search, UsersRound, X } from "lucide-react";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { Chat, User } from "../api/types";
import { formatMemberCount } from "../lib/format";
import { Avatar } from "./Avatar";
type ChatListProps = {
chats: Chat[];
currentUser: User;
error: boolean;
isLoading: boolean;
selectedChatID?: string;
onCreateChat: () => void;
};
export function ChatList({
chats,
currentUser,
error,
isLoading,
selectedChatID,
onCreateChat,
}: ChatListProps) {
const navigate = useNavigate();
const [search, setSearch] = useState("");
const filteredChats = useMemo(() => {
const normalized = search.trim().toLocaleLowerCase("ru");
if (!normalized) {
return chats;
}
return chats.filter((chat) =>
chat.title.toLocaleLowerCase("ru").includes(normalized),
);
}, [chats, search]);
return (
<aside className="chat-sidebar">
<header className="chat-sidebar__header">
<div>
<p className="eyebrow">Сообщения</p>
<h1>Чаты</h1>
</div>
<button
aria-label="Создать чат"
className="soft-icon-button"
onClick={onCreateChat}
type="button"
>
<MessageSquarePlus aria-hidden="true" />
</button>
</header>
<div className="search-box">
<Search aria-hidden="true" />
<input
aria-label="Поиск чатов"
onChange={(event) => setSearch(event.target.value)}
placeholder="Поиск"
value={search}
/>
{search && (
<button aria-label="Очистить поиск" onClick={() => setSearch("")} type="button">
<X aria-hidden="true" />
</button>
)}
</div>
<div className="chat-list" aria-live="polite">
{isLoading && (
<div className="sidebar-state">
<span className="loading-line" />
<p>Загружаем чаты…</p>
</div>
)}
{error && (
<div className="sidebar-state sidebar-state--error">
<p>Не удалось загрузить список чатов.</p>
</div>
)}
{!isLoading && !error && filteredChats.length === 0 && (
<div className="sidebar-state">
<UsersRound aria-hidden="true" />
<p>{search ? "Ничего не найдено" : "У вас пока нет чатов"}</p>
{!search && (
<button className="text-button" onClick={onCreateChat} type="button">
Создать первый
</button>
)}
</div>
)}
{filteredChats.map((chat) => (
<button
className={`chat-row ${selectedChatID === chat.id ? "chat-row--active" : ""}`}
key={chat.id}
onClick={() => navigate(`/app/chats/${chat.id}`)}
type="button"
>
<Avatar label={chat.title} seed={chat.id} />
<span className="chat-row__body">
<strong>{chat.title}</strong>
<small>{formatMemberCount(chat.member_ids.length)}</small>
</span>
{chat.member_ids.includes(currentUser.id) && (
<span className="chat-row__status" title="Вы участник">
•
</span>
)}
</button>
))}
</div>
<footer className="sidebar-footer">
<span className="status-dot" />
API подключён
</footer>
</aside>
);
}
+236
View File
@@ -0,0 +1,236 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
ArrowLeft,
CheckCheck,
RefreshCcw,
Send,
ShieldCheck,
UsersRound,
} from "lucide-react";
import {
useEffect,
useMemo,
useRef,
useState,
type FormEvent,
type KeyboardEvent,
} from "react";
import { api } from "../api/client";
import type { Chat, Message, User } from "../api/types";
import {
dayKey,
formatDay,
formatMemberCount,
formatMessageTime,
shortID,
} from "../lib/format";
import { createIdempotencyKey } from "../lib/idempotency";
import { Avatar } from "./Avatar";
type ChatViewProps = {
chat: Chat;
currentUser: User;
onBack: () => void;
};
type SendEnvelope = {
text: string;
idempotencyKey: string;
};
export function ChatView({ chat, currentUser, onBack }: ChatViewProps) {
const queryClient = useQueryClient();
const messagesEnd = useRef<HTMLDivElement>(null);
const [draft, setDraft] = useState("");
const [failedEnvelope, setFailedEnvelope] = useState<SendEnvelope | null>(null);
const messagesQuery = useQuery({
queryKey: ["messages", chat.id],
queryFn: () => api.messages(chat.id),
refetchInterval: 3_000,
staleTime: 1_000,
});
const messages = messagesQuery.data ?? [];
useEffect(() => {
messagesEnd.current?.scrollIntoView({
behavior: messages.length > 1 ? "smooth" : "auto",
block: "end",
});
}, [chat.id, messages.length]);
const mutation = useMutation({
mutationFn: (envelope: SendEnvelope) =>
api.sendMessage(chat.id, envelope.text, envelope.idempotencyKey),
onSuccess: (message) => {
setFailedEnvelope(null);
queryClient.setQueryData<Message[]>(
["messages", chat.id],
(current = []) => {
if (current.some((item) => item.id === message.id)) {
return current;
}
return [...current, message];
},
);
},
onError: (_error, envelope) => {
setFailedEnvelope(envelope);
},
});
const groups = useMemo(() => {
const result: Array<{ key: string; label: string; messages: Message[] }> = [];
for (const message of messages) {
const key = dayKey(message.created_at);
const current = result.at(-1);
if (!current || current.key !== key) {
result.push({
key,
label: formatDay(message.created_at),
messages: [message],
});
} else {
current.messages.push(message);
}
}
return result;
}, [messages]);
function send(envelope: SendEnvelope) {
if (!mutation.isPending) {
mutation.mutate(envelope);
}
}
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const text = draft.trim();
if (!text || Array.from(text).length > 4_000) {
return;
}
const envelope = { text, idempotencyKey: createIdempotencyKey() };
setDraft("");
setFailedEnvelope(null);
send(envelope);
}
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
event.currentTarget.form?.requestSubmit();
}
}
return (
<section className="conversation">
<header className="conversation-header">
<button
aria-label="Назад к списку чатов"
className="mobile-back-button"
onClick={onBack}
type="button"
>
<ArrowLeft aria-hidden="true" />
</button>
<Avatar label={chat.title} seed={chat.id} size="small" />
<div className="conversation-header__title">
<strong>{chat.title}</strong>
<span>{formatMemberCount(chat.member_ids.length)}</span>
</div>
<div className="conversation-header__security">
<ShieldCheck aria-hidden="true" />
<span>сессия защищена</span>
</div>
</header>
<div className="message-canvas">
<div className="message-canvas__shade" />
<div className="message-stream" aria-live="polite">
{messagesQuery.isLoading && (
<div className="floating-state">
<span className="loading-line" />
Загружаем историю
</div>
)}
{messagesQuery.isError && (
<div className="floating-state floating-state--error">
<p>История временно недоступна</p>
<button onClick={() => messagesQuery.refetch()} type="button">
<RefreshCcw aria-hidden="true" /> Повторить
</button>
</div>
)}
{!messagesQuery.isLoading && !messagesQuery.isError && messages.length === 0 && (
<div className="floating-state">
<UsersRound aria-hidden="true" />
<p>Сообщений пока нет. Начните разговор.</p>
</div>
)}
{groups.map((group) => (
<div className="message-day" key={group.key}>
<div className="date-divider"><span>{group.label}</span></div>
{group.messages.map((message) => {
const own = message.sender_id === currentUser.id;
return (
<article
className={`message-bubble ${own ? "message-bubble--own" : ""}`}
key={message.id}
>
<span className="message-bubble__sender">
{own ? "Вы" : shortID(message.sender_id)}
</span>
<p>{message.text}</p>
<span className="message-bubble__meta">
{formatMessageTime(message.created_at)}
{own && <CheckCheck aria-label="Доставлено серверу" />}
</span>
</article>
);
})}
</div>
))}
<div ref={messagesEnd} />
</div>
</div>
<footer className="composer">
{failedEnvelope && (
<div className="send-error" role="alert">
<span>Отправка не подтверждена.</span>
<button onClick={() => send(failedEnvelope)} type="button">
Повторить с тем же ключом
</button>
</div>
)}
<form onSubmit={submit}>
<textarea
aria-label="Текст сообщения"
maxLength={4_000}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleKeyDown}
placeholder="Сообщение…"
rows={1}
value={draft}
/>
<span className="composer__counter">
{draft.length > 3_600 ? `${Array.from(draft).length}/4000` : ""}
</span>
<button
aria-label="Отправить"
className="send-button"
disabled={!draft.trim() || mutation.isPending}
type="submit"
>
<Send aria-hidden="true" />
</button>
</form>
</footer>
</section>
);
}
@@ -0,0 +1,148 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, UserRoundPlus, X } from "lucide-react";
import { useEffect, useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { api, ApiError } from "../api/client";
import type { Chat, User } from "../api/types";
import { shortID } from "../lib/format";
type CreateChatDialogProps = {
currentUser: User;
onClose: () => void;
};
const uuidPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function CreateChatDialog({
currentUser,
onClose,
}: CreateChatDialogProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [title, setTitle] = useState("");
const [memberInput, setMemberInput] = useState("");
const [validationError, setValidationError] = useState("");
useEffect(() => {
function closeOnEscape(event: KeyboardEvent) {
if (event.key === "Escape") {
onClose();
}
}
window.addEventListener("keydown", closeOnEscape);
return () => window.removeEventListener("keydown", closeOnEscape);
}, [onClose]);
const mutation = useMutation({
mutationFn: api.createChat,
onSuccess: (chat) => {
queryClient.setQueryData<Chat[]>(["chats"], (current = []) => [
...current,
chat,
]);
onClose();
navigate(`/app/chats/${chat.id}`);
},
});
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setValidationError("");
const enteredIDs = memberInput
.split(/[\s,;]+/)
.map((value) => value.trim())
.filter(Boolean);
const memberIds = Array.from(new Set([currentUser.id, ...enteredIDs]));
if (!title.trim() || Array.from(title.trim()).length > 100) {
setValidationError("Название должно содержать от 1 до 100 символов");
return;
}
const invalidID = enteredIDs.find((id) => !uuidPattern.test(id));
if (invalidID) {
setValidationError(`Некорректный UUID: ${invalidID}`);
return;
}
mutation.mutate({ title: title.trim(), memberIds });
}
const serverError =
mutation.error instanceof ApiError
? mutation.error.message
: mutation.error
? "Не удалось создать чат"
: "";
return (
<div className="dialog-backdrop" onMouseDown={onClose}>
<section
aria-labelledby="create-chat-title"
aria-modal="true"
className="dialog-card"
onMouseDown={(event) => event.stopPropagation()}
role="dialog"
>
<header className="dialog-card__header">
<div>
<p className="eyebrow">Новый разговор</p>
<h2 id="create-chat-title">Создать чат</h2>
</div>
<button
aria-label="Закрыть"
className="soft-icon-button"
onClick={onClose}
type="button"
>
<X aria-hidden="true" />
</button>
</header>
<form className="dialog-form" onSubmit={submit}>
<label>
<span>Название</span>
<div className="input-shell">
<Plus aria-hidden="true" />
<input
autoFocus
maxLength={100}
onChange={(event) => setTitle(event.target.value)}
placeholder="Например, Команда проекта"
required
value={title}
/>
</div>
</label>
<label>
<span>UUID участников</span>
<div className="textarea-shell">
<UserRoundPlus aria-hidden="true" />
<textarea
onChange={(event) => setMemberInput(event.target.value)}
placeholder="Вставьте UUID через пробел, запятую или с новой строки"
rows={4}
value={memberInput}
/>
</div>
<small>
Ваш ID добавлен автоматически: <code>{shortID(currentUser.id)}</code>
</small>
</label>
{(validationError || serverError) && (
<div className="form-error" role="alert">
{validationError || serverError}
</div>
)}
<button className="primary-button" disabled={mutation.isPending} type="submit">
{mutation.isPending ? "Создаём…" : "Создать чат"}
</button>
</form>
</section>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { MessageSquarePlus } from "lucide-react";
type EmptyChatProps = {
hasChats: boolean;
onCreateChat: () => void;
};
export function EmptyChat({ hasChats, onCreateChat }: EmptyChatProps) {
return (
<section className="conversation conversation--empty">
<div className="empty-chat-card">
<span className="empty-chat-card__line" />
<p className="eyebrow">MTUCI Messenger</p>
<h2>{hasChats ? "Выберите чат" : "Начните разговор"}</h2>
<p>
{hasChats
? "История и новые сообщения появятся здесь."
: "Создайте первый чат и пригласите участников по UUID."}
</p>
{!hasChats && (
<button className="primary-button" onClick={onCreateChat} type="button">
<MessageSquarePlus aria-hidden="true" />
Создать чат
</button>
)}
</div>
</section>
);
}
+11
View File
@@ -0,0 +1,11 @@
export function LoadingScreen() {
return (
<main className="loading-screen" aria-live="polite">
<div className="brand-mark brand-mark--large" aria-hidden="true">
M
</div>
<p>Подключаемся к Messenger</p>
<span className="loading-line" />
</main>
);
}
@@ -0,0 +1,42 @@
import { MessagesSquare, UserRound } from "lucide-react";
import { Link } from "react-router-dom";
import type { User } from "../api/types";
import { Avatar } from "./Avatar";
type NavigationRailProps = {
user: User;
profileOpen: boolean;
};
export function NavigationRail({ user, profileOpen }: NavigationRailProps) {
return (
<nav className="navigation-rail" aria-label="Основная навигация">
<Link className="rail-brand" to="/app" aria-label="MTUCI Messenger">
M
</Link>
<div className="rail-actions">
<Link
className={`rail-action ${profileOpen ? "" : "rail-action--active"}`}
to="/app"
>
<MessagesSquare aria-hidden="true" />
<span>Чаты</span>
</Link>
<Link
className={`rail-action ${profileOpen ? "rail-action--active" : ""}`}
to="/app/profile"
>
<UserRound aria-hidden="true" />
<span>Профиль</span>
</Link>
</div>
<Link className="rail-profile" to="/app/profile" aria-label="Открыть профиль">
<Avatar label={user.display_name} seed={user.id} size="small" />
<span className="presence-dot" />
</Link>
</nav>
);
}
+123
View File
@@ -0,0 +1,123 @@
import {
CalendarDays,
Check,
Copy,
LogOut,
ShieldCheck,
UserRound,
X,
} from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import type { User } from "../api/types";
import { useAuth } from "../auth/AuthProvider";
import { Avatar } from "./Avatar";
type ProfileDrawerProps = {
user: User;
};
const createdAtFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
});
export function ProfileDrawer({ user }: ProfileDrawerProps) {
const { logout } = useAuth();
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const [error, setError] = useState("");
const [isLoggingOut, setIsLoggingOut] = useState(false);
async function copyID() {
await navigator.clipboard.writeText(user.id);
setCopied(true);
window.setTimeout(() => setCopied(false), 1800);
}
async function submitLogout() {
setError("");
setIsLoggingOut(true);
try {
await logout();
navigate("/login", { replace: true });
} catch {
setError("Не удалось завершить сессию. Попробуйте ещё раз.");
setIsLoggingOut(false);
}
}
return (
<>
<button
aria-label="Закрыть профиль"
className="drawer-backdrop"
onClick={() => navigate("/app")}
type="button"
/>
<aside className="profile-drawer" aria-label="Профиль пользователя">
<header className="profile-drawer__header">
<p className="eyebrow">Ваш аккаунт</p>
<button
aria-label="Закрыть"
className="soft-icon-button"
onClick={() => navigate("/app")}
type="button"
>
<X aria-hidden="true" />
</button>
</header>
<div className="profile-identity">
<Avatar label={user.display_name} seed={user.id} size="large" />
<h2>{user.display_name}</h2>
<p>@{user.username}</p>
<span className="profile-badge">
<ShieldCheck aria-hidden="true" />
серверная сессия
</span>
</div>
<dl className="profile-details">
<div>
<dt><UserRound aria-hidden="true" /> ID аккаунта</dt>
<dd>
<code>{user.id}</code>
<button
aria-label="Скопировать ID"
className="copy-button"
onClick={copyID}
type="button"
>
{copied ? <Check /> : <Copy />}
</button>
</dd>
</div>
<div>
<dt><CalendarDays aria-hidden="true" /> Дата регистрации</dt>
<dd>{createdAtFormatter.format(new Date(user.created_at))}</dd>
</div>
</dl>
<div className="profile-roadmap">
<strong>Следующие версии</strong>
<p>Аватар, редактирование имени и смена пароля появятся после API-контрактов.</p>
</div>
{error && <div className="form-error" role="alert">{error}</div>}
<button
className="logout-button"
disabled={isLoggingOut}
onClick={submitLogout}
type="button"
>
<LogOut aria-hidden="true" />
{isLoggingOut ? "Завершаем…" : "Выйти из аккаунта"}
</button>
</aside>
</>
);
}
+58
View File
@@ -0,0 +1,58 @@
const timeFormatter = new Intl.DateTimeFormat("ru-RU", {
hour: "2-digit",
minute: "2-digit",
});
const dayFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
});
const fullDateFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
});
export function formatMessageTime(value: string): string {
return timeFormatter.format(new Date(value));
}
export function formatDay(value: string): string {
const date = new Date(value);
const now = new Date();
const sameYear = date.getFullYear() === now.getFullYear();
return (sameYear ? dayFormatter : fullDateFormatter).format(date);
}
export function dayKey(value: string): string {
const date = new Date(value);
return [date.getFullYear(), date.getMonth(), date.getDate()].join("-");
}
export function formatMemberCount(count: number): string {
const mod10 = count % 10;
const mod100 = count % 100;
if (mod10 === 1 && mod100 !== 11) {
return `${count} участник`;
}
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) {
return `${count} участника`;
}
return `${count} участников`;
}
export function shortID(id: string): string {
return id.length > 12 ? `${id.slice(0, 8)}…` : id;
}
export function initials(value: string): string {
const parts = value.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) {
return "?";
}
return parts
.slice(0, 2)
.map((part) => Array.from(part)[0]?.toUpperCase() ?? "")
.join("");
}
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it, vi } from "vitest";
import { createIdempotencyKey } from "./idempotency";
describe("createIdempotencyKey", () => {
it("creates an API-compatible unique key", () => {
vi.stubGlobal("crypto", {
randomUUID: () => "12345678-1234-1234-1234-123456789abc",
});
const key = createIdempotencyKey();
expect(key).toMatch(/^[A-Za-z0-9._:-]{1,128}$/);
expect(key).toContain("12345678123412341234123456789abc");
expect(key.length).toBeLessThanOrEqual(128);
vi.unstubAllGlobals();
});
});
+4
View File
@@ -0,0 +1,4 @@
export function createIdempotencyKey(): string {
const random = crypto.randomUUID().replaceAll("-", "");
return `web-${Date.now().toString(36)}-${random}`;
}
+32
View File
@@ -0,0 +1,32 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { App } from "./app/App";
import { AuthProvider } from "./auth/AuthProvider";
import "./styles.css";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: true,
},
mutations: {
retry: false,
},
},
});
createRoot(document.getElementById("root")!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
</QueryClientProvider>
</StrictMode>,
);
+190
View File
@@ -0,0 +1,190 @@
import {
ArrowRight,
Eye,
EyeOff,
LockKeyhole,
MessageCircleMore,
UserRound,
} from "lucide-react";
import { useState, type FormEvent } from "react";
import { Link, useNavigate } from "react-router-dom";
import { ApiError } from "../api/client";
import { useAuth } from "../auth/AuthProvider";
type AuthMode = "login" | "register";
type AuthPageProps = {
initialMode: AuthMode;
};
function errorMessage(error: unknown): string {
if (error instanceof ApiError) {
if (error.status === 401) {
return "Неверный логин или пароль";
}
if (error.status === 409) {
return "Такой username уже занят";
}
return error.message;
}
return "Не удалось связаться с сервером. Попробуйте ещё раз.";
}
export function AuthPage({ initialMode }: AuthPageProps) {
const { login, register } = useAuth();
const navigate = useNavigate();
const [username, setUsername] = useState("");
const [displayName, setDisplayName] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const isRegister = initialMode === "register";
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError("");
if (!/^[a-z0-9_]{3,32}$/.test(username)) {
setError("Username: 3–32 символа, только a–z, цифры и _");
return;
}
if (isRegister && displayName.trim().length === 0) {
setError("Укажите отображаемое имя");
return;
}
if (password.length < 12 || Array.from(password).length > 128) {
setError("Пароль должен содержать от 12 до 128 символов");
return;
}
setIsSubmitting(true);
try {
if (isRegister) {
await register({ username, displayName: displayName.trim(), password });
} else {
await login({ username, password });
}
navigate("/app", { replace: true });
} catch (submitError) {
setError(errorMessage(submitError));
} finally {
setIsSubmitting(false);
}
}
return (
<main className="auth-page">
<section className="auth-story" aria-label="О приложении">
<div className="auth-brand">
<div className="brand-mark" aria-hidden="true">
M
</div>
<span>MTUCI Messenger</span>
</div>
<div className="auth-copy">
<p className="eyebrow">Распределённый мессенджер</p>
<h1>Разговоры, которые остаются с вами.</h1>
<p>
Минималистичный клиент поверх отказоустойчивого Go API. Одна сессия,
несколько реплик, никаких лишних отвлечений.
</p>
<div className="auth-status">
<span className="status-dot" />
защищённая серверная сессия
</div>
</div>
</section>
<section className="auth-panel">
<div className="auth-card">
<MessageCircleMore className="auth-card__icon" aria-hidden="true" />
<p className="eyebrow">{isRegister ? "Новый аккаунт" : "С возвращением"}</p>
<h2>{isRegister ? "Создать профиль" : "Войти в Messenger"}</h2>
<p className="auth-card__lead">
{isRegister
? "Данные профиля можно будет расширить в следующих версиях."
: "Продолжите общение с того места, где остановились."}
</p>
<form className="auth-form" onSubmit={submit}>
{isRegister && (
<label>
<span>Отображаемое имя</span>
<div className="input-shell">
<UserRound aria-hidden="true" />
<input
autoComplete="name"
maxLength={100}
onChange={(event) => setDisplayName(event.target.value)}
placeholder="Как к вам обращаться"
required
value={displayName}
/>
</div>
</label>
)}
<label>
<span>Username</span>
<div className="input-shell">
<UserRound aria-hidden="true" />
<input
autoCapitalize="none"
autoComplete="username"
maxLength={32}
onChange={(event) => setUsername(event.target.value.toLowerCase())}
placeholder="username"
required
value={username}
/>
</div>
</label>
<label>
<span>Пароль</span>
<div className="input-shell">
<LockKeyhole aria-hidden="true" />
<input
autoComplete={isRegister ? "new-password" : "current-password"}
maxLength={128}
minLength={12}
onChange={(event) => setPassword(event.target.value)}
placeholder="Минимум 12 символов"
required
type={showPassword ? "text" : "password"}
value={password}
/>
<button
aria-label={showPassword ? "Скрыть пароль" : "Показать пароль"}
className="icon-button"
onClick={() => setShowPassword((value) => !value)}
type="button"
>
{showPassword ? <EyeOff /> : <Eye />}
</button>
</div>
</label>
{error && <div className="form-error" role="alert">{error}</div>}
<button className="primary-button" disabled={isSubmitting} type="submit">
<span>{isSubmitting ? "Подождите…" : isRegister ? "Создать аккаунт" : "Войти"}</span>
{!isSubmitting && <ArrowRight aria-hidden="true" />}
</button>
</form>
<p className="auth-switch">
{isRegister ? "Уже есть аккаунт?" : "Впервые здесь?"}{" "}
<Link to={isRegister ? "/login" : "/register"}>
{isRegister ? "Войти" : "Создать профиль"}
</Link>
</p>
</div>
</section>
</main>
);
}
+81
View File
@@ -0,0 +1,81 @@
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { api } from "../api/client";
import { useAuth } from "../auth/AuthProvider";
import { ChatList } from "../components/ChatList";
import { ChatView } from "../components/ChatView";
import { CreateChatDialog } from "../components/CreateChatDialog";
import { EmptyChat } from "../components/EmptyChat";
import { NavigationRail } from "../components/NavigationRail";
import { ProfileDrawer } from "../components/ProfileDrawer";
type MessengerPageProps = {
profileOpen?: boolean;
};
export function MessengerPage({ profileOpen = false }: MessengerPageProps) {
const { user } = useAuth();
const { chatId } = useParams();
const navigate = useNavigate();
const [createChatOpen, setCreateChatOpen] = useState(false);
const chatsQuery = useQuery({
queryKey: ["chats"],
queryFn: api.chats,
refetchInterval: 10_000,
staleTime: 5_000,
});
if (!user) {
return null;
}
const chats = chatsQuery.data ?? [];
const selectedChat = chatId
? chats.find((chat) => chat.id === chatId)
: undefined;
return (
<main
className={[
"messenger-shell",
chatId ? "messenger-shell--chat-open" : "",
profileOpen ? "messenger-shell--drawer-open" : "",
].join(" ")}
>
<NavigationRail profileOpen={profileOpen} user={user} />
<ChatList
chats={chats}
currentUser={user}
error={chatsQuery.isError}
isLoading={chatsQuery.isLoading}
onCreateChat={() => setCreateChatOpen(true)}
selectedChatID={chatId}
/>
{selectedChat ? (
<ChatView
chat={selectedChat}
currentUser={user}
onBack={() => navigate("/app")}
/>
) : (
<EmptyChat
hasChats={chats.length > 0}
onCreateChat={() => setCreateChatOpen(true)}
/>
)}
{profileOpen && <ProfileDrawer user={user} />}
{createChatOpen && (
<CreateChatDialog
currentUser={user}
onClose={() => setCreateChatOpen(false)}
/>
)}
</main>
);
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true
},
"include": ["vite.config.ts"]
}
+23
View File
@@ -0,0 +1,23 @@
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
strictPort: true,
proxy: {
"/api": "http://localhost:8080",
"/web-api": "http://localhost:8080",
"/health": "http://localhost:8080",
},
},
preview: {
port: 4173,
strictPort: true,
},
test: {
environment: "node",
include: ["src/**/*.test.ts"],
},
});
+21
View File
@@ -0,0 +1,21 @@
module mtusi2026lab3
go 1.27.1
require (
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.11.0
github.com/redis/go-redis/v9 v9.23.0
golang.org/x/crypto v0.57.0
)
require (
github.com/cespare/xxhash/v2 v2.3.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
go.uber.org/atomic v1.12.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
)
+43
View File
@@ -0,0 +1,43 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.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/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
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.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
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/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+7
View File
@@ -0,0 +1,7 @@
FROM haproxy:3.2-alpine@sha256:dfba86f031bd4c9039f10f8cc5de75991d1b6766d5460f0335b980408503baad
COPY infrastructure/haproxy/haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
USER haproxy
EXPOSE 8080
+66
View File
@@ -0,0 +1,66 @@
global
log stdout format raw local0
maxconn 2048
defaults
log global
mode http
option httplog
timeout connect 1s
timeout client 30s
timeout server 30s
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold other 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
frontend public
bind :8080
acl api_request path_beg /api/ /web-api/ /health/
acl web_api path_beg /web-api/
acl has_session req.cook(mtusi_session) -m found
acl message_create method POST
acl message_path path_reg ^/(api|web-api)/v1/chats/[^/]+/messages$
http-request del-header Authorization if web_api
http-request set-header Authorization "Bearer %[req.cook(mtusi_session)]" if web_api has_session
http-request del-header Cookie if api_request
http-request replace-path ^/web-api/(.*)$ /api/\1 if web_api
use_backend message_backend if message_create message_path
use_backend api_backend if api_request
default_backend frontend_backend
backend api_backend
balance leastconn
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker init-addr libc,none
server-template api 8 api:8080
backend message_backend
balance leastconn
option httpchk
option redispatch
option http-buffer-request
retries 3
retry-on conn-failure empty-response response-timeout 502 503 504
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker init-addr libc,none
server-template api 8 api:8080
backend frontend_backend
option httpchk GET /
http-check expect status 200
server frontend frontend:8080 check inter 2s fall 2 rise 2 resolvers docker init-addr libc,none
+15
View File
@@ -0,0 +1,15 @@
FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS frontend-build
WORKDIR /frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm test && npm run build
FROM nginx:1.30.6-alpine@sha256:970364228b1e4f932abc22d321932816782cca8a20b85a77552a7cfe9acfb3b5
COPY infrastructure/nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=frontend-build /frontend/dist /usr/share/nginx/html
EXPOSE 8080
+32
View File
@@ -0,0 +1,32 @@
worker_processes auto;
events {
worker_connections 512;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
listen 8080;
server_name _;
root /usr/share/nginx/html;
index index.html;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer" always;
add_header X-Frame-Options "DENY" always;
add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
location /assets/ {
try_files $uri =404;
expires 1y;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
}
}
+99
View File
@@ -0,0 +1,99 @@
package cache
import (
"context"
"errors"
"log"
"mtusi2026lab3/internal/adapter/redis"
"mtusi2026lab3/internal/application"
"mtusi2026lab3/internal/domain"
)
// CachedRepository декорирует основной Repository. Все операции, кроме чтения
// и создания чата, автоматически делегируются встроенному Repository.
type CachedRepository struct {
application.Repository
chatCache redis.ChatCache
logger *log.Logger
}
func NewCachedRepository(
repository application.Repository,
chatCache redis.ChatCache,
logger *log.Logger,
) *CachedRepository {
if logger == nil {
logger = log.Default()
}
return &CachedRepository{
Repository: repository,
chatCache: chatCache,
logger: logger,
}
}
func (r *CachedRepository) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
chat, err := r.Repository.CreateChat(ctx, title, memberIDs)
if err != nil {
return domain.Chat{}, err
}
// Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не
// должна превращать успешную бизнес-операцию в 503.
if err = r.chatCache.Set(ctx, chat); err != nil {
r.logger.Printf("[WARN] Redis chat cache write failed: %v", err)
}
return chat, nil
}
func (r *CachedRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
chat, err := r.chatCache.Get(ctx, chatID)
if err == nil {
if !containsMember(chat.MemberIDs, callerID) {
return domain.Chat{}, domain.ErrNotFound
}
return chat, nil
}
shouldFillCache := errors.Is(err, redis.ErrMiss)
if !shouldFillCache {
r.logger.Printf("[WARN] Redis chat cache read failed: %v", err)
}
chat, err = r.Repository.GetChatByID(ctx, chatID, callerID)
if err != nil {
return domain.Chat{}, err
}
if shouldFillCache {
if err = r.chatCache.Set(ctx, chat); err != nil {
r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err)
}
}
return chat, nil
}
func containsMember(memberIDs []string, callerID string) bool {
for _, memberID := range memberIDs {
if memberID == callerID {
return true
}
}
return false
}
var _ application.Repository = (*CachedRepository)(nil)
+183
View File
@@ -0,0 +1,183 @@
package cache
import (
"context"
"errors"
"io"
"log"
"testing"
"mtusi2026lab3/internal/adapter/memory"
"mtusi2026lab3/internal/adapter/redis"
"mtusi2026lab3/internal/application"
"mtusi2026lab3/internal/domain"
)
type fakeChatCache struct {
chats map[string]domain.Chat
getErr error
setErr error
sets int
}
func (c *fakeChatCache) Get(
_ context.Context,
chatID string,
) (domain.Chat, error) {
if c.getErr != nil {
return domain.Chat{}, c.getErr
}
chat, exists := c.chats[chatID]
if !exists {
return domain.Chat{}, redis.ErrMiss
}
return chat, nil
}
func (c *fakeChatCache) Set(
_ context.Context,
chat domain.Chat,
) error {
c.sets++
if c.setErr != nil {
return c.setErr
}
c.chats[chat.ID] = chat
return nil
}
type countingRepository struct {
application.Repository
getChatCalls int
}
func (r *countingRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
r.getChatCalls++
return r.Repository.GetChatByID(ctx, chatID, callerID)
}
func cachedRepositoryFixture(
t *testing.T,
) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) {
t.Helper()
legacy := memory.NewMemoryStore()
member, err := legacy.CreateUser("cache_member", "Участник")
if err != nil {
t.Fatalf("create member: %v", err)
}
outsider, err := legacy.CreateUser("cache_outsider", "Посторонний")
if err != nil {
t.Fatalf("create outsider: %v", err)
}
chat, err := legacy.CreateChat("Кешируемый чат", []string{member.ID})
if err != nil {
t.Fatalf("create chat: %v", err)
}
repository := &countingRepository{
Repository: memory.NewMemoryRepository(legacy),
}
chatCache := &fakeChatCache{
chats: make(map[string]domain.Chat),
}
return repository, chatCache, member, outsider, chat
}
func TestCachedRepositoryMissThenHit(t *testing.T) {
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
first, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("first read: %v", err)
}
second, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("second read: %v", err)
}
if repository.getChatCalls != 1 {
t.Fatalf("expected one source read, got %d", repository.getChatCalls)
}
if chatCache.sets != 1 {
t.Fatalf("expected one cache fill, got %d", chatCache.sets)
}
if first.ID != expected.ID || second.ID != expected.ID {
t.Fatal("cache changed chat identity")
}
}
func TestCachedRepositoryFallsBackWhenCacheUnavailable(t *testing.T) {
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
chatCache.getErr = errors.New("redis unavailable")
chatCache.setErr = errors.New("redis unavailable")
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
chat, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("fallback read: %v", err)
}
if chat.ID != expected.ID || repository.getChatCalls != 1 {
t.Fatal("source repository was not used after cache failure")
}
if chatCache.sets != 0 {
t.Fatal("failed cache read must not trigger another cache operation")
}
}
func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) {
repository, chatCache, _, outsider, expected := cachedRepositoryFixture(t)
chatCache.chats[expected.ID] = expected
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
_, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID)
if !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("expected ErrNotFound for outsider, got %v", err)
}
if repository.getChatCalls != 0 {
t.Fatal("cache hit unexpectedly queried source repository")
}
}
func TestCachedRepositoryIgnoresWriteFailure(t *testing.T) {
repository, chatCache, member, _, _ := cachedRepositoryFixture(t)
chatCache.setErr = errors.New("redis unavailable")
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
chat, err := cached.CreateChat(
context.Background(),
"Новый чат",
[]string{member.ID},
)
if err != nil {
t.Fatalf("create chat with unavailable cache: %v", err)
}
if chat.ID == "" || chatCache.sets != 1 {
t.Fatal("chat was not created before best-effort cache write")
}
}
+8
View File
@@ -0,0 +1,8 @@
package memory
import "mtusi2026lab3/internal/domain"
var (
ErrNotFound = domain.ErrNotFound
ErrConflict = domain.ErrConflict
)
+295
View File
@@ -0,0 +1,295 @@
package memory
import (
"context"
"fmt"
"sync"
"time"
"mtusi2026lab3/internal/application"
"mtusi2026lab3/internal/domain"
)
type memorySession struct {
userID string
expiresAt time.Time
}
type memoryIdempotencyScope struct {
actorID string
method string
canonicalPath string
key string
}
type memoryIdempotencyResult struct {
requestHash [32]byte
message domain.Message
expiresAt time.Time
}
type MemoryRepository struct {
legacy *MemoryStore
mu sync.RWMutex
passwordByUserID map[string]string
userIDByUsername map[string]string
sessionsByHashKey map[[32]byte]memorySession
idempotencyByScope map[memoryIdempotencyScope]memoryIdempotencyResult
}
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
return &MemoryRepository{
legacy: legacy,
passwordByUserID: make(map[string]string),
userIDByUsername: make(map[string]string),
sessionsByHashKey: make(map[[32]byte]memorySession),
idempotencyByScope: make(map[memoryIdempotencyScope]memoryIdempotencyResult),
}
}
func (r *MemoryRepository) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
user, err := r.legacy.CreateUser(username, displayName)
if err != nil {
return domain.User{}, err
}
r.mu.Lock()
r.passwordByUserID[user.ID] = passwordHash
r.userIDByUsername[user.Username] = user.ID
r.mu.Unlock()
return user, nil
}
func (r *MemoryRepository) GetUserByID(
ctx context.Context,
userID string,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
return r.legacy.GetUserByID(userID)
}
func (r *MemoryRepository) GetUserByUsername(
ctx context.Context,
username string,
) (domain.User, string, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, "", err
}
r.mu.RLock()
userID, exists := r.userIDByUsername[username]
passwordHash := r.passwordByUserID[userID]
r.mu.RUnlock()
if !exists {
return domain.User{}, "", ErrNotFound
}
user, err := r.legacy.GetUserByID(userID)
if err != nil {
return domain.User{}, "", err
}
return user, passwordHash, nil
}
func (r *MemoryRepository) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
if err := ctx.Err(); err != nil {
return domain.Chat{}, err
}
return r.legacy.CreateChat(title, memberIDs)
}
func (r *MemoryRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
if err := ctx.Err(); err != nil {
return domain.Chat{}, err
}
return r.legacy.GetChatByID(chatID, callerID)
}
func (r *MemoryRepository) GetChatsForUser(
ctx context.Context,
userID string,
limit int,
cursor *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
if err := ctx.Err(); err != nil {
return nil, false, err
}
return r.legacy.GetChatsForUser(userID, limit, cursor)
}
func (r *MemoryRepository) CreateMessageIdempotently(
ctx context.Context,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
if err := ctx.Err(); err != nil {
return domain.Message{}, err
}
scope := memoryIdempotencyScope{
actorID: write.ActorID,
method: write.Method,
canonicalPath: write.CanonicalPath,
key: write.Key,
}
now := time.Now().UTC()
r.mu.Lock()
defer r.mu.Unlock()
if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil {
return domain.Message{}, err
}
if stored, exists := r.idempotencyByScope[scope]; exists {
if stored.expiresAt.After(now) {
if stored.requestHash != write.RequestHash {
return domain.Message{}, application.ErrIdempotencyConflict
}
return stored.message, nil
}
delete(r.idempotencyByScope, scope)
}
message, err := r.legacy.CreateMessage(write.ChatID, write.ActorID, write.Text)
if err != nil {
return domain.Message{}, err
}
r.idempotencyByScope[scope] = memoryIdempotencyResult{
requestHash: write.RequestHash,
message: message,
expiresAt: now.Add(write.TTL),
}
return message, nil
}
func (r *MemoryRepository) GetMessages(
ctx context.Context,
chatID string,
callerID string,
limit int,
cursor *domain.MessageCursor,
) ([]domain.Message, bool, error) {
if err := ctx.Err(); err != nil {
return nil, false, err
}
return r.legacy.GetMessages(
chatID,
callerID,
limit,
cursor,
)
}
func (r *MemoryRepository) CreateSession(
ctx context.Context,
tokenHash []byte,
userID string,
expiresAt time.Time,
) error {
if err := ctx.Err(); err != nil {
return err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return err
}
r.mu.Lock()
r.sessionsByHashKey[key] = memorySession{
userID: userID,
expiresAt: expiresAt,
}
r.mu.Unlock()
return nil
}
func (r *MemoryRepository) GetUserBySession(
ctx context.Context,
tokenHash []byte,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return domain.User{}, ErrNotFound
}
r.mu.RLock()
session, exists := r.sessionsByHashKey[key]
r.mu.RUnlock()
if !exists || !session.expiresAt.After(time.Now().UTC()) {
return domain.User{}, ErrNotFound
}
return r.legacy.GetUserByID(session.userID)
}
func (r *MemoryRepository) DeleteSession(
ctx context.Context,
tokenHash []byte,
) error {
if err := ctx.Err(); err != nil {
return err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return err
}
r.mu.Lock()
delete(r.sessionsByHashKey, key)
r.mu.Unlock()
return nil
}
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
var key [32]byte
if len(tokenHash) != len(key) {
return key, fmt.Errorf(
"session token hash must contain %d bytes",
len(key),
)
}
copy(key[:], tokenHash)
return key, nil
}
var _ application.Repository = (*MemoryRepository)(nil)
+287
View File
@@ -0,0 +1,287 @@
package memory
import (
"fmt"
"sort"
"sync"
"time"
"mtusi2026lab3/internal/domain"
"github.com/google/uuid"
)
type MemoryStore struct {
mu sync.RWMutex
usersByID map[string]domain.User //key = user UUID
usersByUsername map[string]string //key = username для быстрой проверки уникальности
chatsByID map[string]domain.Chat //key = chat UUID
messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{
usersByID: make(map[string]domain.User),
usersByUsername: make(map[string]string),
chatsByID: make(map[string]domain.Chat),
messagesByChatID: make(map[string][]domain.Message),
}
}
// ---пользователи---
func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) {
s.mu.Lock()
defer s.mu.Unlock()
// дубликат username -> 409 Conflict
if _, exists := s.usersByUsername[username]; exists {
return domain.User{}, ErrConflict
}
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
CreatedAt: time.Now().UTC(),
}
s.usersByID[user.ID] = user
s.usersByUsername[user.Username] = user.ID
return user, nil
}
func (s *MemoryStore) GetUserByID(id string) (domain.User, error) {
s.mu.RLock()
defer s.mu.RUnlock()
user, exists := s.usersByID[id]
if !exists {
return domain.User{}, ErrNotFound
}
return user, nil
}
// ---чаты---
func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) {
s.mu.Lock()
defer s.mu.Unlock()
//все участники рил существуют
for _, memberID := range memberIDs {
if _, exists := s.usersByID[memberID]; !exists {
return domain.Chat{}, fmt.Errorf(
"%w: member %s",
ErrNotFound,
memberID,
)
}
}
chat := domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции
CreatedAt: time.Now().UTC(),
}
s.chatsByID[chat.ID] = chat
s.messagesByChatID[chat.ID] = make([]domain.Message, 0)
return chat, nil
}
func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return domain.Chat{}, ErrNotFound
}
// Требование безопасности: посторонний получает 404, а не 403
isMember := false
for _, m := range chat.MemberIDs {
if m == callerID {
isMember = true
break
}
}
if !isMember {
return domain.Chat{}, ErrNotFound
}
return chat, nil
}
func (s *MemoryStore) GetChatsForUser(
userID string,
limit int,
cursorData *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chats := make([]domain.Chat, 0)
for _, chat := range s.chatsByID {
for _, memberID := range chat.MemberIDs {
if memberID == userID {
chats = append(chats, chat)
break
}
}
}
sort.Slice(chats, func(i, j int) bool {
if chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
return chats[i].ID < chats[j].ID
}
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
})
start := 0
if cursorData != nil {
start = sort.Search(len(chats), func(index int) bool {
chat := chats[index]
if chat.CreatedAt.After(cursorData.CreatedAt) {
return true
}
return chat.CreatedAt.Equal(cursorData.CreatedAt) &&
chat.ID > cursorData.ChatID
})
}
if start >= len(chats) {
return make([]domain.Chat, 0), false, nil
}
end := start + limit
if end > len(chats) {
end = len(chats)
}
items := make([]domain.Chat, end-start)
copy(items, chats[start:end])
return items, end < len(chats), nil
}
// ---Сообщения---
func (s *MemoryStore) CreateMessage(
chatID, senderID, text string,
) (domain.Message, error) {
messageID := uuid.NewString()
s.mu.Lock()
defer s.mu.Unlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return domain.Message{}, ErrNotFound
}
isMember := false
for _, memberID := range chat.MemberIDs {
if memberID == senderID {
isMember = true
break
}
}
if !isMember {
return domain.Message{}, ErrNotFound
}
createdAt := time.Now().UTC()
messages := s.messagesByChatID[chatID]
if len(messages) > 0 {
lastCreatedAt := messages[len(messages)-1].CreatedAt
// Обеспечиваем строго возрастающее время внутри каждого чата.
if !createdAt.After(lastCreatedAt) {
createdAt = lastCreatedAt.Add(time.Nanosecond)
}
}
message := domain.Message{
ID: messageID,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: createdAt,
}
s.messagesByChatID[chatID] = append(messages, message)
return message, nil
}
func (s *MemoryStore) GetMessages(
chatID, callerID string,
limit int,
cursorData *domain.MessageCursor,
) ([]domain.Message, bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return nil, false, ErrNotFound
}
isMember := false
for _, memberID := range chat.MemberIDs {
if memberID == callerID {
isMember = true
break
}
}
if !isMember {
return nil, false, ErrNotFound
}
messages := s.messagesByChatID[chatID]
start := 0
if cursorData != nil {
// Срез уже упорядочен во время записи, поэтому вместо
// полного прохода используем бинарный поиск.
start = sort.Search(len(messages), func(index int) bool {
message := messages[index]
if message.CreatedAt.After(cursorData.CreatedAt) {
return true
}
return message.CreatedAt.Equal(cursorData.CreatedAt) &&
message.ID > cursorData.MessageID
})
}
if start >= len(messages) {
return make([]domain.Message, 0), false, nil
}
end := len(messages)
if limit > 0 && end-start > limit {
end = start + limit
}
// копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез
items := make([]domain.Message, end-start)
copy(items, messages[start:end])
return items, end < len(messages), nil
}
+278
View File
@@ -0,0 +1,278 @@
package postgres
import (
"context"
"errors"
"fmt"
"mtusi2026lab3/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
transaction, err := s.pool.Begin(queryContext)
if err != nil {
return domain.Chat{}, fmt.Errorf(
"begin create chat transaction: %w",
err,
)
}
defer func() {
_ = transaction.Rollback(queryContext)
}()
chat := domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
}
err = transaction.QueryRow(
queryContext,
`
INSERT INTO chats (
id,
title
)
VALUES ($1, $2)
RETURNING created_at
`,
chat.ID,
chat.Title,
).Scan(&chat.CreatedAt)
if err != nil {
return domain.Chat{}, fmt.Errorf("insert chat: %w", err)
}
for position, memberID := range memberIDs {
commandTag, insertErr := transaction.Exec(
queryContext,
`
INSERT INTO chat_members (
chat_id,
user_id,
position
)
SELECT
$1,
id,
$3
FROM users
WHERE id = $2
`,
chat.ID,
memberID,
position,
)
if insertErr != nil {
return domain.Chat{}, fmt.Errorf(
"insert chat member %s: %w",
memberID,
insertErr,
)
}
// INSERT ... SELECT не вставляет строку, если пользователя нет.
// Возврат из функции активирует deferred Rollback: уже созданные
// chat и предыдущие membership-строки не останутся в базе.
if commandTag.RowsAffected() != 1 {
return domain.Chat{}, fmt.Errorf(
"%w: member %s",
ErrNotFound,
memberID,
)
}
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Chat{}, fmt.Errorf(
"commit create chat transaction: %w",
err,
)
}
return chat, nil
}
func (s *PostgreSQLStore) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var chat domain.Chat
err := s.pool.QueryRow(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chats AS chat
JOIN chat_members AS caller
ON caller.chat_id = chat.id
AND caller.user_id = $2
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE chat.id = $1
GROUP BY
chat.id,
chat.title,
chat.created_at
`,
chatID,
callerID,
).Scan(
&chat.ID,
&chat.Title,
&chat.CreatedAt,
&chat.MemberIDs,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Chat{}, ErrNotFound
}
if err != nil {
return domain.Chat{}, fmt.Errorf("select chat by id: %w", err)
}
return chat, nil
}
func (s *PostgreSQLStore) GetChatsForUser(
ctx context.Context,
userID string,
limit int,
cursor *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var (
rows pgx.Rows
err error
)
if cursor == nil {
rows, err = s.pool.Query(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chat_members AS own_membership
JOIN chats AS chat
ON chat.id = own_membership.chat_id
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE own_membership.user_id = $1
GROUP BY
chat.id,
chat.title,
chat.created_at
ORDER BY
chat.created_at,
chat.id
LIMIT $2
`,
userID,
limit+1,
)
} else {
rows, err = s.pool.Query(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chat_members AS own_membership
JOIN chats AS chat
ON chat.id = own_membership.chat_id
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE own_membership.user_id = $1
AND (chat.created_at, chat.id) > ($2, $3)
GROUP BY
chat.id,
chat.title,
chat.created_at
ORDER BY
chat.created_at,
chat.id
LIMIT $4
`,
userID,
cursor.CreatedAt,
cursor.ChatID,
limit+1,
)
}
if err != nil {
return nil, false, fmt.Errorf(
"query chats for user: %w",
err,
)
}
defer rows.Close()
items := make([]domain.Chat, 0, limit+1)
for rows.Next() {
var chat domain.Chat
if err := rows.Scan(
&chat.ID,
&chat.Title,
&chat.CreatedAt,
&chat.MemberIDs,
); err != nil {
return nil, false, fmt.Errorf(
"scan chat page: %w",
err,
)
}
items = append(items, chat)
}
if err := rows.Err(); err != nil {
return nil, false, fmt.Errorf(
"iterate chat page: %w",
err,
)
}
hasMore := len(items) > limit
if hasMore {
items = items[:limit]
}
return items, hasMore, nil
}
+5
View File
@@ -0,0 +1,5 @@
package postgres
import "mtusi2026lab3/internal/application"
var _ application.Repository = (*PostgreSQLStore)(nil)
+8
View File
@@ -0,0 +1,8 @@
package postgres
import "mtusi2026lab3/internal/domain"
var (
ErrNotFound = domain.ErrNotFound
ErrConflict = domain.ErrConflict
)
+321
View File
@@ -0,0 +1,321 @@
package postgres
import (
"bytes"
"context"
"errors"
"fmt"
"time"
"mtusi2026lab3/internal/application"
"mtusi2026lab3/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateMessageIdempotently(
ctx context.Context,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
if err != nil {
return domain.Message{}, fmt.Errorf("begin idempotent message transaction: %w", err)
}
defer func() { _ = transaction.Rollback(queryContext) }()
var isMember bool
err = transaction.QueryRow(
queryContext,
`
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
`,
write.ChatID,
write.ActorID,
).Scan(&isMember)
if err != nil {
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
}
if !isMember {
return domain.Message{}, ErrNotFound
}
_, err = transaction.Exec(
queryContext,
`
DELETE FROM message_idempotency
WHERE user_id = $1
AND method = $2
AND canonical_path = $3
AND idempotency_key = $4
AND expires_at <= CURRENT_TIMESTAMP
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
)
if err != nil {
return domain.Message{}, fmt.Errorf("delete expired idempotency key: %w", err)
}
message := domain.Message{
ID: uuid.NewString(),
ChatID: write.ChatID,
SenderID: write.ActorID,
Text: write.Text,
}
var storedHash []byte
var storedMessageID string
err = transaction.QueryRow(
queryContext,
`
INSERT INTO message_idempotency (
user_id,
method,
canonical_path,
idempotency_key,
request_hash,
message_id,
expires_at
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
CURRENT_TIMESTAMP + $7 * INTERVAL '1 second'
)
ON CONFLICT DO NOTHING
RETURNING request_hash, message_id::text
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
write.RequestHash[:],
message.ID,
int64(write.TTL/time.Second),
).Scan(&storedHash, &storedMessageID)
if errors.Is(err, pgx.ErrNoRows) {
err = transaction.QueryRow(
queryContext,
`
SELECT request_hash, message_id::text
FROM message_idempotency
WHERE user_id = $1
AND method = $2
AND canonical_path = $3
AND idempotency_key = $4
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
).Scan(&storedHash, &storedMessageID)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotency result: %w", err)
}
if !bytes.Equal(storedHash, write.RequestHash[:]) {
return domain.Message{}, application.ErrIdempotencyConflict
}
err = transaction.QueryRow(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at
FROM messages
WHERE id = $1
`,
storedMessageID,
).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotency replay: %w", err)
}
return message, nil
}
if err != nil {
return domain.Message{}, fmt.Errorf("claim idempotency key: %w", err)
}
err = transaction.QueryRow(
queryContext,
`
INSERT INTO messages (
id,
chat_id,
sender_id,
text
)
VALUES ($1, $2, $3, $4)
RETURNING created_at
`,
message.ID,
message.ChatID,
message.SenderID,
message.Text,
).Scan(&message.CreatedAt)
if err != nil {
return domain.Message{}, fmt.Errorf("insert message: %w", err)
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
}
return message, nil
}
func (s *PostgreSQLStore) GetMessages(
ctx context.Context,
chatID string,
callerID string,
limit int,
cursor *domain.MessageCursor,
) ([]domain.Message, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var isMember bool
err := s.pool.QueryRow(
queryContext,
`
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
`,
chatID,
callerID,
).Scan(&isMember)
if err != nil {
return nil, false, fmt.Errorf(
"check chat membership: %w",
err,
)
}
if !isMember {
return nil, false, ErrNotFound
}
var rows pgx.Rows
if cursor == nil {
rows, err = s.pool.Query(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at
FROM messages
WHERE chat_id = $1
ORDER BY
created_at,
id
LIMIT $2
`,
chatID,
limit+1,
)
} else {
rows, err = s.pool.Query(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at
FROM messages
WHERE chat_id = $1
AND (created_at, id) > ($2, $3)
ORDER BY
created_at,
id
LIMIT $4
`,
chatID,
cursor.CreatedAt,
cursor.MessageID,
limit+1,
)
}
if err != nil {
return nil, false, fmt.Errorf(
"query messages: %w",
err,
)
}
defer rows.Close()
items := make([]domain.Message, 0, limit+1)
for rows.Next() {
var message domain.Message
if err := rows.Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
); err != nil {
return nil, false, fmt.Errorf(
"scan message page: %w",
err,
)
}
items = append(items, message)
}
if err := rows.Err(); err != nil {
return nil, false, fmt.Errorf(
"iterate message page: %w",
err,
)
}
hasMore := len(items) > limit
if hasMore {
items = items[:limit]
}
return items, hasMore, nil
}
+108
View File
@@ -0,0 +1,108 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"mtusi2026lab3/internal/domain"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateSession(
ctx context.Context,
tokenHash []byte,
userID string,
expiresAt time.Time,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(
queryContext,
`
INSERT INTO sessions (
token_hash,
user_id,
expires_at
)
VALUES ($1, $2, $3)
`,
tokenHash,
userID,
expiresAt,
)
if err != nil {
return fmt.Errorf("insert session: %w", err)
}
return nil
}
func (s *PostgreSQLStore) GetUserBySession(
ctx context.Context,
tokenHash []byte,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var user domain.User
err := s.pool.QueryRow(
queryContext,
`
SELECT
app_user.id::text,
app_user.username,
app_user.display_name,
app_user.created_at
FROM sessions AS session
JOIN users AS app_user
ON app_user.id = session.user_id
WHERE session.token_hash = $1
AND session.expires_at > CURRENT_TIMESTAMP
`,
tokenHash,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, ErrNotFound
}
if err != nil {
return domain.User{}, fmt.Errorf(
"select user by session: %w",
err,
)
}
return user, nil
}
func (s *PostgreSQLStore) DeleteSession(
ctx context.Context,
tokenHash []byte,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(
queryContext,
`
DELETE FROM sessions
WHERE token_hash = $1
`,
tokenHash,
)
if err != nil {
return fmt.Errorf("delete session: %w", err)
}
return nil
}
+40
View File
@@ -0,0 +1,40 @@
package postgres
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type PostgreSQLStore struct {
pool *pgxpool.Pool
queryTimeout time.Duration
}
func NewPostgreSQLStore(
pool *pgxpool.Pool,
queryTimeout time.Duration,
) *PostgreSQLStore {
return &PostgreSQLStore{
pool: pool,
queryTimeout: queryTimeout,
}
}
func (s *PostgreSQLStore) Ping(ctx context.Context) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
return s.pool.Ping(queryContext)
}
func (s *PostgreSQLStore) Close() {
s.pool.Close()
}
func (s *PostgreSQLStore) withTimeout(
ctx context.Context,
) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, s.queryTimeout)
}
+144
View File
@@ -0,0 +1,144 @@
package postgres
import (
"context"
"errors"
"fmt"
"mtusi2026lab3/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func (s *PostgreSQLStore) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
}
err := s.pool.QueryRow(
queryContext,
`
INSERT INTO users (
id,
username,
display_name,
password_hash
)
VALUES ($1, $2, $3, $4)
RETURNING created_at
`,
user.ID,
user.Username,
user.DisplayName,
passwordHash,
).Scan(&user.CreatedAt)
if err == nil {
return user, nil
}
var postgresError *pgconn.PgError
if errors.As(err, &postgresError) &&
postgresError.Code == "23505" &&
postgresError.ConstraintName == "users_username_unique" {
return domain.User{}, ErrConflict
}
return domain.User{}, fmt.Errorf("insert user: %w", err)
}
func (s *PostgreSQLStore) GetUserByID(
ctx context.Context,
userID string,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var user domain.User
err := s.pool.QueryRow(
queryContext,
`
SELECT
id::text,
username,
display_name,
created_at
FROM users
WHERE id = $1
`,
userID,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, ErrNotFound
}
if err != nil {
return domain.User{}, fmt.Errorf("select user by id: %w", err)
}
return user, nil
}
func (s *PostgreSQLStore) GetUserByUsername(
ctx context.Context,
username string,
) (domain.User, string, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var (
user domain.User
passwordHash string
)
err := s.pool.QueryRow(
queryContext,
`
SELECT
id::text,
username,
display_name,
created_at,
password_hash
FROM users
WHERE username = $1
`,
username,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
&passwordHash,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, "", ErrNotFound
}
if err != nil {
return domain.User{}, "", fmt.Errorf(
"select user by username: %w",
err,
)
}
return user, passwordHash, nil
}
+175
View File
@@ -0,0 +1,175 @@
package redis
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"mtusi2026lab3/internal/domain"
"github.com/google/uuid"
goredis "github.com/redis/go-redis/v9"
)
const chatKeyPrefix = "chat:v2:"
var ErrMiss = errors.New("cache miss")
// ChatCache хранит только производную копию неизменяемых данных чата.
// PostgreSQL остаётся источником истины.
type ChatCache interface {
Get(ctx context.Context, chatID string) (domain.Chat, error)
Set(ctx context.Context, chat domain.Chat) error
}
type RedisChatCache struct {
client *goredis.Client
ttl time.Duration
operationTimeout time.Duration
}
func NewRedisChatCache(
redisURL string,
ttl time.Duration,
operationTimeout time.Duration,
poolSize int,
) (*RedisChatCache, error) {
options, err := goredis.ParseURL(strings.TrimSpace(redisURL))
if err != nil {
return nil, fmt.Errorf("parse Redis URL: %w", err)
}
options.DialTimeout = operationTimeout
options.ReadTimeout = operationTimeout
options.WriteTimeout = operationTimeout
options.PoolTimeout = operationTimeout
options.PoolSize = poolSize
options.MaxRetries = -1
return &RedisChatCache{
client: goredis.NewClient(options),
ttl: ttl,
operationTimeout: operationTimeout,
}, nil
}
func (c *RedisChatCache) Ping(ctx context.Context) error {
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
if err := c.client.Ping(operationContext).Err(); err != nil {
return fmt.Errorf("ping Redis: %w", err)
}
return nil
}
func (c *RedisChatCache) Close() error {
return c.client.Close()
}
func (c *RedisChatCache) Get(
ctx context.Context,
chatID string,
) (domain.Chat, error) {
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
payload, err := c.client.Get(
operationContext,
chatKey(chatID),
).Bytes()
if errors.Is(err, goredis.Nil) {
return domain.Chat{}, ErrMiss
}
if err != nil {
return domain.Chat{}, fmt.Errorf("get cached chat: %w", err)
}
var chat domain.Chat
if err = json.Unmarshal(payload, &chat); err != nil {
c.deleteInvalidValue(operationContext, chatID)
return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err)
}
if err = validateCachedChat(chat, chatID); err != nil {
c.deleteInvalidValue(operationContext, chatID)
return domain.Chat{}, err
}
return chat, nil
}
func (c *RedisChatCache) Set(
ctx context.Context,
chat domain.Chat,
) error {
payload, err := json.Marshal(chat)
if err != nil {
return fmt.Errorf("encode chat for cache: %w", err)
}
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
if err = c.client.Set(
operationContext,
chatKey(chat.ID),
payload,
c.ttl,
).Err(); err != nil {
return fmt.Errorf("cache chat: %w", err)
}
return nil
}
func (c *RedisChatCache) withTimeout(
ctx context.Context,
) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, c.operationTimeout)
}
func (c *RedisChatCache) deleteInvalidValue(
ctx context.Context,
chatID string,
) {
_ = c.client.Del(ctx, chatKey(chatID)).Err()
}
func chatKey(chatID string) string {
return chatKeyPrefix + chatID
}
func validateCachedChat(chat domain.Chat, expectedID string) error {
if chat.ID != expectedID {
return errors.New("cached chat id does not match cache key")
}
if _, err := uuid.Parse(chat.ID); err != nil {
return errors.New("cached chat contains invalid id")
}
if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() {
return errors.New("cached chat is incomplete")
}
if len(chat.MemberIDs) == 0 {
return errors.New("cached chat has no members")
}
seenMembers := make(map[string]struct{}, len(chat.MemberIDs))
for _, memberID := range chat.MemberIDs {
if _, err := uuid.Parse(memberID); err != nil {
return errors.New("cached chat contains invalid member id")
}
if _, exists := seenMembers[memberID]; exists {
return errors.New("cached chat contains duplicate member id")
}
seenMembers[memberID] = struct{}{}
}
return nil
}
var _ ChatCache = (*RedisChatCache)(nil)
+55
View File
@@ -0,0 +1,55 @@
package application
import (
"context"
"fmt"
"mtusi2026lab3/internal/domain"
)
func (s *Service) CreateChat(ctx context.Context, command CreateChatCommand) (domain.Chat, error) {
if err := domain.ValidateChatInput(command.Title, command.MemberIDs, command.ActorID); err != nil {
return domain.Chat{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
return s.repository.CreateChat(ctx, command.Title, command.MemberIDs)
}
func (s *Service) GetChat(ctx context.Context, actorID, chatID string) (domain.Chat, error) {
return s.repository.GetChatByID(ctx, chatID, actorID)
}
func (s *Service) ListChats(
ctx context.Context,
actorID string,
limit int,
cursorToken string,
) (domain.ChatPage, error) {
var cursor *domain.ChatCursor
if cursorToken != "" {
decoded, err := s.cursors.DecodeChat(cursorToken, actorID)
if err != nil {
return domain.ChatPage{}, ErrInvalidCursor
}
cursor = decoded
}
items, hasMore, err := s.repository.GetChatsForUser(ctx, actorID, limit, cursor)
if err != nil {
return domain.ChatPage{}, err
}
page := domain.ChatPage{Items: items}
if page.Items == nil {
page.Items = make([]domain.Chat, 0)
}
if hasMore {
last := page.Items[len(page.Items)-1]
next, encodeErr := s.cursors.EncodeChat(domain.ChatCursor{
CreatedAt: last.CreatedAt, ChatID: last.ID, UserID: actorID,
})
if encodeErr != nil {
return domain.ChatPage{}, encodeErr
}
page.NextCursor = &next
}
return page, nil
}
+27
View File
@@ -0,0 +1,27 @@
package application
type CreateUserCommand struct {
Username string
DisplayName string
Password string
}
type CreateSessionCommand struct {
Username string
Password string
}
type CreateChatCommand struct {
ActorID string
Title string
MemberIDs []string
}
type SendMessageCommand struct {
ActorID string
ChatID string
Text string
Method string
CanonicalPath string
IdempotencyKey string
}
+121
View File
@@ -0,0 +1,121 @@
package application
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"time"
"mtusi2026lab3/internal/domain"
"github.com/google/uuid"
)
const cursorVersion = 1
type CursorCodec struct {
key []byte
}
type cursorPayload struct {
Version int `json:"v"`
Kind string `json:"kind"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
ScopeID string `json:"scope_id"`
}
func NewCursorCodec(key string) (*CursorCodec, error) {
if len(key) < 32 {
return nil, fmt.Errorf("cursor signing key must contain at least 32 bytes")
}
return &CursorCodec{key: []byte(key)}, nil
}
func (c *CursorCodec) EncodeChat(cursor domain.ChatCursor) (string, error) {
return c.encode(cursorPayload{
Version: cursorVersion, Kind: "chat", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: cursor.ChatID, ScopeID: cursor.UserID,
})
}
func (c *CursorCodec) DecodeChat(token, expectedUserID string) (*domain.ChatCursor, error) {
payload, err := c.decode(token, "chat", expectedUserID)
if err != nil {
return nil, err
}
return &domain.ChatCursor{CreatedAt: payload.createdAt, ChatID: payload.id, UserID: payload.scopeID}, nil
}
func (c *CursorCodec) EncodeMessage(cursor domain.MessageCursor) (string, error) {
return c.encode(cursorPayload{
Version: cursorVersion, Kind: "message", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: cursor.MessageID, ScopeID: cursor.ChatID,
})
}
func (c *CursorCodec) DecodeMessage(token, expectedChatID string) (*domain.MessageCursor, error) {
payload, err := c.decode(token, "message", expectedChatID)
if err != nil {
return nil, err
}
return &domain.MessageCursor{CreatedAt: payload.createdAt, MessageID: payload.id, ChatID: payload.scopeID}, nil
}
func (c *CursorCodec) encode(payload cursorPayload) (string, error) {
encodedPayload, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("encode cursor payload: %w", err)
}
mac := hmac.New(sha256.New, c.key)
_, _ = mac.Write(encodedPayload)
return base64.RawURLEncoding.EncodeToString(encodedPayload) + "." +
base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
}
type decodedCursor struct {
createdAt time.Time
id string
scopeID string
}
func (c *CursorCodec) decode(token, expectedKind, expectedScopeID string) (decodedCursor, error) {
parts := strings.Split(token, ".")
if len(parts) != 2 {
return decodedCursor{}, ErrInvalidCursor
}
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
mac := hmac.New(sha256.New, c.key)
_, _ = mac.Write(payloadBytes)
if !hmac.Equal(signature, mac.Sum(nil)) {
return decodedCursor{}, ErrInvalidCursor
}
var payload cursorPayload
if err = json.Unmarshal(payloadBytes, &payload); err != nil ||
payload.Version != cursorVersion || payload.Kind != expectedKind ||
payload.ScopeID != expectedScopeID {
return decodedCursor{}, ErrInvalidCursor
}
createdAt, err := time.Parse(time.RFC3339Nano, payload.CreatedAt)
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
if _, err = uuid.Parse(payload.ID); err != nil {
return decodedCursor{}, ErrInvalidCursor
}
if _, err = uuid.Parse(payload.ScopeID); err != nil {
return decodedCursor{}, ErrInvalidCursor
}
return decodedCursor{createdAt: createdAt.UTC(), id: payload.ID, scopeID: payload.ScopeID}, nil
}
+70
View File
@@ -0,0 +1,70 @@
package application
import (
"errors"
"testing"
"time"
"mtusi2026lab3/internal/domain"
)
const cursorTestKey = "cursor-test-key-with-more-than-thirty-two-bytes"
func TestCursorCodecRoundTrip(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
expected := domain.MessageCursor{
CreatedAt: time.Date(2026, 10, 18, 12, 30, 0, 123, time.UTC),
MessageID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
ChatID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
}
token, err := codec.EncodeMessage(expected)
if err != nil {
t.Fatal(err)
}
actual, err := codec.DecodeMessage(token, expected.ChatID)
if err != nil {
t.Fatal(err)
}
if *actual != expected {
t.Fatalf("cursor changed after round trip: got %#v, want %#v", *actual, expected)
}
}
func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
token, err := codec.EncodeChat(domain.ChatCursor{
CreatedAt: time.Now().UTC(),
ChatID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
UserID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
})
if err != nil {
t.Fatal(err)
}
replacement := "A"
if token[len(token)-1:] == replacement {
replacement = "B"
}
tampered := token[:len(token)-1] + replacement
if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err)
}
if _, err = codec.DecodeChat(token, "e6ca4af0-69ed-4784-8ce0-ee035299fe08"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("wrong scope: got %v, want ErrInvalidCursor", err)
}
if _, err = codec.DecodeMessage(token, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("wrong cursor kind: got %v, want ErrInvalidCursor", err)
}
}
func TestCursorCodecRequiresStrongSharedKey(t *testing.T) {
if _, err := NewCursorCodec("too-short"); err == nil {
t.Fatal("expected short cursor signing key to be rejected")
}
}
+11
View File
@@ -0,0 +1,11 @@
package application
import "errors"
var (
ErrInvalidCursor = errors.New("invalid cursor")
ErrInvalidCredentials = errors.New("invalid credentials")
ErrInvalidInput = errors.New("invalid input")
ErrCredentialState = errors.New("invalid stored credential state")
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
)
+77
View File
@@ -0,0 +1,77 @@
package application
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"mtusi2026lab3/internal/domain"
)
type canonicalMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
if err := domain.ValidateMessageText(command.Text); err != nil {
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
canonicalBody, err := json.Marshal(canonicalMessageRequest{
Text: command.Text,
AttachmentIDs: make([]string, 0),
})
if err != nil {
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
}
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
ActorID: command.ActorID,
ChatID: command.ChatID,
Text: command.Text,
Method: command.Method,
CanonicalPath: command.CanonicalPath,
Key: command.IdempotencyKey,
RequestHash: sha256.Sum256(canonicalBody),
TTL: s.idempotencyTTL,
})
}
func (s *Service) ListMessages(
ctx context.Context,
actorID string,
chatID string,
limit int,
cursorToken string,
) (domain.MessagePage, error) {
var cursor *domain.MessageCursor
if cursorToken != "" {
decoded, err := s.cursors.DecodeMessage(cursorToken, chatID)
if err != nil {
return domain.MessagePage{}, ErrInvalidCursor
}
cursor = decoded
}
items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor)
if err != nil {
return domain.MessagePage{}, err
}
page := domain.MessagePage{Items: items}
if page.Items == nil {
page.Items = make([]domain.Message, 0)
}
if hasMore {
last := page.Items[len(page.Items)-1]
next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{
CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID,
})
if encodeErr != nil {
return domain.MessagePage{}, encodeErr
}
page.NextCursor = &next
}
return page, nil
}
+48
View File
@@ -0,0 +1,48 @@
package application
import (
"context"
"time"
"mtusi2026lab3/internal/domain"
)
type UserRepository interface {
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
}
type SessionRepository interface {
CreateSession(ctx context.Context, tokenHash []byte, userID string, expiresAt time.Time) error
GetUserBySession(ctx context.Context, tokenHash []byte) (domain.User, error)
DeleteSession(ctx context.Context, tokenHash []byte) error
}
type ChatRepository interface {
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
GetChatByID(ctx context.Context, chatID, callerID string) (domain.Chat, error)
GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error)
}
type IdempotentMessageWrite struct {
ActorID string
ChatID string
Text string
Method string
CanonicalPath string
Key string
RequestHash [32]byte
TTL time.Duration
}
type MessageRepository interface {
CreateMessageIdempotently(ctx context.Context, write IdempotentMessageWrite) (domain.Message, error)
GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error)
}
type Repository interface {
UserRepository
SessionRepository
ChatRepository
MessageRepository
}
+53
View File
@@ -0,0 +1,53 @@
package application
import (
"fmt"
"time"
)
const MinimumIdempotencyTTL = 24 * time.Hour
type ServiceOption func(*Service) error
type Service struct {
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
}
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
if repository == nil {
return nil, fmt.Errorf("repository is required")
}
if cursors == nil {
return nil, fmt.Errorf("cursor codec is required")
}
if sessionTTL <= 0 {
return nil, fmt.Errorf("session TTL must be positive")
}
service := &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
}
for _, option := range options {
if err := option(service); err != nil {
return nil, err
}
}
return service, nil
}
func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
return func(service *Service) error {
if ttl < MinimumIdempotencyTTL {
return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL)
}
service.idempotencyTTL = ttl
return nil
}
}
+57
View File
@@ -0,0 +1,57 @@
package application
import (
"context"
"errors"
"fmt"
"mtusi2026lab3/internal/domain"
"mtusi2026lab3/internal/security"
)
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
"AAAAAAAAAAAAAAAAAAAAAA$" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
func (s *Service) CreateSession(ctx context.Context, command CreateSessionCommand) (domain.Session, error) {
user, passwordHash, err := s.repository.GetUserByUsername(ctx, command.Username)
userNotFound := errors.Is(err, domain.ErrNotFound)
if userNotFound {
passwordHash = dummyPasswordHash
} else if err != nil {
return domain.Session{}, err
}
passwordMatches, verifyErr := security.VerifyPassword(command.Password, passwordHash)
if verifyErr != nil {
return domain.Session{}, fmt.Errorf("%w: %v", ErrCredentialState, verifyErr)
}
if userNotFound || !passwordMatches {
return domain.Session{}, ErrInvalidCredentials
}
token, tokenHash, err := security.GenerateSessionToken()
if err != nil {
return domain.Session{}, fmt.Errorf("generate session token: %w", err)
}
expiresAt := s.now().Add(s.sessionTTL)
if err = s.repository.CreateSession(ctx, tokenHash, user.ID, expiresAt); err != nil {
return domain.Session{}, err
}
return domain.Session{
Token: token, TokenType: "Bearer", ExpiresAt: expiresAt, User: user,
}, nil
}
func (s *Service) Authenticate(ctx context.Context, token string) (domain.User, []byte, error) {
tokenHash := security.HashSessionToken(token)
user, err := s.repository.GetUserBySession(ctx, tokenHash)
if err != nil {
return domain.User{}, nil, err
}
return user, tokenHash, nil
}
func (s *Service) DeleteSession(ctx context.Context, tokenHash []byte) error {
return s.repository.DeleteSession(ctx, tokenHash)
}
+29
View File
@@ -0,0 +1,29 @@
package application
import (
"context"
"fmt"
"mtusi2026lab3/internal/domain"
"mtusi2026lab3/internal/security"
)
func (s *Service) CreateUser(ctx context.Context, command CreateUserCommand) (domain.User, error) {
if err := domain.ValidateUser(command.Username, command.DisplayName); err != nil {
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
if err := security.ValidatePassword(command.Password); err != nil {
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
passwordHash, err := security.HashPassword(command.Password)
if err != nil {
return domain.User{}, fmt.Errorf("hash password: %w", err)
}
return s.repository.CreateUser(
ctx,
command.Username,
command.DisplayName,
passwordHash,
)
}
+434
View File
@@ -0,0 +1,434 @@
package config
import (
"errors"
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
)
type Config struct {
HTTPHost string
HTTPPort string
InstanceID string
SessionTTL time.Duration
IdempotencyTTL time.Duration
SessionCookieSecure bool
CursorSigningKey string
DatabaseURL string
DatabaseMaxConns int32
DatabaseMinConns int32
DatabaseMaxConnLifetime time.Duration
DatabaseMaxConnIdleTime time.Duration
DatabaseHealthCheckPeriod time.Duration
DatabaseConnectTimeout time.Duration
DatabaseQueryTimeout time.Duration
RedisURL string
RedisCacheTTL time.Duration
RedisOperationTimeout time.Duration
RedisPoolSize int
ReadinessTimeout time.Duration
ShutdownDrainDelay time.Duration
ShutdownTimeout time.Duration
}
func Load() (Config, error) {
instanceID, err := instanceIDFromEnv()
if err != nil {
return Config{}, err
}
sessionTTL, err := secondsDurationFromEnv(
"SESSION_TTL_SECONDS",
3600,
)
if err != nil {
return Config{}, err
}
idempotencyTTL, err := secondsDurationFromEnv(
"IDEMPOTENCY_TTL_SECONDS",
86400,
)
if err != nil {
return Config{}, err
}
sessionCookieSecure, err := boolFromEnv("SESSION_COOKIE_SECURE", false)
if err != nil {
return Config{}, err
}
databaseURL, err := requiredValueOrFile(
"DATABASE_URL",
"DATABASE_URL_FILE",
)
if err != nil {
return Config{}, err
}
cursorSigningKey, err := requiredValueOrFile(
"CURSOR_SIGNING_KEY",
"CURSOR_SIGNING_KEY_FILE",
)
if err != nil {
return Config{}, err
}
databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1)
if err != nil {
return Config{}, err
}
databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0)
if err != nil {
return Config{}, err
}
databaseMaxConnLifetime, err := durationFromEnv(
"DB_MAX_CONN_LIFETIME",
30*time.Minute,
)
if err != nil {
return Config{}, err
}
databaseMaxConnIdleTime, err := durationFromEnv(
"DB_MAX_CONN_IDLE_TIME",
5*time.Minute,
)
if err != nil {
return Config{}, err
}
databaseHealthCheckPeriod, err := durationFromEnv(
"DB_HEALTH_CHECK_PERIOD",
30*time.Second,
)
if err != nil {
return Config{}, err
}
databaseConnectTimeout, err := durationFromEnv(
"DB_CONNECT_TIMEOUT",
5*time.Second,
)
if err != nil {
return Config{}, err
}
databaseQueryTimeout, err := durationFromEnv(
"DB_QUERY_TIMEOUT",
3*time.Second,
)
if err != nil {
return Config{}, err
}
redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE")
if err != nil {
return Config{}, err
}
redisCacheTTL, err := durationFromEnv(
"CACHE_TTL",
5*time.Minute,
)
if err != nil {
return Config{}, err
}
redisOperationTimeout, err := durationFromEnv(
"CACHE_OPERATION_TIMEOUT",
250*time.Millisecond,
)
if err != nil {
return Config{}, err
}
redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1)
if err != nil {
return Config{}, err
}
readinessTimeout, err := durationFromEnv(
"READINESS_TIMEOUT",
2*time.Second,
)
if err != nil {
return Config{}, err
}
shutdownDrainDelay, err := durationFromEnv(
"SHUTDOWN_DRAIN_DELAY",
2*time.Second,
)
if err != nil {
return Config{}, err
}
shutdownTimeout, err := durationFromEnv(
"SHUTDOWN_TIMEOUT",
10*time.Second,
)
if err != nil {
return Config{}, err
}
if databaseMinConns > databaseMaxConns {
return Config{}, errors.New(
"DB_MIN_CONNS must not be greater than DB_MAX_CONNS",
)
}
if idempotencyTTL < 24*time.Hour {
return Config{}, errors.New(
"IDEMPOTENCY_TTL_SECONDS must be at least 86400",
)
}
if shutdownDrainDelay >= shutdownTimeout {
return Config{}, errors.New(
"SHUTDOWN_DRAIN_DELAY must be less than SHUTDOWN_TIMEOUT",
)
}
return Config{
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
HTTPPort: envOrDefault("APP_PORT", "8080"),
InstanceID: instanceID,
SessionTTL: sessionTTL,
IdempotencyTTL: idempotencyTTL,
SessionCookieSecure: sessionCookieSecure,
CursorSigningKey: cursorSigningKey,
DatabaseURL: databaseURL,
DatabaseMaxConns: databaseMaxConns,
DatabaseMinConns: databaseMinConns,
DatabaseMaxConnLifetime: databaseMaxConnLifetime,
DatabaseMaxConnIdleTime: databaseMaxConnIdleTime,
DatabaseHealthCheckPeriod: databaseHealthCheckPeriod,
DatabaseConnectTimeout: databaseConnectTimeout,
DatabaseQueryTimeout: databaseQueryTimeout,
RedisURL: redisURL,
RedisCacheTTL: redisCacheTTL,
RedisOperationTimeout: redisOperationTimeout,
RedisPoolSize: int(redisPoolSize),
ReadinessTimeout: readinessTimeout,
ShutdownDrainDelay: shutdownDrainDelay,
ShutdownTimeout: shutdownTimeout,
}, nil
}
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
func instanceIDFromEnv() (string, error) {
instanceID := strings.TrimSpace(os.Getenv("INSTANCE_ID"))
if instanceID == "" {
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("resolve instance id from hostname: %w", err)
}
instanceID = hostname
}
if !instanceIDPattern.MatchString(instanceID) {
return "", errors.New(
"INSTANCE_ID or hostname must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}",
)
}
return instanceID, nil
}
func (c Config) HTTPAddress() string {
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
}
func requiredValueOrFile(valueEnv, fileEnv string) (string, error) {
value, valueExists := os.LookupEnv(valueEnv)
filePath, fileExists := os.LookupEnv(fileEnv)
if valueExists && fileExists {
return "", fmt.Errorf(
"%s and %s must not be set at the same time",
valueEnv,
fileEnv,
)
}
if valueExists {
value = strings.TrimSpace(value)
if value == "" {
return "", fmt.Errorf("%s must not be empty", valueEnv)
}
return value, nil
}
if fileExists {
filePath = strings.TrimSpace(filePath)
if filePath == "" {
return "", fmt.Errorf("%s must not be empty", fileEnv)
}
data, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("read %s: %w", fileEnv, err)
}
value = strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
}
return value, nil
}
return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv)
}
func optionalValueOrFile(valueEnv, fileEnv string) (string, error) {
value, valueExists := os.LookupEnv(valueEnv)
filePath, fileExists := os.LookupEnv(fileEnv)
if valueExists && fileExists {
return "", fmt.Errorf(
"%s and %s must not be set at the same time",
valueEnv,
fileEnv,
)
}
if valueExists {
value = strings.TrimSpace(value)
if value == "" {
return "", fmt.Errorf("%s must not be empty", valueEnv)
}
return value, nil
}
if fileExists {
filePath = strings.TrimSpace(filePath)
if filePath == "" {
return "", fmt.Errorf("%s must not be empty", fileEnv)
}
data, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("read %s: %w", fileEnv, err)
}
value = strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
}
return value, nil
}
return "", nil
}
func envOrDefault(name, fallback string) string {
value := strings.TrimSpace(os.Getenv(name))
if value == "" {
return fallback
}
return value
}
func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := strconv.ParseInt(raw, 10, 32)
if err != nil {
return 0, fmt.Errorf("%s must be an integer: %w", name, err)
}
if value < int64(minimum) {
return 0, fmt.Errorf("%s must be at least %d", name, minimum)
}
return int32(value), nil
}
func boolFromEnv(name string, fallback bool) (bool, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := strconv.ParseBool(raw)
if err != nil {
return false, fmt.Errorf("%s must be true or false: %w", name, err)
}
return value, nil
}
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := time.ParseDuration(raw)
if err != nil {
return 0, fmt.Errorf(
"%s must be a Go duration such as 3s or 5m: %w",
name,
err,
)
}
if value <= 0 {
return 0, fmt.Errorf("%s must be positive", name)
}
return value, nil
}
func secondsDurationFromEnv(
name string,
fallbackSeconds int64,
) (time.Duration, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
raw = strconv.FormatInt(fallbackSeconds, 10)
}
seconds, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return 0, fmt.Errorf(
"%s must be an integer number of seconds: %w",
name,
err,
)
}
if seconds <= 0 {
return 0, fmt.Errorf("%s must be positive", name)
}
duration, err := time.ParseDuration(raw + "s")
if err != nil {
return 0, fmt.Errorf("%s is too large: %w", name, err)
}
return duration, nil
}
+35
View File
@@ -0,0 +1,35 @@
package config
import "testing"
func TestInstanceIDFromEnvironment(t *testing.T) {
t.Setenv("INSTANCE_ID", "api-replica_01")
instanceID, err := instanceIDFromEnv()
if err != nil {
t.Fatal(err)
}
if instanceID != "api-replica_01" {
t.Fatalf("got %q, want api-replica_01", instanceID)
}
}
func TestInstanceIDRejectsUnsafeHeaderValue(t *testing.T) {
t.Setenv("INSTANCE_ID", "api-1\r\nX-Forged: true")
if _, err := instanceIDFromEnv(); err == nil {
t.Fatal("expected unsafe instance ID to be rejected")
}
}
func TestInstanceIDFallsBackToHostname(t *testing.T) {
t.Setenv("INSTANCE_ID", "")
instanceID, err := instanceIDFromEnv()
if err != nil {
t.Fatal(err)
}
if instanceID == "" {
t.Fatal("hostname fallback returned an empty instance ID")
}
}
+29
View File
@@ -0,0 +1,29 @@
package config
import "testing"
func TestBoolFromEnv(t *testing.T) {
t.Run("fallback", func(t *testing.T) {
t.Setenv("TEST_BOOL", "")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || !value {
t.Fatalf("boolFromEnv() = %v, %v; want true, nil", value, err)
}
})
t.Run("explicit false", func(t *testing.T) {
t.Setenv("TEST_BOOL", "false")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || value {
t.Fatalf("boolFromEnv() = %v, %v; want false, nil", value, err)
}
})
t.Run("invalid", func(t *testing.T) {
t.Setenv("TEST_BOOL", "sometimes")
_, err := boolFromEnv("TEST_BOOL", false)
if err == nil {
t.Fatal("boolFromEnv() error = nil, want validation error")
}
})
}
+40
View File
@@ -0,0 +1,40 @@
package database
import (
"context"
"fmt"
"mtusi2026lab3/internal/config"
"github.com/jackc/pgx/v5/pgxpool"
)
func Open(
ctx context.Context,
cfg config.Config,
) (*pgxpool.Pool, error) {
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
if err != nil {
return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err)
}
poolConfig.MaxConns = cfg.DatabaseMaxConns
poolConfig.MinConns = cfg.DatabaseMinConns
poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime
poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime
poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
// NewWithConfig создаёт структуру пула, но не гарантирует,
// что PostgreSQL уже доступен. Ping обеспечивает fail-fast.
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
}
return pool, nil
}
+21
View File
@@ -0,0 +1,21 @@
package domain
import "time"
type Chat struct {
ID string
Title string
MemberIDs []string
CreatedAt time.Time
}
type ChatCursor struct {
CreatedAt time.Time
ChatID string
UserID string
}
type ChatPage struct {
Items []Chat
NextCursor *string
}
+8
View File
@@ -0,0 +1,8 @@
package domain
import "errors"
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
+22
View File
@@ -0,0 +1,22 @@
package domain
import "time"
type Message struct {
ID string
ChatID string
SenderID string
Text string
CreatedAt time.Time
}
type MessageCursor struct {
CreatedAt time.Time
MessageID string
ChatID string
}
type MessagePage struct {
Items []Message
NextCursor *string
}
+10
View File
@@ -0,0 +1,10 @@
package domain
import "time"
type Session struct {
Token string
TokenType string
ExpiresAt time.Time
User User
}
+11
View File
@@ -0,0 +1,11 @@
package domain
import "time"
// User is the transport-independent representation of a messenger user.
type User struct {
ID string
Username string
DisplayName string
CreatedAt time.Time
}
+77
View File
@@ -0,0 +1,77 @@
package domain
import (
"fmt"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func ValidateUser(username, displayName string) error {
if !usernameRegex.MatchString(username) {
return fmt.Errorf("username must match [a-z0-9_]{3,32}")
}
nameRunes := utf8.RuneCountInString(displayName)
if nameRunes < 1 || nameRunes > 100 {
return fmt.Errorf("display_name length must be between 1 and 100 code points")
}
if strings.TrimSpace(displayName) == "" {
return fmt.Errorf("display_name cannot be only whitespace")
}
return nil
}
// Validate remains as a compatibility convenience for existing callers.
func (u User) Validate() error {
return ValidateUser(u.Username, u.DisplayName)
}
func ValidateChatInput(title string, memberIDs []string, callerID string) error {
titleRunes := utf8.RuneCountInString(title)
if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" {
return fmt.Errorf("invalid chat title")
}
if len(memberIDs) == 0 {
return fmt.Errorf("member_ids cannot be empty")
}
if len(memberIDs) > 100 {
return fmt.Errorf("member_ids must contain at most 100 users")
}
hasCaller := false
seen := make(map[string]struct{}, len(memberIDs))
for _, id := range memberIDs {
if _, err := uuid.Parse(id); err != nil {
return fmt.Errorf("invalid member uuid: %s", id)
}
if _, exists := seen[id]; exists {
return fmt.Errorf("duplicate member_id: %s", id)
}
seen[id] = struct{}{}
if id == callerID {
hasCaller = true
}
}
if !hasCaller {
return fmt.Errorf("caller must be in member_ids")
}
return nil
}
func ValidateMessageText(text string) error {
textRunes := utf8.RuneCountInString(text)
if textRunes < 1 || textRunes > 4000 {
return fmt.Errorf("message text length must be between 1 and 4000 code points")
}
if strings.TrimSpace(text) == "" {
return fmt.Errorf("message text cannot be only whitespace")
}
return nil
}
+164
View File
@@ -0,0 +1,164 @@
package security
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"unicode/utf8"
"golang.org/x/crypto/argon2"
)
const (
argonMemory uint32 = 19 * 1024
argonIterations uint32 = 2
argonParallelism uint8 = 1
argonSaltLength = 16
argonKeyLength uint32 = 32
minPasswordLength = 12
maxPasswordLength = 128
)
var ErrInvalidPasswordHash = errors.New("invalid password hash")
func ValidatePassword(password string) error {
if !utf8.ValidString(password) {
return errors.New("password must be valid UTF-8")
}
length := utf8.RuneCountInString(password)
if length < minPasswordLength || length > maxPasswordLength {
return fmt.Errorf(
"password length must be between %d and %d code points",
minPasswordLength,
maxPasswordLength,
)
}
return nil
}
func HashPassword(password string) (string, error) {
if err := ValidatePassword(password); err != nil {
return "", err
}
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
hash := argon2.IDKey(
[]byte(password),
salt,
argonIterations,
argonMemory,
argonParallelism,
argonKeyLength,
)
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
encoded := fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
argonMemory,
argonIterations,
argonParallelism,
encodedSalt,
encodedHash,
)
return encoded, nil
}
func VerifyPassword(
password string,
encodedHash string,
) (bool, error) {
parameters, salt, expectedHash, err := decodePasswordHash(encodedHash)
if err != nil {
return false, err
}
actualHash := argon2.IDKey(
[]byte(password),
salt,
parameters.iterations,
parameters.memory,
parameters.parallelism,
uint32(len(expectedHash)),
)
matches := subtle.ConstantTimeCompare(
actualHash,
expectedHash,
) == 1
return matches, nil
}
type argonParameters struct {
memory uint32
iterations uint32
parallelism uint8
}
func decodePasswordHash(
encodedHash string,
) (argonParameters, []byte, []byte, error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 ||
parts[0] != "" ||
parts[1] != "argon2id" {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
if version != argon2.Version {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
var parameters argonParameters
if _, err := fmt.Sscanf(
parts[3],
"m=%d,t=%d,p=%d",
&parameters.memory,
&parameters.iterations,
&parameters.parallelism,
); err != nil {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
// Ограничения не позволяют повреждённой строке из БД запросить
// гигантский объём памяти или процессорного времени.
if parameters.memory < 8*1024 ||
parameters.memory > 256*1024 ||
parameters.iterations < 1 ||
parameters.iterations > 10 ||
parameters.parallelism < 1 ||
parameters.parallelism > 8 {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 16 || len(salt) > 64 {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(hash) < 16 || len(hash) > 64 {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
return parameters, salt, hash, nil
}
+105
View File
@@ -0,0 +1,105 @@
package security
import (
"strings"
"testing"
)
func TestPasswordHashAndVerify(t *testing.T) {
password := "Correct-password-123"
encodedHash, err := HashPassword(password)
if err != nil {
t.Fatalf("HashPassword returned error: %v", err)
}
if strings.Contains(encodedHash, password) {
t.Fatal("encoded hash contains plaintext password")
}
matches, err := VerifyPassword(password, encodedHash)
if err != nil {
t.Fatalf("VerifyPassword returned error: %v", err)
}
if !matches {
t.Fatal("correct password did not match")
}
matches, err = VerifyPassword("Wrong-password-123", encodedHash)
if err != nil {
t.Fatalf("VerifyPassword returned error: %v", err)
}
if matches {
t.Fatal("wrong password matched")
}
}
func TestPasswordHashesUseDifferentSalts(t *testing.T) {
password := "Correct-password-123"
firstHash, err := HashPassword(password)
if err != nil {
t.Fatalf("first HashPassword returned error: %v", err)
}
secondHash, err := HashPassword(password)
if err != nil {
t.Fatalf("second HashPassword returned error: %v", err)
}
if firstHash == secondHash {
t.Fatal("equal passwords produced equal encoded hashes")
}
}
func TestPasswordValidation(t *testing.T) {
testCases := []struct {
name string
password string
wantErr bool
}{
{
name: "minimum length",
password: "123456789012",
wantErr: false,
},
{
name: "unicode",
password: "пароль-проверка-123",
wantErr: false,
},
{
name: "colon is allowed",
password: "password:with:colon",
wantErr: false,
},
{
name: "too short",
password: "short",
wantErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidatePassword(testCase.password)
if testCase.wantErr && err == nil {
t.Fatal("expected validation error")
}
if !testCase.wantErr && err != nil {
t.Fatalf("unexpected validation error: %v", err)
}
})
}
}
func TestMalformedPasswordHash(t *testing.T) {
_, err := VerifyPassword(
"Correct-password-123",
"not-an-argon2-hash",
)
if err == nil {
t.Fatal("expected malformed hash error")
}
}
+32
View File
@@ -0,0 +1,32 @@
package security
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
)
const sessionTokenBytes = 32
func GenerateSessionToken() (string, []byte, error) {
randomBytes := make([]byte, sessionTokenBytes)
if _, err := rand.Read(randomBytes); err != nil {
return "", nil, fmt.Errorf("generate session token: %w", err)
}
token := base64.RawURLEncoding.EncodeToString(randomBytes)
tokenHash := HashSessionToken(token)
return token, tokenHash, nil
}
func HashSessionToken(token string) []byte {
digest := sha256.Sum256([]byte(token))
hash := make([]byte, len(digest))
copy(hash, digest[:])
return hash
}
+35
View File
@@ -0,0 +1,35 @@
package security
import (
"bytes"
"testing"
)
func TestGenerateSessionToken(t *testing.T) {
firstToken, firstHash, err := GenerateSessionToken()
if err != nil {
t.Fatalf("GenerateSessionToken returned error: %v", err)
}
secondToken, secondHash, err := GenerateSessionToken()
if err != nil {
t.Fatalf("GenerateSessionToken returned error: %v", err)
}
if firstToken == secondToken {
t.Fatal("generated session tokens are equal")
}
if bytes.Equal(firstHash, secondHash) {
t.Fatal("generated session token hashes are equal")
}
if len(firstHash) != 32 {
t.Fatalf("expected 32-byte token hash, got %d", len(firstHash))
}
recalculatedHash := HashSessionToken(firstToken)
if !bytes.Equal(firstHash, recalculatedHash) {
t.Fatal("token hash is not reproducible")
}
}
+38
View File
@@ -0,0 +1,38 @@
package dto
import (
"time"
"mtusi2026lab3/internal/domain"
)
type CreateChatRequest struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
type ChatResponse struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt time.Time `json:"created_at"`
}
type ChatPageResponse struct {
Items []ChatResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func ChatFromDomain(chat domain.Chat) ChatResponse {
return ChatResponse{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
}
}
func ChatPageFromDomain(page domain.ChatPage) ChatPageResponse {
items := make([]ChatResponse, len(page.Items))
for index, chat := range page.Items {
items[index] = ChatFromDomain(chat)
}
return ChatPageResponse{Items: items, NextCursor: page.NextCursor}
}
+39
View File
@@ -0,0 +1,39 @@
package dto
import (
"time"
"mtusi2026lab3/internal/domain"
)
type CreateMessageRequest struct {
Text string `json:"text"`
}
type MessageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
}
type MessagePageResponse struct {
Items []MessageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func MessageFromDomain(message domain.Message) MessageResponse {
return MessageResponse{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, CreatedAt: message.CreatedAt,
}
}
func MessagePageFromDomain(page domain.MessagePage) MessagePageResponse {
items := make([]MessageResponse, len(page.Items))
for index, message := range page.Items {
items[index] = MessageFromDomain(message)
}
return MessagePageResponse{Items: items, NextCursor: page.NextCursor}
}

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