ЛР 3 — БПИ2303 — Белоусов — на 5 #117
+18
-7
@@ -1,13 +1,24 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
APP_ACCESS_LOG=1
|
||||
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
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=messenger
|
||||
POSTGRES_DB=messenger
|
||||
|
||||
# Внутри сети Compose. Хосту для student-tests — localhost после проброса портов.
|
||||
DATABASE_URL=postgres://messenger:messenger@postgres:5432/messenger?sslmode=disable
|
||||
REDIS_URL=redis://redis:6379/0
|
||||
SESSION_STORE=redis
|
||||
|
||||
# Число API-реплик за LB. Поднимать: scripts/up.sh или compose --scale api=N
|
||||
API_REPLICAS=2
|
||||
# Лимиты одной API-реплики (суммарный бюджет track1 = replicas * эти значения).
|
||||
API_CPUS=0.50
|
||||
API_MEMORY=256M
|
||||
# Пул соединений на одну реплику. Суммарно ≈ API_REPLICAS * DB_MAX_CONNS.
|
||||
DB_MAX_CONNS=5
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
FROM golang:1.23.8-bookworm AS build
|
||||
WORKDIR /src
|
||||
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="-s -w" -o /out/server ./cmd/server
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
COPY --from=build /out/server /server
|
||||
USER nonroot:nonroot
|
||||
EXPOSE 8080
|
||||
ENV APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080 \
|
||||
APP_ENV=lab \
|
||||
SESSION_TTL_SECONDS=3600
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=15s --retries=5 \
|
||||
CMD ["/server", "-healthcheck"]
|
||||
ENTRYPOINT ["/server"]
|
||||
@@ -4,10 +4,12 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
GO ?= go
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover student-test up down track1
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "up: build+scale API behind LB; test/test-persistence/test-failover/student-test/track1"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -15,6 +17,12 @@ check:
|
||||
validate:
|
||||
$(PYTHON) scripts/validate_openapi.py
|
||||
|
||||
up:
|
||||
bash scripts/up.sh
|
||||
|
||||
down:
|
||||
docker compose --env-file .env down
|
||||
|
||||
test:
|
||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
@@ -28,3 +36,9 @@ 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)
|
||||
|
||||
student-test:
|
||||
$(GO) test ./student-tests/ -v -count=1 -timeout 180s
|
||||
|
||||
track1:
|
||||
bash scripts/run_track1.sh
|
||||
|
||||
@@ -1,37 +1,99 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Белоусов Анатолий Фахраддинович, БПИ2303
|
||||
- Целевая оценка; выбранный трек 5: **5, трек 1** (цена масштабирования)
|
||||
- Commit/PR: ветка `solution/bpi2303-belousov`
|
||||
- Использованные источники, библиотеки и помощь ИИ: Go `net/http`, `pgx` v5, `go-redis` v9, `golang.org/x/crypto/argon2`, `google/uuid`; HAProxy 2.9; публичные `tests/`; Cursor/Composer для реализации и прогонов. База — собственная реализация lab2.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker, Go 1.23+ (собственные тесты), Python 3.9+.
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
bash scripts/up.sh
|
||||
# дождаться ready; внутри: build, migrate (один раз), --scale api=${API_REPLICAS}, LB на :8080
|
||||
make test
|
||||
make student-test
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
# после failover восстановить реплику и повторить для второй:
|
||||
bash scripts/restore-one.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
bash scripts/run_track1.sh # трек 5; долго, пересоздаёт/rescale стенд
|
||||
```
|
||||
|
||||
Остановка без удаления данных: `docker compose --env-file .env stop`.
|
||||
Удаление учебных volumes: `docker compose --env-file .env down -v`.
|
||||
|
||||
Образы: сборка `golang:1.23.8-bookworm`, runtime `gcr.io/distroless/static-debian12:nonroot`, PostgreSQL `postgres:16.6`, Redis `redis:7.4.1` (AOF `everysec`), HAProxy `haproxy:2.9.14-alpine`.
|
||||
|
||||
Соответствие `.env.example`: `API_REPLICAS` (по умолчанию 2), `API_CPUS`/`API_MEMORY` — лимиты **одной** реплики, `DB_MAX_CONNS` — пул на реплику, `IDEMPOTENCY_TTL_SECONDS=86400`. `DATABASE_URL`/`REDIS_URL` задаются контейнерам явно; `*_FILE` тоже читаются.
|
||||
|
||||
Миграции применяет одноразовый сервис `migrate` (`/server -migrate`) до старта API. Реплики API миграции не гоняют (`RUN_MIGRATIONS` выключен). Повторный migrate идемпотентен через `schema_migrations`.
|
||||
|
||||
Инструкция по сдаче для себя: `SUBMISSION.md`.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Клиент → **HAProxy (LB)** → **API × N** → общие PostgreSQL (данные + idempotency) и Redis (сессии).
|
||||
|
||||
Что перенесено из lab2: пользователи/чаты/сообщения в PostgreSQL, Argon2id, Bearer-сессии в Redis с AOF, keyset-история, graceful shutdown ≤10 с, non-root образ.
|
||||
|
||||
Что добавлено в lab3:
|
||||
|
||||
1. **X-Instance-Id** — hostname контейнера (или `INSTANCE_ID`), стабилен на жизнь процесса; виден в каждом ответе API.
|
||||
2. **Idempotency-Key** на `POST .../messages` — область `(user_id, method, path, key)` в таблице `idempotency_keys`. Сериализация конкурентов — `pg_advisory_xact_lock` + одна транзакция на INSERT message и ключа. Повтор с тем же телом → тот же 201/Message; другой body → 409. 5xx не фиксируются.
|
||||
3. **Общие сессии** в Redis: повторный вход при смене реплики не нужен. Sticky sessions не используются.
|
||||
4. **LB healthcheck** `GET /health/ready` каждые 1 с, `fall 3` → обнаружение ~3 с; DNS hold valid 2 с. На SIGTERM реплика сразу отдаёт 503 ready (BeginDrain).
|
||||
5. **Порты API наружу не публикуются**; наружу только `127.0.0.1:8080` у LB. Postgres/Redis на localhost — только для `student-tests`.
|
||||
6. **CPU/RAM limits** на сервисах; `container_name` нет — `compose --scale api=N` работает. У API `restart: "no"`, иначе `docker stop` в failover-тесте может быть отменён демоном.
|
||||
7. **Rolling update**: `docker compose up -d --scale api=N` / `scripts/restore-one.sh` поднимает недостающие реплики без `down -v`.
|
||||
|
||||
`scripts/stop-one.sh` сопоставляет `TARGET_INSTANCE_ID` с hostname/`INSTANCE_ID` контейнера сервиса `api` и делает `docker stop`, оставляя реплику остановленной.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Стенд прогона: macOS (Darwin 24.6), Docker Desktop, Go 1.23+/1.27 host toolchain. Дата: 2026-11-06.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Публичный smoke | `make test` | PASS lab3 scenario (idempotency, instance id) | `evidence/smoke-pass.txt` |
|
||||
| ≥2 реплики через LB | заголовки `X-Instance-Id` | ≥2 разных id | `evidence/instances.txt` |
|
||||
| Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS | `evidence/persistence.txt` |
|
||||
| Failover одной реплики | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | PASS, recovery ≈2.5 s | `evidence/failover-1.txt` |
|
||||
| Failover второй реплики | restore + повтор failover | PASS, recovery ≈2.8 s | `evidence/failover-2.txt` |
|
||||
| Идемпотентность / гонка ключа | `make student-test` | replay=тот же id; 8 параллельных → 1 сообщение | `evidence/student-test.txt` |
|
||||
| Лимиты / нет publish API | `compose.yaml` + inspect | api Ports без HostPort; NanoCpus/Memory заданы; LB `:8080` | `evidence/ps.txt` |
|
||||
| Трек 1 | `bash scripts/run_track1.sh` | сводка RPS 1/2/4 и grow | `evidence/track1/` |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
## Эксперименты и отказы (трек 1)
|
||||
|
||||
## Эксперименты и отказы
|
||||
**Гипотеза.** При фиксированном суммарном бюджете 2.0 CPU / 1024 MiB на все API рост N=1→2 повышает successful RPS; N=2→4 перестаёт помогать из‑за PostgreSQL/пула/LB.
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
**Методика.** Bootstrap один раз; дальше rescale только `api`+`lb`. Для N∈{1,2,4}: `API_CPUS=2/N`, `API_MEMORY=1024/N MiB`, `DB_MAX_CONNS=5` на реплику. Прогрев до серии успешных `/health/ready`, затем `tests/load.py --duration 30 --concurrency 8`. Затем N=2 с ростом CPU/RAM реплики (0.5→1.0→1.5). Повтор: `bash scripts/run_track1.sh`. Сырые JSON — `evidence/track1/*.json`, сводка — `summary.md`.
|
||||
|
||||
**Наблюдения (закрытый цикл, successful RPS):**
|
||||
|
||||
| Конфиг | RPS | err | p95 ms |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| fixed_budget_n1 (2.0 CPU / 1024 MiB ×1) | **1274.5** | 0 | 11.4 |
|
||||
| fixed_budget_n2 (1.0 / 512 ×2) | 803.2 | 0 | 21.0 |
|
||||
| fixed_budget_n4 (0.5 / 256 ×4) | 1031.5 | 0 | 15.4 |
|
||||
| grow_n2_small (0.5 / 256 ×2) | 898.8 | 0 | 22.0 |
|
||||
| grow_n2_medium (1.0 / 512 ×2) | 1104.5 | 0 | 13.5 |
|
||||
| grow_n2_large (1.5 / 768 ×2) | 1176.9 | 0 | 12.6 |
|
||||
|
||||
**Вывод.** На этом стенде гипотеза «N=2 лучше N=1 при том же бюджете» **не подтвердилась**: один процесс с 2.0 CPU обогнал нарезку. N=4 при том же бюджете лучше N=2, но всё ещё ниже N=1. Узкое место — не «мало реплик», а координация (LB/DNS), суммарный пул к Postgres и closed-loop клиента (coordinated omission).
|
||||
|
||||
**Подтверждённое улучшение:** в серии grow при N=2 рост CPU/RAM 0.5→1.0 поднял RPS 898→1104 (**+23%**); 1.0→1.5 дал ещё +7% (1104→1177) — насыщение: добавление CPU репликам почти догоняет одиночный «толстый» процесс, но не обгоняет его на этом профиле.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| `scripts/restart.sh` | рестарт postgres+redis+api+lb; тот же токен | PASS persistence | volumes на месте |
|
||||
| `scripts/stop-one.sh` | одна реплика down; запись через другую ≤10с | PASS; first_recovery ≈2.4–2.8 с; 1 краткая ошибка | дублей нет |
|
||||
| Stop второй после restore | то же | PASS | подтверждённые сообщения на месте |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Один Docker-host и один HAProxy/Postgres/Redis — SPOF узла. Отказ API-реплики закрыт; отказ БД/LB/host — нет. Redis AOF `everysec` может потерять ~1с сессий при kill -9. Closed-loop load страдает coordinated omission — RPS не open-loop capacity. Трек 2 (multi-node) не выполнялся. Цифры трека 1 — один прогон на локальном диске Docker Desktop, не распределённый бенчмарк.
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# Как сдать лабораторную 3 (для меня)
|
||||
|
||||
Краткий чеклист перед защитой и после замечаний ревью.
|
||||
|
||||
## Что уже сделано в этом PR
|
||||
|
||||
- База — решение lab2 (PostgreSQL + Redis-сессии + Argon2id).
|
||||
- Lab3: HAProxy → API×2+, `X-Instance-Id`, обязательный `Idempotency-Key`, общие сессии, одноразовый `migrate`.
|
||||
- Оценка **5**, трек **1** (цена масштабирования): `scripts/run_track1.sh` → `evidence/track1/`.
|
||||
- Публичные проверки: `make test`, `test-persistence`, `test-failover` (обе реплики), `make student-test`.
|
||||
|
||||
## Перед защитой (локально)
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
bash scripts/up.sh
|
||||
make check
|
||||
make test
|
||||
make student-test
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
bash scripts/restore-one.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
bash scripts/restore-one.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
# трек 5 — долго (~10–20 мин), пересоздаёт стенд:
|
||||
bash scripts/run_track1.sh
|
||||
```
|
||||
|
||||
После трека стенд сам возвращается к `API_REPLICAS=2`.
|
||||
|
||||
## Что говорить на защите
|
||||
|
||||
1. Через LB показать ≥2 разных `X-Instance-Id` на одной сессии (без sticky).
|
||||
2. `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` — одна реплика down, запись идёт через другую ≤10 с, дублей нет.
|
||||
3. Persistence: тот же Bearer после `scripts/restart.sh`.
|
||||
4. Трек 1: гипотеза про фиксированный CPU/RAM бюджет; цифры в `evidence/track1/summary.md`.
|
||||
5. SPOF: один Docker-host, один HAProxy, одна БД — отказ API-реплики закрыт, узла БД/LB — нет.
|
||||
|
||||
## PR
|
||||
|
||||
- Ветка: `solution/bpi2303-belousov`
|
||||
- База PR: `mtusi2026/mtusi2026lab3` → `main`
|
||||
- Заголовок: `ЛР 3 — БПИ2303 — Белоусов — на 5`
|
||||
- Не коммитить `.env`, токены, volumes.
|
||||
- После замечаний — пуш в ту же ветку, тот же PR.
|
||||
|
||||
## Если что-то красное
|
||||
|
||||
| Симптом | Что проверить |
|
||||
| --- | --- |
|
||||
| `less than two API instances` | `bash scripts/restore-one.sh`, в `.env` должно быть `API_REPLICAS=2` |
|
||||
| failover видит остановленную реплику | у `api` в compose `restart: "no"`; `stop-one.sh` делает `docker stop` |
|
||||
| порт 8080 занят | остановить другой стенд (lab2 и т.п.) |
|
||||
| student-test не видит БД | Postgres проброшен на `127.0.0.1:5432` |
|
||||
|
||||
Подробности архитектуры и таблица доказательств — в `REPORT.md`.
|
||||
@@ -0,0 +1,171 @@
|
||||
// Точка входа HTTP API и одноразового мигратора.
|
||||
//
|
||||
// Режимы:
|
||||
//
|
||||
// (по умолчанию) — API-реплика: ждёт Postgres/Redis, слушает порт, миграции НЕ применяет
|
||||
// (их гоняет отдельный сервис migrate, чтобы реплики не гонялись);
|
||||
// -migrate — применить встроенные SQL и выйти с кодом 0/1;
|
||||
// -healthcheck — локальный probe /health/ready для Docker HEALTHCHECK.
|
||||
//
|
||||
// SIGTERM: /health/ready → 503 (LB снимает реплику) и Shutdown до 10 секунд.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab3/internal/api"
|
||||
"mtusi2026lab3/internal/auth"
|
||||
"mtusi2026lab3/internal/config"
|
||||
"mtusi2026lab3/internal/session"
|
||||
"mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
healthcheck := flag.Bool("healthcheck", false, "probe local /health/ready and exit")
|
||||
migrateOnly := flag.Bool("migrate", false, "apply SQL migrations and exit")
|
||||
flag.Parse()
|
||||
if *healthcheck {
|
||||
os.Exit(runHealthcheck())
|
||||
}
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("config: %v", err)
|
||||
}
|
||||
hasher, err := auth.NewHasher()
|
||||
if err != nil {
|
||||
log.Fatalf("password hasher: %v", err)
|
||||
}
|
||||
|
||||
rootCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
st, err := waitPostgres(rootCtx, cfg.DatabaseURL, hasher, cfg.MaxConns)
|
||||
if err != nil {
|
||||
log.Fatalf("postgres: %v", err)
|
||||
}
|
||||
defer st.Close()
|
||||
|
||||
if *migrateOnly || cfg.RunMigrations {
|
||||
if err := st.Migrate(rootCtx); err != nil {
|
||||
log.Fatalf("migrate: %v", err)
|
||||
}
|
||||
log.Printf("migrations applied")
|
||||
if *migrateOnly {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
sessions, err := waitRedis(rootCtx, cfg.RedisURL, cfg.SessionTTL)
|
||||
if err != nil {
|
||||
log.Fatalf("redis: %v", err)
|
||||
}
|
||||
defer sessions.Close()
|
||||
|
||||
srvAPI := api.New(st, sessions, cfg.InstanceID)
|
||||
httpServer := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: srvAPI.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("listening on %s env=%s instance=%s session_ttl=%s db_max_conns=%d",
|
||||
cfg.Addr(), cfg.Env, cfg.InstanceID, cfg.SessionTTL, cfg.MaxConns)
|
||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
errCh <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
log.Fatalf("listen: %v", err)
|
||||
case <-rootCtx.Done():
|
||||
}
|
||||
log.Printf("shutting down instance=%s", cfg.InstanceID)
|
||||
srvAPI.BeginDrain()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := httpServer.Shutdown(ctx); err != nil {
|
||||
log.Printf("shutdown error: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Printf("shutdown complete")
|
||||
}
|
||||
|
||||
func waitPostgres(ctx context.Context, dsn string, hasher *auth.Hasher, maxConns int32) (*store.Store, error) {
|
||||
deadline := time.Now().Add(45 * time.Second)
|
||||
var last error
|
||||
for {
|
||||
st, err := store.Open(ctx, dsn, hasher, maxConns)
|
||||
if err == nil {
|
||||
return st, nil
|
||||
}
|
||||
last = err
|
||||
if ctx.Err() != nil || time.Now().After(deadline) {
|
||||
return nil, last
|
||||
}
|
||||
log.Printf("postgres not ready, retrying")
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitRedis(ctx context.Context, redisURL string, ttl time.Duration) (*session.Store, error) {
|
||||
deadline := time.Now().Add(45 * time.Second)
|
||||
var last error
|
||||
for {
|
||||
st, err := session.Open(redisURL, ttl)
|
||||
if err == nil {
|
||||
return st, nil
|
||||
}
|
||||
last = err
|
||||
if ctx.Err() != nil || time.Now().After(deadline) {
|
||||
return nil, last
|
||||
}
|
||||
log.Printf("redis not ready, retrying")
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runHealthcheck() int {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
host := cfg.Host
|
||||
if host == "0.0.0.0" || host == "::" {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
resp, err := client.Get(fmt.Sprintf("http://%s:%d/health/ready", host, cfg.Port))
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
# Локальный стенд lab3: Клиент → HAProxy → API×N → общие PostgreSQL и Redis.
|
||||
# Публикуется только LB (:8080). Порты API наружу не публикуются.
|
||||
# Запуск: bash scripts/up.sh (миграции однократно через compose run, затем --scale api=N)
|
||||
# container_name не задаём: иначе --scale одного сервиса невозможен.
|
||||
x-api-env: &api-env
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
APP_ACCESS_LOG: ${APP_ACCESS_LOG:-1}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
DB_MAX_CONNS: ${DB_MAX_CONNS:-5}
|
||||
DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:-messenger}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.6
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
stop_grace_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 512M
|
||||
|
||||
redis:
|
||||
image: redis:7.4.1
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
ports:
|
||||
- "127.0.0.1:6379:6379"
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
stop_grace_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.50"
|
||||
memory: 256M
|
||||
|
||||
# Одноразовый мигратор. Не в depends_on API: иначе compose спотыкается о restart:no.
|
||||
# Запускается явно из scripts/up.sh: docker compose run --rm migrate
|
||||
migrate:
|
||||
build: .
|
||||
command: ["-migrate"]
|
||||
environment:
|
||||
<<: *api-env
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
healthcheck:
|
||||
disable: true
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.50"
|
||||
memory: 256M
|
||||
|
||||
api:
|
||||
build: .
|
||||
environment:
|
||||
<<: *api-env
|
||||
expose:
|
||||
- "8080"
|
||||
depends_on:
|
||||
redis:
|
||||
condition: service_healthy
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "/server", "-healthcheck"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 10
|
||||
start_period: 15s
|
||||
stop_grace_period: 10s
|
||||
# no: иначе после docker stop в stop-one.sh демон может снова поднять реплику,
|
||||
# и failover-тест увидит TARGET_INSTANCE_ID среди живых ответов.
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: ${API_CPUS:-0.50}
|
||||
memory: ${API_MEMORY:-256M}
|
||||
|
||||
lb:
|
||||
image: haproxy:2.9.14-alpine
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "haproxy", "-c", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
start_period: 5s
|
||||
stop_grace_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.50"
|
||||
memory: 128M
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
redisdata:
|
||||
+11
-3
@@ -1,5 +1,13 @@
|
||||
# Доказательства
|
||||
# Evidence
|
||||
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
Текстовые выводы публичных и собственных проверок. Не кладите сюда токены, пароли и дампы сессий.
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
| Файл | Что доказывает |
|
||||
| --- | --- |
|
||||
| `smoke-pass.txt` | `make test` (lab3 smoke: idempotency + instance id) |
|
||||
| `instances.txt` | ≥2 разных `X-Instance-Id` через LB |
|
||||
| `persistence.txt` | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` |
|
||||
| `failover-1.txt` / `failover-2.txt` | поочерёдный отказ каждой API-реплики |
|
||||
| `student-test.txt` | собственные Go-тесты (idempotency race, deps down, …) |
|
||||
| `ps.txt` | API без publish наружу; CPU/RAM limits; LB на `:8080` |
|
||||
| `track1/` | трек 5: RPS при 1/2/4 репликах и grow-серия |
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
:0
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 112, "failed_attempts": 1, "first_recovery_seconds": 2.452}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 115, "failed_attempts": 1, "first_recovery_seconds": 2.45}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,4 @@
|
||||
observed X-Instance-Id via LB /health/live (40 requests):
|
||||
768d1d0dcfb6
|
||||
ac070c8e5c53
|
||||
count=2
|
||||
@@ -0,0 +1 @@
|
||||
500000000 268435456 {"8080/tcp":null}
|
||||
@@ -0,0 +1,3 @@
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,7 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api 50 seconds ago Up 3 seconds (health: starting) 8080/tcp
|
||||
mtusi2026lab3-api-2 mtusi2026lab3-api "/server" api 50 seconds ago Up 25 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb 49 seconds ago Up 25 seconds (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 mtusi2026lab3-migrate "/server -migrate" migrate 4 seconds ago Exited (0) 2 seconds ago
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres 58 seconds ago Up 25 seconds (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis 58 seconds ago Up 24 seconds (healthy) 127.0.0.1:6379->6379/tcp
|
||||
@@ -0,0 +1,7 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api About a minute ago Up 19 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-2 mtusi2026lab3-api "/server" api About a minute ago Exited (0) 15 seconds ago
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb About a minute ago Up 41 seconds (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 mtusi2026lab3-migrate "/server -migrate" migrate 20 seconds ago Exited (0) 19 seconds ago
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres About a minute ago Up 41 seconds (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis About a minute ago Up 41 seconds (healthy) 127.0.0.1:6379->6379/tcp
|
||||
@@ -0,0 +1,12 @@
|
||||
=== compose ps ===
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api 2 seconds ago Up 1 second (health: starting) 8080/tcp
|
||||
mtusi2026lab3-api-2 mtusi2026lab3-api "/server" api 2 seconds ago Up Less than a second (health: starting) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb About a minute ago Up About a minute (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres 6 minutes ago Up 6 minutes (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis 6 minutes ago Up 6 minutes (healthy) 127.0.0.1:6379->6379/tcp
|
||||
=== api publish / limits ===
|
||||
Name=/mtusi2026lab3-api-1 NanoCpus=500000000 Memory=268435456 Ports={"8080/tcp":null}
|
||||
Name=/mtusi2026lab3-api-2 NanoCpus=500000000 Memory=268435456 Ports={"8080/tcp":null}
|
||||
=== lb ===
|
||||
Name=/mtusi2026lab3-lb-1 Ports={"8080/tcp":[{"HostIp":"127.0.0.1","HostPort":"8080"}]}
|
||||
@@ -0,0 +1,7 @@
|
||||
Container mtusi2026lab3-api-1 Running
|
||||
Container mtusi2026lab3-api-2 Running
|
||||
Container mtusi2026lab3-lb-1 Running
|
||||
Container mtusi2026lab3-api-1 Running
|
||||
Container mtusi2026lab3-api-2 Starting
|
||||
Container mtusi2026lab3-api-2 Started
|
||||
Container mtusi2026lab3-lb-1 Running
|
||||
@@ -0,0 +1,2 @@
|
||||
{"successful_writes": 33, "failed_attempts": 70}
|
||||
PASS: rolling recreate under load completed
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,185 @@
|
||||
go test ./student-tests/ -v -count=1 -timeout 180s
|
||||
=== RUN TestMalformedJSONAndValidation
|
||||
api_test.go:73: → битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=400 request_id=82502122-e299-413e-a454-059549f1db06 duration_ms=0
|
||||
api_test.go:76: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"82502122-e299-413e-a454-059549f1db06"}}
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=400 request_id=f620552d-a5de-4f1a-990f-c2cd66d99b78 duration_ms=0
|
||||
api_test.go:83: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"f620552d-a5de-4f1a-990f-c2cd66d99b78"}}
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=201 request_id=d16e4fd8-9d25-43ed-9f98-ae67851ed42c duration_ms=53
|
||||
api_test.go:88: создан ok_user_0b3aa182 id=75e06162-aff8-4c24-b10d-9620a50189b6
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/auth/sessions status=201 request_id=2a1553f4-7ec2-4cd1-860c-b1e2716c58f2 duration_ms=39
|
||||
api_test.go:89: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/chats status=201 request_id=a75c4f01-e734-4e4e-b646-c4d7741e70e2 duration_ms=10
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/chats/85a4b239-bf50-4f7c-ac5a-c96dc7991831/messages status=400 request_id=c364a82e-6455-407e-8171-cf8fc5f583ad duration_ms=0
|
||||
api_test.go:96: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"c364a82e-6455-407e-8171-cf8fc5f583ad"}}
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/chats/85a4b239-bf50-4f7c-ac5a-c96dc7991831/messages status=400 request_id=d65cd251-e7e5-4481-a652-e47538eee956 duration_ms=0
|
||||
api_test.go:96: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"d65cd251-e7e5-4481-a652-e47538eee956"}}
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/chats/85a4b239-bf50-4f7c-ac5a-c96dc7991831/messages status=400 request_id=7c7dc7ef-6675-4dc6-bf8f-7ef48aa0ab02 duration_ms=0
|
||||
api_test.go:103: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"7c7dc7ef-6675-4dc6-bf8f-7ef48aa0ab02"}}
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=201 request_id=8ed32fcb-dee3-49d5-be05-eb3657cc460d duration_ms=28
|
||||
api_test.go:108: создан outsider_f6dc956a id=5a9797fb-7ba6-4e15-8587-8aa59d40d9de
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/auth/sessions status=201 request_id=ba923b7f-edeb-476a-b613-e565c5a576cf duration_ms=29
|
||||
api_test.go:109: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/chats/85a4b239-bf50-4f7c-ac5a-c96dc7991831/messages status=404 request_id=89e82723-1e18-42d7-80d7-8bff739389ad duration_ms=6
|
||||
api_test.go:111: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"89e82723-1e18-42d7-80d7-8bff739389ad"}}
|
||||
api_test.go:115: ✓ валидация JSON, хвоста, пустого текста и чужого чата
|
||||
--- PASS: TestMalformedJSONAndValidation (0.17s)
|
||||
=== RUN TestMessageTextPreservedAndLengthOnOriginal
|
||||
api_test.go:121: → пробелы по краям сохраняются; длина считается по исходному тексту
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=201 request_id=18304831-da8e-46a6-b4b0-a22b14164c0d duration_ms=32
|
||||
api_test.go:122: создан text_user_b7e1d958 id=d6ae736e-a66f-4dd7-8cc1-00a6e0c1544e
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/auth/sessions status=201 request_id=1b6bbefc-ce95-4a07-8e03-9b1a5fe7c8ae duration_ms=29
|
||||
api_test.go:123: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/chats status=201 request_id=818e462b-9f65-47b4-af19-e28112de7cff duration_ms=2
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/chats/0f0dc75f-1c0b-40db-8164-f3b0c4e02137/messages status=201 request_id=a43b9d37-4525-4a7d-9f99-22d8cfd9e59b duration_ms=4
|
||||
api_test.go:130: status=201 body={"chat_id":"0f0dc75f-1c0b-40db-8164-f3b0c4e02137","created_at":"2026-11-06T17:46:06.477Z","id":"d79cc695-026b-41f1-995e-266ed033e556","sender_id":"d6ae736e-a66f-4dd7-8cc1-00a6e0c1544e","text":" строка\nс пробелами "}
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/chats/0f0dc75f-1c0b-40db-8164-f3b0c4e02137/messages status=400 request_id=633bed72-2e32-46a9-a08a-785f69e11c73 duration_ms=0
|
||||
api_test.go:142: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"633bed72-2e32-46a9-a08a-785f69e11c73"}}
|
||||
api_test.go:146: ✓ текст сохранён целиком, обход лимита через TrimSpace закрыт
|
||||
--- PASS: TestMessageTextPreservedAndLengthOnOriginal (0.07s)
|
||||
=== RUN TestSessionRejectsJSONBody
|
||||
api_test.go:152: → POST /auth/sessions с телом должен быть 400 даже при верном Basic
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=201 request_id=832252b5-494d-4883-9c1e-c4e13359256d duration_ms=28
|
||||
api_test.go:153: создан body_user_f7fed7a7 id=76627b78-1f74-42fc-9d03-9e3d90a24212
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/auth/sessions status=400 request_id=99776f27-00fc-474b-80fc-fb10d223601a duration_ms=0
|
||||
api_test.go:157: status=400 body={"error":{"code":"invalid_request","message":"session create must not have a body","request_id":"99776f27-00fc-474b-80fc-fb10d223601a"}}
|
||||
api_test.go:161: ✓ вход без JSON body
|
||||
--- PASS: TestSessionRejectsJSONBody (0.03s)
|
||||
=== RUN TestWrongPasswordLogoutAndIgnoredUserHeader
|
||||
api_test.go:167: → неверный пароль, Basic на бизнес-методе, X-User-Id, logout
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=201 request_id=b33cebf9-78d0-4d84-a869-2b991b57120c duration_ms=49
|
||||
api_test.go:168: создан auth_user_f2aa9ca5 id=e7e6c3a8-718b-4731-97d0-d6bcc38a7927
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=201 request_id=0be0610f-10cb-4330-a7d6-33433ce6f8c4 duration_ms=27
|
||||
api_test.go:169: создан auth_other_8d1c78ab id=523b562b-8ae9-49fc-83a6-120e5732aa79
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/auth/sessions status=401 request_id=795419f7-7fbe-4391-9c05-049473f467d7 duration_ms=28
|
||||
api_test.go:174: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"795419f7-7fbe-4391-9c05-049473f467d7"}}
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/auth/sessions status=201 request_id=45f65dfd-bd2d-4ac8-8b2b-da1d4b3d6d0c duration_ms=34
|
||||
api_test.go:179: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:06 method=GET path=/api/v1/users/me status=401 request_id=c54d4b50-be84-46b5-92a4-f5956bf89616 duration_ms=0
|
||||
api_test.go:183: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"c54d4b50-be84-46b5-92a4-f5956bf89616"}}
|
||||
2026/11/06 20:46:06 method=GET path=/api/v1/users/me status=401 request_id=363b4c77-e5a7-455d-839a-5a3f9a6244ec duration_ms=0
|
||||
api_test.go:189: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"363b4c77-e5a7-455d-839a-5a3f9a6244ec"}}
|
||||
2026/11/06 20:46:06 method=GET path=/api/v1/users/me status=200 request_id=d87440cd-27f2-4183-a277-e90f70fa8e80 duration_ms=1
|
||||
api_test.go:198: status=200 body={"created_at":"2026-11-06T17:46:06.563Z","display_name":"Студент","id":"e7e6c3a8-718b-4731-97d0-d6bcc38a7927","username":"auth_user_f2aa9ca5"}
|
||||
2026/11/06 20:46:06 method=DELETE path=/api/v1/auth/sessions/current status=204 request_id=62ff5724-32bd-492c-9e15-e9d3956356e8 duration_ms=0
|
||||
api_test.go:204: logout status=204
|
||||
2026/11/06 20:46:06 method=GET path=/api/v1/users/me status=401 request_id=f495e2f2-0dea-4525-ba92-30461ee7c456 duration_ms=0
|
||||
2026/11/06 20:46:06 method=DELETE path=/api/v1/auth/sessions/current status=401 request_id=f55f3f25-0ed1-483b-aa18-15dee90d0648 duration_ms=0
|
||||
api_test.go:216: ✓ пароль, заголовки и отзыв сессии
|
||||
--- PASS: TestWrongPasswordLogoutAndIgnoredUserHeader (0.15s)
|
||||
=== RUN TestSessionExpiry
|
||||
api_test.go:222: → SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/users status=201 request_id=9291cb27-d279-46d0-90df-abc5010b6469 duration_ms=28
|
||||
api_test.go:223: создан ttl_user_bf52abe7 id=f12b0275-5d5c-41a5-be2b-17b95c6ffe94
|
||||
2026/11/06 20:46:06 method=POST path=/api/v1/auth/sessions status=201 request_id=8eeac3c6-5b03-4a72-b47e-84cbb1bd7cd1 duration_ms=29
|
||||
api_test.go:224: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:09 method=GET path=/api/v1/users/me status=401 request_id=4b4016cf-40ba-49a1-a536-fded793098de duration_ms=1
|
||||
api_test.go:227: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"4b4016cf-40ba-49a1-a536-fded793098de"}}
|
||||
api_test.go:231: ✓ истёкшая сессия отклонена
|
||||
--- PASS: TestSessionExpiry (2.57s)
|
||||
=== RUN TestDuplicateUsernameRace
|
||||
api_test.go:238: → 8 параллельных регистраций username=race_13b2e314
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=201 request_id=98b7cabe-a9a3-48e9-856b-667f4e25c443 duration_ms=95
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=409 request_id=310438e7-62b0-4243-926e-5984cf9f7f31 duration_ms=98
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=409 request_id=bc8611ed-4a07-45e9-9ab2-276f15c80746 duration_ms=99
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=409 request_id=359c5ecd-43c2-4b4e-9846-73c044250997 duration_ms=101
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=409 request_id=752c74ac-8cda-4905-a92f-7a4c8de4c55a duration_ms=108
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=409 request_id=b79e711a-6017-4287-9d78-beedd0996f60 duration_ms=109
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=409 request_id=2c56cb2f-89bf-4636-aba2-a508dfbbc488 duration_ms=110
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=409 request_id=4375b0f8-3cb5-4f9b-80a6-377b54c239df duration_ms=111
|
||||
api_test.go:263: created=1 conflict=7
|
||||
api_test.go:267: ✓ UNIQUE username выдержал гонку
|
||||
--- PASS: TestDuplicateUsernameRace (0.14s)
|
||||
=== RUN TestChatCreateRollsBack
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=201 request_id=e00f3a1b-3d87-4dbf-acc4-4511c7ad88a8 duration_ms=42
|
||||
api_test.go:273: создан roll_user_4e5e1481 id=40d54c17-c429-404e-8c79-4276ec80de85
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/auth/sessions status=201 request_id=56669740-a3d6-4cac-996c-1de21c5d3222 duration_ms=78
|
||||
api_test.go:274: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
api_test.go:277: → создание чата с несуществующим участником должно откатиться, title=rollback-7c25ebeb-1184-43ab-bf55-ea03b9a798bd
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/chats status=400 request_id=04d22041-678b-4164-a931-3fce67c2cb8f duration_ms=12
|
||||
api_test.go:280: status=400 body={"error":{"code":"invalid_request","message":"unknown member","request_id":"04d22041-678b-4164-a931-3fce67c2cb8f"}}
|
||||
api_test.go:288: строк chats с этим title после ошибки: 0
|
||||
api_test.go:292: ✓ транзакция создания чата откатилась
|
||||
--- PASS: TestChatCreateRollsBack (0.14s)
|
||||
=== RUN TestPaginationPages
|
||||
api_test.go:298: → три сообщения, две страницы limit=2, затем последняя
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=201 request_id=b0815bd7-8ebc-4fdd-99d3-66ece6241da8 duration_ms=77
|
||||
api_test.go:299: создан page_user_e98926ce id=0886a2ab-448f-4e4c-85dd-1fd070883523
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/auth/sessions status=201 request_id=93c6547d-8fa1-4334-83f1-505534305f92 duration_ms=92
|
||||
api_test.go:300: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/chats status=201 request_id=ad862b85-9219-40a7-993d-ba506a9dfb45 duration_ms=13
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/chats/0543e598-c52f-42eb-905b-80fa0d477598/messages status=201 request_id=8f4d9da8-7abf-4d66-a4e7-c8ff784cbaeb duration_ms=19
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/chats/0543e598-c52f-42eb-905b-80fa0d477598/messages status=201 request_id=7bcd1b07-9071-43bb-9ff1-d7f18559557b duration_ms=3
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/chats/0543e598-c52f-42eb-905b-80fa0d477598/messages status=201 request_id=c417896e-d061-44f6-9984-a8e5c77764b6 duration_ms=8
|
||||
2026/11/06 20:46:09 method=GET path=/api/v1/chats/0543e598-c52f-42eb-905b-80fa0d477598/messages status=200 request_id=393c6e66-6853-4609-a458-b17d858ed07b duration_ms=2
|
||||
api_test.go:310: status=200 body={"items":[{"chat_id":"0543e598-c52f-42eb-905b-80fa0d477598","created_at":"2026-11-06T17:46:09.707Z","id":"7baf8fda-3541-4183-8af3-c6788bb1c2cd","sender_id":"0886a2ab-448f-4e4c-85dd-1fd070883523","text":"раз"},{"chat_id":"0543e598-c52f-42eb-905b-80fa0d477598","created_at":"2026-11-06T17:46:09.715Z","id":"f960271d-045c-4ec2-a5d8-8e135402a904","sender_id":"0886a2ab-448f-4e4c-85dd-1fd070883523","te...
|
||||
2026/11/06 20:46:09 method=GET path=/api/v1/chats/0543e598-c52f-42eb-905b-80fa0d477598/messages status=200 request_id=3c18f8fe-8f42-4570-9cde-478beea37a6e duration_ms=1
|
||||
api_test.go:318: status=200 body={"items":[{"chat_id":"0543e598-c52f-42eb-905b-80fa0d477598","created_at":"2026-11-06T17:46:09.725Z","id":"ea86bb15-c6a7-4059-8177-e54c2b4d9c07","sender_id":"0886a2ab-448f-4e4c-85dd-1fd070883523","text":"три"}],"next_cursor":null}
|
||||
api_test.go:324: ✓ keyset обошёл историю без зависания cursor
|
||||
--- PASS: TestPaginationPages (0.23s)
|
||||
=== RUN TestRedisDownIsNotAnonymous
|
||||
api_test.go:328: → закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=201 request_id=1942453a-9f9c-4837-a004-8c99e5253c91 duration_ms=53
|
||||
api_test.go:340: создан redis_down_a3d94db1 id=3833f1aa-b200-4e2a-a7f3-8ea35efcf275
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/auth/sessions status=503 request_id=9078472e-cb44-41c0-a910-8654261b01e0 duration_ms=39
|
||||
api_test.go:344: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"9078472e-cb44-41c0-a910-8654261b01e0"}}
|
||||
2026/11/06 20:46:09 method=GET path=/api/v1/users/me status=503 request_id=a6107a51-fd7c-40b2-be2e-b2545ba82665 duration_ms=0
|
||||
api_test.go:351: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"a6107a51-fd7c-40b2-be2e-b2545ba82665"}}
|
||||
api_test.go:355: ✓ сбой Redis не стал анонимным доступом
|
||||
--- PASS: TestRedisDownIsNotAnonymous (0.10s)
|
||||
=== RUN TestPostgresDownIsNotAnonymous
|
||||
api_test.go:359: → закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/users status=201 request_id=e7c4b84e-f07f-449a-b66c-ed07917a1f28 duration_ms=42
|
||||
api_test.go:362: создан pg_down_6ccc1931 id=05b646b7-4815-439c-96b1-9057413d6957
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/auth/sessions status=201 request_id=16c7eacc-6092-4903-a044-9b5a0a3a81b6 duration_ms=38
|
||||
api_test.go:363: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:09 method=GET path=/health/ready status=503 request_id=d6fb4e1d-f01b-4474-b401-89e094a9eee7 duration_ms=0
|
||||
api_test.go:384: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"d6fb4e1d-f01b-4474-b401-89e094a9eee7"}}
|
||||
2026/11/06 20:46:09 method=GET path=/api/v1/users/me status=503 request_id=52afb042-c70b-4ed8-a9ee-8ab497a758c4 duration_ms=0
|
||||
api_test.go:391: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"52afb042-c70b-4ed8-a9ee-8ab497a758c4"}}
|
||||
2026/11/06 20:46:09 method=POST path=/api/v1/auth/sessions status=503 request_id=90541ca1-961a-4276-96cb-f19172eecf7b duration_ms=0
|
||||
api_test.go:398: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"90541ca1-961a-4276-96cb-f19172eecf7b"}}
|
||||
api_test.go:402: ✓ сбой PostgreSQL не стал анонимным доступом
|
||||
--- PASS: TestPostgresDownIsNotAnonymous (0.15s)
|
||||
=== RUN TestIdempotencyReplayAndConflict
|
||||
api_test.go:409: → повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/users status=201 request_id=4ec37886-8d95-4784-b5d5-1e7dfabcddab duration_ms=29
|
||||
api_test.go:410: создан idem_user_9c6d662f id=53d33900-2eae-4e46-a939-bedb0cc5d928
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/auth/sessions status=201 request_id=d20cc604-21c6-43d5-90c9-6e822d5ff191 duration_ms=32
|
||||
api_test.go:411: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats status=201 request_id=c4f200f9-64fe-4903-88db-73782e8ee422 duration_ms=3
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/11936c78-4669-481a-a808-a602f56627e0/messages status=201 request_id=0371a103-73f4-4865-b9e3-4ae9c1745f3f duration_ms=7
|
||||
api_test.go:419: status=201 body={"chat_id":"11936c78-4669-481a-a808-a602f56627e0","created_at":"2026-11-06T17:46:10.047Z","id":"6fc605ac-e37e-4640-b90a-2a4c2a8c9042","sender_id":"53d33900-2eae-4e46-a939-bedb0cc5d928","text":"один раз"}
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/11936c78-4669-481a-a808-a602f56627e0/messages status=201 request_id=58363eaf-1693-4f3a-b141-ba06410a7576 duration_ms=6
|
||||
api_test.go:425: status=201 body={"chat_id":"11936c78-4669-481a-a808-a602f56627e0","created_at":"2026-11-06T17:46:10.047Z","id":"6fc605ac-e37e-4640-b90a-2a4c2a8c9042","sender_id":"53d33900-2eae-4e46-a939-bedb0cc5d928","text":"один раз"}
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/11936c78-4669-481a-a808-a602f56627e0/messages status=409 request_id=d33766c6-ce1d-44a2-8aa9-7625c50c4814 duration_ms=3
|
||||
api_test.go:434: status=409 body={"error":{"code":"conflict","message":"idempotency key reused with different body","request_id":"d33766c6-ce1d-44a2-8aa9-7625c50c4814"}}
|
||||
api_test.go:438: ✓ replay и conflict по Idempotency-Key
|
||||
--- PASS: TestIdempotencyReplayAndConflict (0.08s)
|
||||
=== RUN TestIdempotencyKeyRequiredAndConcurrent
|
||||
api_test.go:444: → нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/users status=201 request_id=3a3990a8-015c-4c86-be56-3e98ebba3950 duration_ms=41
|
||||
api_test.go:445: создан idem_race_33d4db8f id=5415e7f3-4c00-407f-877e-21fa32c903c5
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/auth/sessions status=201 request_id=73ab668c-8f19-4195-8c9c-d1a2e72b9a46 duration_ms=27
|
||||
api_test.go:446: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats status=201 request_id=d4cabda8-aeda-4ef6-975d-ff7abfc571ed duration_ms=2
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=400 request_id=5a178619-44f1-4be5-a14c-2392431291d6 duration_ms=0
|
||||
api_test.go:464: status=400 body={"error":{"code":"invalid_request","message":"invalid or missing Idempotency-Key","request_id":"5a178619-44f1-4be5-a14c-2392431291d6"}}
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=201 request_id=0fcd82fa-4921-40eb-8223-1f072ec8ce45 duration_ms=6
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=201 request_id=c5388197-6a37-48ee-992d-106bae593dc5 duration_ms=8
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=201 request_id=0fcdda38-46dc-4bce-a52e-704745db52be duration_ms=10
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=201 request_id=ecaee0b6-d366-4b20-b458-404e23f80db5 duration_ms=12
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=201 request_id=a99fb3f0-624a-4a6b-a9b8-5ac18bed4618 duration_ms=15
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=201 request_id=e8685009-2b1b-43d5-ae95-4d5e724efc12 duration_ms=15
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=201 request_id=fcf8faaa-d21f-4d90-aa11-5c594266d0a5 duration_ms=16
|
||||
2026/11/06 20:46:10 method=POST path=/api/v1/chats/7bfa2935-365b-4bec-ad28-e8b9a5329627/messages status=201 request_id=b189e688-fd76-4c73-8cb6-76c00423a2d5 duration_ms=17
|
||||
api_test.go:496: unique message ids=1
|
||||
api_test.go:500: ✓ ключ обязателен; конкурентный повтор не плодит дубли
|
||||
--- PASS: TestIdempotencyKeyRequiredAndConcurrent (0.09s)
|
||||
=== RUN TestInstanceIDHeaderPresent
|
||||
api_test.go:506: → каждый ответ содержит непустой X-Instance-Id
|
||||
api_test.go:508: status=200 body={"status":"ok"}
|
||||
api_test.go:512: ✓ X-Instance-Id=test-instance
|
||||
--- PASS: TestInstanceIDHeaderPresent (0.00s)
|
||||
PASS
|
||||
ok mtusi2026lab3/student-tests 5.156s
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.007,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 38244,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1274.523,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.207,
|
||||
"p95": 11.383,
|
||||
"p99": 23.418
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api 42 seconds ago Up 41 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb 41 seconds ago Up 40 seconds (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres 4 minutes ago Up 4 minutes (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis 4 minutes ago Up 4 minutes (healthy) 127.0.0.1:6379->6379/tcp
|
||||
@@ -0,0 +1,4 @@
|
||||
mtusi2026lab3-lb-1 0.18% 12.72MiB / 128MiB
|
||||
mtusi2026lab3-api-1 2.11% 34.25MiB / 1GiB
|
||||
mtusi2026lab3-postgres-1 0.64% 169.6MiB / 512MiB
|
||||
mtusi2026lab3-redis-1 0.67% 10.23MiB / 256MiB
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.011,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 24105,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 803.214,
|
||||
"successful_latency_ms": {
|
||||
"p50": 6.762,
|
||||
"p95": 21.044,
|
||||
"p99": 57.587
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api 43 seconds ago Up 41 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-2 mtusi2026lab3-api "/server" api 43 seconds ago Up 41 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb 41 seconds ago Up 40 seconds (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres 5 minutes ago Up 5 minutes (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis 5 minutes ago Up 5 minutes (healthy) 127.0.0.1:6379->6379/tcp
|
||||
@@ -0,0 +1,5 @@
|
||||
mtusi2026lab3-lb-1 0.35% 11.57MiB / 128MiB
|
||||
mtusi2026lab3-api-2 4.60% 11.25MiB / 512MiB
|
||||
mtusi2026lab3-api-1 4.82% 11.74MiB / 512MiB
|
||||
mtusi2026lab3-postgres-1 16.66% 181.6MiB / 512MiB
|
||||
mtusi2026lab3-redis-1 1.86% 10.24MiB / 256MiB
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.023,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 30969,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1031.514,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.836,
|
||||
"p95": 15.396,
|
||||
"p99": 33.891
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api 43 seconds ago Up 41 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-2 mtusi2026lab3-api "/server" api 43 seconds ago Up 42 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-3 mtusi2026lab3-api "/server" api 43 seconds ago Up 41 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-4 mtusi2026lab3-api "/server" api 43 seconds ago Up 41 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb 41 seconds ago Up 38 seconds (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres About a minute ago Up About a minute (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis About a minute ago Up About a minute (healthy) 127.0.0.1:6379->6379/tcp
|
||||
@@ -0,0 +1,7 @@
|
||||
mtusi2026lab3-lb-1 0.49% 14.12MiB / 128MiB
|
||||
mtusi2026lab3-api-2 3.45% 10.9MiB / 256MiB
|
||||
mtusi2026lab3-api-3 0.58% 11.18MiB / 256MiB
|
||||
mtusi2026lab3-api-1 0.09% 11.75MiB / 256MiB
|
||||
mtusi2026lab3-api-4 0.27% 11.09MiB / 256MiB
|
||||
mtusi2026lab3-postgres-1 7.41% 146.9MiB / 512MiB
|
||||
mtusi2026lab3-redis-1 0.97% 9.758MiB / 256MiB
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.007,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 35315,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1176.901,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.551,
|
||||
"p95": 12.617,
|
||||
"p99": 27.51
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api 41 seconds ago Up 40 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-2 mtusi2026lab3-api "/server" api 41 seconds ago Up 39 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb 40 seconds ago Up 38 seconds (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres 3 minutes ago Up 3 minutes (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis 3 minutes ago Up 3 minutes (healthy) 127.0.0.1:6379->6379/tcp
|
||||
@@ -0,0 +1,5 @@
|
||||
mtusi2026lab3-lb-1 0.38% 11.92MiB / 128MiB
|
||||
mtusi2026lab3-api-1 1.48% 29.01MiB / 768MiB
|
||||
mtusi2026lab3-api-2 1.33% 15.62MiB / 768MiB
|
||||
mtusi2026lab3-postgres-1 1.01% 180.4MiB / 512MiB
|
||||
mtusi2026lab3-redis-1 2.30% 9.98MiB / 256MiB
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.007,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 33143,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 1104.515,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.507,
|
||||
"p95": 13.456,
|
||||
"p99": 33.913
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api 40 seconds ago Up 40 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-2 mtusi2026lab3-api "/server" api 40 seconds ago Up 40 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb 40 seconds ago Up 38 seconds (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres 3 minutes ago Up 3 minutes (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis 3 minutes ago Up 3 minutes (healthy) 127.0.0.1:6379->6379/tcp
|
||||
@@ -0,0 +1,5 @@
|
||||
mtusi2026lab3-lb-1 0.40% 13.71MiB / 128MiB
|
||||
mtusi2026lab3-api-1 0.27% 30.51MiB / 512MiB
|
||||
mtusi2026lab3-api-2 0.17% 13.12MiB / 512MiB
|
||||
mtusi2026lab3-postgres-1 61.94% 200.2MiB / 512MiB
|
||||
mtusi2026lab3-redis-1 0.66% 9.973MiB / 256MiB
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.013,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 26975,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 898.769,
|
||||
"successful_latency_ms": {
|
||||
"p50": 5.925,
|
||||
"p95": 21.961,
|
||||
"p99": 56.599
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-1 mtusi2026lab3-api "/server" api 40 seconds ago Up 39 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-2 mtusi2026lab3-api "/server" api 40 seconds ago Up 39 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:2.9.14-alpine "docker-entrypoint.s…" lb 39 seconds ago Up 37 seconds (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab3-postgres-1 postgres:16.6 "docker-entrypoint.s…" postgres 2 minutes ago Up 2 minutes (healthy) 127.0.0.1:5432->5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.1 "docker-entrypoint.s…" redis 2 minutes ago Up 2 minutes (healthy) 127.0.0.1:6379->6379/tcp
|
||||
@@ -0,0 +1,5 @@
|
||||
mtusi2026lab3-lb-1 0.48% 11.75MiB / 128MiB
|
||||
mtusi2026lab3-api-1 0.38% 27.84MiB / 256MiB
|
||||
mtusi2026lab3-api-2 0.22% 15.15MiB / 256MiB
|
||||
mtusi2026lab3-postgres-1 0.69% 153.8MiB / 512MiB
|
||||
mtusi2026lab3-redis-1 0.52% 9.75MiB / 256MiB
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"runs": [
|
||||
{
|
||||
"label": "fixed_budget_n1",
|
||||
"successful_rps": 1274.523,
|
||||
"error_ratio": 0.0,
|
||||
"p50_ms": 5.207,
|
||||
"p95_ms": 11.383,
|
||||
"p99_ms": 23.418,
|
||||
"successful_requests": 38244,
|
||||
"failed_requests": 0,
|
||||
"concurrency": 8,
|
||||
"elapsed_seconds": 30.007
|
||||
},
|
||||
{
|
||||
"label": "fixed_budget_n2",
|
||||
"successful_rps": 803.214,
|
||||
"error_ratio": 0.0,
|
||||
"p50_ms": 6.762,
|
||||
"p95_ms": 21.044,
|
||||
"p99_ms": 57.587,
|
||||
"successful_requests": 24105,
|
||||
"failed_requests": 0,
|
||||
"concurrency": 8,
|
||||
"elapsed_seconds": 30.011
|
||||
},
|
||||
{
|
||||
"label": "fixed_budget_n4",
|
||||
"successful_rps": 1031.514,
|
||||
"error_ratio": 0.0,
|
||||
"p50_ms": 5.836,
|
||||
"p95_ms": 15.396,
|
||||
"p99_ms": 33.891,
|
||||
"successful_requests": 30969,
|
||||
"failed_requests": 0,
|
||||
"concurrency": 8,
|
||||
"elapsed_seconds": 30.023
|
||||
},
|
||||
{
|
||||
"label": "grow_n2_small",
|
||||
"successful_rps": 898.769,
|
||||
"error_ratio": 0.0,
|
||||
"p50_ms": 5.925,
|
||||
"p95_ms": 21.961,
|
||||
"p99_ms": 56.599,
|
||||
"successful_requests": 26975,
|
||||
"failed_requests": 0,
|
||||
"concurrency": 8,
|
||||
"elapsed_seconds": 30.013
|
||||
},
|
||||
{
|
||||
"label": "grow_n2_medium",
|
||||
"successful_rps": 1104.515,
|
||||
"error_ratio": 0.0,
|
||||
"p50_ms": 5.507,
|
||||
"p95_ms": 13.456,
|
||||
"p99_ms": 33.913,
|
||||
"successful_requests": 33143,
|
||||
"failed_requests": 0,
|
||||
"concurrency": 8,
|
||||
"elapsed_seconds": 30.007
|
||||
},
|
||||
{
|
||||
"label": "grow_n2_large",
|
||||
"successful_rps": 1176.901,
|
||||
"error_ratio": 0.0,
|
||||
"p50_ms": 5.551,
|
||||
"p95_ms": 12.617,
|
||||
"p99_ms": 27.51,
|
||||
"successful_requests": 35315,
|
||||
"failed_requests": 0,
|
||||
"concurrency": 8,
|
||||
"elapsed_seconds": 30.007
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Track 1 summary
|
||||
|
||||
Closed-loop `tests/load.py` (duration=30, concurrency=8). RPS — только успешные HTTP 201.
|
||||
|
||||
| label | RPS | err_ratio | p50 ms | p95 ms | p99 ms | ok | fail |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| fixed_budget_n1 | 1274.523 | 0.0 | 5.207 | 11.383 | 23.418 | 38244 | 0 |
|
||||
| fixed_budget_n2 | 803.214 | 0.0 | 6.762 | 21.044 | 57.587 | 24105 | 0 |
|
||||
| fixed_budget_n4 | 1031.514 | 0.0 | 5.836 | 15.396 | 33.891 | 30969 | 0 |
|
||||
| grow_n2_small | 898.769 | 0.0 | 5.925 | 21.961 | 56.599 | 26975 | 0 |
|
||||
| grow_n2_medium | 1104.515 | 0.0 | 5.507 | 13.456 | 33.913 | 33143 | 0 |
|
||||
| grow_n2_large | 1176.901 | 0.0 | 5.551 | 12.617 | 27.51 | 35315 | 0 |
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
module mtusi2026lab3
|
||||
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.7.4
|
||||
github.com/redis/go-redis/v9 v9.7.3
|
||||
golang.org/x/crypto v0.36.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // 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
|
||||
golang.org/x/sync v0.12.0 // indirect
|
||||
golang.org/x/sys v0.31.0 // indirect
|
||||
golang.org/x/text v0.23.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
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.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/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.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
|
||||
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
|
||||
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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
|
||||
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
|
||||
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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
|
||||
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
|
||||
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
|
||||
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
|
||||
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
|
||||
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
|
||||
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=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,52 @@
|
||||
# HAProxy — единственная публичная точка входа lab3.
|
||||
#
|
||||
# Backend-адреса берутся из Docker DNS имени сервиса `api` (A-записи всех реплик).
|
||||
# server-template + resolvers перечитывает DNS; option httpchk снимает реплику,
|
||||
# у которой /health/ready != 200 (в т.ч. после BeginDrain на SIGTERM).
|
||||
#
|
||||
# Оценка обнаружения отказа:
|
||||
# inter 1s * fall 2 = ~2s по healthcheck + hold valid 2s у DNS ≈ до ~4s.
|
||||
# Краткие 502/503 в это окно допустимы контрактом failover-теста.
|
||||
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 512
|
||||
|
||||
defaults
|
||||
log global
|
||||
mode http
|
||||
option httplog
|
||||
option dontlognull
|
||||
timeout connect 2s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
timeout check 1s
|
||||
timeout http-keep-alive 10s
|
||||
retries 2
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 2s
|
||||
hold other 2s
|
||||
hold refused 2s
|
||||
hold nx 2s
|
||||
hold timeout 2s
|
||||
hold obsolete 2s
|
||||
|
||||
frontend fe_http
|
||||
bind *:8080
|
||||
default_backend be_api
|
||||
|
||||
backend be_api
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
option redispatch
|
||||
retry-on conn-failure empty-response response-timeout
|
||||
http-check send meth GET uri /health/ready
|
||||
http-check expect status 200
|
||||
# До 8 слотов под --scale api=N. init-addr last,libc,none ждёт DNS при старте.
|
||||
# fall 3: чуть терпимее к краткому DNS-мерцанию при docker stop одной реплики.
|
||||
server-template api 8 api:8080 check inter 1s fall 3 rise 1 resolvers docker resolve-prefer ipv4 init-addr last,libc,none
|
||||
@@ -0,0 +1,721 @@
|
||||
// Package api — HTTP-слой lab3.
|
||||
//
|
||||
// Порядок обработки запроса:
|
||||
// 1. X-Request-Id и X-Instance-Id на каждый ответ, включая ошибки;
|
||||
// 2. журнал method/path/status без текста сообщений и без токена;
|
||||
// 3. маршрут;
|
||||
// 4. для защищённых маршрутов — только Bearer. Basic и X-User-Id доступ не дают.
|
||||
//
|
||||
// /health/live отвечает, пока процесс жив. /health/ready ещё проверяет PostgreSQL и Redis:
|
||||
// без них нельзя честно принять запись или узнать, кто делает запрос.
|
||||
//
|
||||
// POST сообщения требует Idempotency-Key; результат хранится в общей БД, а не в памяти реплики.
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab3/internal/session"
|
||||
"mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
userKey ctxKey = iota
|
||||
tokenKey
|
||||
requestIDKey
|
||||
)
|
||||
|
||||
const (
|
||||
challengeBasic = `Basic realm="messenger", charset="UTF-8"`
|
||||
challengeBearer = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
// Server связывает HTTP с PostgreSQL и Redis.
|
||||
type Server struct {
|
||||
Store *store.Store
|
||||
Sessions *session.Store
|
||||
InstanceID string
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
// New помечает процесс готовым. Реальная зависимость всё равно проверяется в /health/ready.
|
||||
// instanceID попадает в X-Instance-Id каждого ответа и стабилен на жизнь процесса.
|
||||
func New(st *store.Store, sessions *session.Store, instanceID string) *Server {
|
||||
s := &Server{Store: st, Sessions: sessions, InstanceID: instanceID}
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
}
|
||||
|
||||
// BeginDrain вызывается на SIGTERM: новые клиенты видят 503 на /health/ready.
|
||||
// HAProxy/Traefik с httpchk на /health/ready перестаёт слать трафик на эту реплику.
|
||||
func (s *Server) BeginDrain() { s.ready.Store(false) }
|
||||
|
||||
// Handler собирает маршруты lab3.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", s.handleLive)
|
||||
mux.HandleFunc("GET /health/ready", s.handleReady)
|
||||
mux.HandleFunc("POST /api/v1/users", s.handleCreateUser)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", s.handleCreateSession)
|
||||
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", s.requireUser(s.handleRevokeSession))
|
||||
mux.HandleFunc("GET /api/v1/users/me", s.requireUser(s.handleMe))
|
||||
mux.HandleFunc("POST /api/v1/chats", s.requireUser(s.handleCreateChat))
|
||||
mux.HandleFunc("GET /api/v1/chats", s.requireUser(s.handleListChats))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", s.requireUser(s.handleGetChat))
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleCreateMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleListMessages))
|
||||
return s.withInstanceID(s.withRequestID(s.withAccessLog(mux)))
|
||||
}
|
||||
|
||||
func (s *Server) handleLive(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.ready.Load() {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "service is shutting down")
|
||||
return
|
||||
}
|
||||
if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeStrict(r, &body); err != nil {
|
||||
writeDecodeErr(w, r, err)
|
||||
return
|
||||
}
|
||||
if !validUsername(body.Username) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
display := strings.TrimSpace(body.DisplayName)
|
||||
if display == "" || utf8.RuneCountInString(display) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
if n := utf8.RuneCountInString(body.Password); n < 12 || n > 128 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid password")
|
||||
return
|
||||
}
|
||||
u, err := s.Store.CreateUser(r.Context(), body.Username, display, body.Password)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusConflict, "conflict", "username already taken")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, userDTO(u))
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
// Контракт: только Basic, без JSON body. Любые байты в теле — 400, не тихий игнор.
|
||||
rawBody, err := io.ReadAll(io.LimitReader(r.Body, 4096))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid body")
|
||||
return
|
||||
}
|
||||
if len(bytes.TrimSpace(rawBody)) != 0 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "session create must not have a body")
|
||||
return
|
||||
}
|
||||
username, password, ok := parseBasic(r.Header.Get("Authorization"))
|
||||
if !ok || !validUsername(username) {
|
||||
writeAuthError(w, r, challengeBasic)
|
||||
return
|
||||
}
|
||||
if n := utf8.RuneCountInString(password); n < 12 || n > 128 {
|
||||
writeAuthError(w, r, challengeBasic)
|
||||
return
|
||||
}
|
||||
u, err := s.Store.Authenticate(r.Context(), username, password)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeAuthError(w, r, challengeBasic)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
token, exp, err := s.Sessions.Issue(r.Context(), u.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": formatTime(exp),
|
||||
"user": userDTO(u),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleRevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token, _ := r.Context().Value(tokenKey).(string)
|
||||
if err := s.Sessions.Revoke(r.Context(), token); err != nil {
|
||||
if errors.Is(err, session.ErrUnauthorized) {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.Store.GetUser(r.Context(), userFrom(r))
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, userDTO(u))
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := decodeStrict(r, &body); err != nil {
|
||||
writeDecodeErr(w, r, err)
|
||||
return
|
||||
}
|
||||
title := strings.TrimSpace(body.Title)
|
||||
if title == "" || utf8.RuneCountInString(title) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid title")
|
||||
return
|
||||
}
|
||||
if len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids")
|
||||
return
|
||||
}
|
||||
uid := userFrom(r)
|
||||
seen := make(map[uuid.UUID]struct{}, len(body.MemberIDs))
|
||||
ids := make([]uuid.UUID, 0, len(body.MemberIDs))
|
||||
callerPresent := false
|
||||
for _, raw := range body.MemberIDs {
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member id")
|
||||
return
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "duplicate member id")
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == uid {
|
||||
callerPresent = true
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if !callerPresent {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "caller must be a member")
|
||||
return
|
||||
}
|
||||
chat, err := s.Store.CreateChat(r.Context(), title, ids)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "unknown member")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, chatDTO(chat))
|
||||
}
|
||||
|
||||
func (s *Server) handleListChats(w http.ResponseWriter, r *http.Request) {
|
||||
uid := userFrom(r)
|
||||
limit, after, err := parsePage(r, "chats:"+uid.String())
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
items, next, err := s.Store.ListChats(r.Context(), uid, limit, after)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
out := make([]any, len(items))
|
||||
for i := range items {
|
||||
out[i] = chatDTO(&items[i])
|
||||
}
|
||||
var cursor *store.PageCursor
|
||||
if next != nil {
|
||||
cursor = &store.PageCursor{Scope: "chats:" + uid.String(), CreatedAt: next.CreatedAt, ID: next.ID}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, pageDTO(out, cursor))
|
||||
}
|
||||
|
||||
func (s *Server) handleGetChat(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
chat, err := s.Store.GetChat(r.Context(), chatID, userFrom(r))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatDTO(chat))
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
idemKey := r.Header.Get("Idempotency-Key")
|
||||
if !validIdempotencyKey(idemKey) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid or missing Idempotency-Key")
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
if err := decodeStrict(r, &body); err != nil {
|
||||
writeDecodeErr(w, r, err)
|
||||
return
|
||||
}
|
||||
// Непустота — по TrimSpace; длина и сохранение — по исходному тексту.
|
||||
// Иначе пробелы по краям пропадают, а строка «пробел + 4000 букв» проходит как 4000.
|
||||
if strings.TrimSpace(body.Text) == "" || utf8.RuneCountInString(body.Text) > 4000 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||
return
|
||||
}
|
||||
// attachment_ids в lab3 ещё не поддерживаются; непустой список — 400.
|
||||
// Отсутствующий ключ и [] семантически равны для хэша идемпотентности.
|
||||
if body.AttachmentIDs == nil {
|
||||
body.AttachmentIDs = []string{}
|
||||
}
|
||||
if len(body.AttachmentIDs) != 0 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "attachments are not supported in lab3")
|
||||
return
|
||||
}
|
||||
path := "/api/v1/chats/" + chatID.String() + "/messages"
|
||||
reqHash := idempotencyRequestHash(body.Text, body.AttachmentIDs)
|
||||
result, err := s.Store.CreateMessageIdempotent(
|
||||
r.Context(), chatID, userFrom(r), body.Text,
|
||||
http.MethodPost, path, idemKey, reqHash,
|
||||
)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, store.ErrIdempotencyConflict) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, messageDTO(result.Message))
|
||||
}
|
||||
|
||||
func (s *Server) handleListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
scope := "chat:" + chatID.String()
|
||||
limit, after, err := parsePage(r, scope)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
items, next, err := s.Store.ListMessages(r.Context(), chatID, userFrom(r), limit, after)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
out := make([]any, len(items))
|
||||
for i := range items {
|
||||
out[i] = messageDTO(&items[i])
|
||||
}
|
||||
var cursor *store.PageCursor
|
||||
if next != nil {
|
||||
cursor = &store.PageCursor{Scope: scope, CreatedAt: next.CreatedAt, ID: next.ID}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, pageDTO(out, cursor))
|
||||
}
|
||||
|
||||
// requireUser принимает только Authorization: Bearer. X-User-Id не читается.
|
||||
// Basic на бизнес-методе — тот же 401, но с Bearer-challenge, не с Basic.
|
||||
func (s *Server) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if strings.HasPrefix(strings.ToLower(header), "basic ") {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
token, ok := parseBearer(header)
|
||||
if !ok {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
uid, err := s.Sessions.Lookup(r.Context(), token)
|
||||
if errors.Is(err, session.ErrUnauthorized) {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userKey, uid)
|
||||
ctx = context.WithValue(ctx, tokenKey, token)
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func userFrom(r *http.Request) uuid.UUID {
|
||||
id, _ := r.Context().Value(userKey).(uuid.UUID)
|
||||
return id
|
||||
}
|
||||
|
||||
func (s *Server) withRequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
rid := r.Header.Get("X-Request-Id")
|
||||
if rid == "" {
|
||||
rid = uuid.NewString()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", rid)
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, rid)))
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) withInstanceID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", s.InstanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// validIdempotencyKey — ASCII [A-Za-z0-9._:-]{1,128}.
|
||||
func validIdempotencyKey(key string) bool {
|
||||
if len(key) < 1 || len(key) > 128 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(key); i++ {
|
||||
c := key[i]
|
||||
switch {
|
||||
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9':
|
||||
case c == '.', c == '_', c == ':', c == '-':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// idempotencyRequestHash канонизирует тело: порядок ключей JSON не важен,
|
||||
// отсутствующий attachment_ids равен []. Хэш — SHA-256 hex.
|
||||
func idempotencyRequestHash(text string, attachmentIDs []string) string {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
payload, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{Text: text, AttachmentIDs: attachmentIDs})
|
||||
sum := sha256.Sum256(payload)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusRecorder) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *Server) withAccessLog(next http.Handler) http.Handler {
|
||||
quiet := strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "0") || strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "false")
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
if quiet && rec.status < 400 {
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/health/") && rec.status == http.StatusOK {
|
||||
return
|
||||
}
|
||||
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||
// path без query: в cursor нет секрета, но и текста сообщения в логе быть не должно.
|
||||
log.Printf("method=%s path=%s status=%d request_id=%s duration_ms=%d",
|
||||
r.Method, r.URL.Path, rec.status, rid, time.Since(start).Milliseconds())
|
||||
})
|
||||
}
|
||||
|
||||
func parsePage(r *http.Request, expectedScope string) (int, *store.PageCursor, error) {
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, fmt.Errorf("invalid limit")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
rawCursor := r.URL.Query().Get("cursor")
|
||||
if rawCursor == "" {
|
||||
return limit, nil, nil
|
||||
}
|
||||
cur, err := decodeCursor(rawCursor)
|
||||
if err != nil || cur.Scope != expectedScope {
|
||||
return 0, nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
return limit, cur, nil
|
||||
}
|
||||
|
||||
func encodeCursor(c *store.PageCursor) string {
|
||||
payload := fmt.Sprintf("%s|%s|%s", c.Scope, c.CreatedAt.UTC().Format(time.RFC3339Nano), c.ID.String())
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(payload))
|
||||
}
|
||||
|
||||
func decodeCursor(raw string) (*store.PageCursor, error) {
|
||||
b, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.SplitN(string(b), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil, fmt.Errorf("bad cursor")
|
||||
}
|
||||
ts, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &store.PageCursor{Scope: parts[0], CreatedAt: ts.UTC(), ID: id}, nil
|
||||
}
|
||||
|
||||
func validUsername(s string) bool {
|
||||
if len(s) < 3 || len(s) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, c := range s {
|
||||
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func decodeStrict(r *http.Request, dst any) error {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if ct != "" && !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ct)), "application/json") {
|
||||
return errUnsupported
|
||||
}
|
||||
// Читаем тело целиком: Decoder.More() не ловит хвост вида {"text":"x"}} —
|
||||
// после одного объекта More()=false, а лишняя скобка всё равно остаётся.
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
return errMalformed
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return errMalformed
|
||||
}
|
||||
rest := bytes.TrimSpace(raw[dec.InputOffset():])
|
||||
if len(rest) != 0 {
|
||||
return errMalformed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
errUnsupported = errors.New("unsupported media type")
|
||||
errMalformed = errors.New("malformed json")
|
||||
)
|
||||
|
||||
func writeDecodeErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, errUnsupported) {
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed json")
|
||||
}
|
||||
|
||||
func parseBasic(header string) (string, string, bool) {
|
||||
const prefix = "basic "
|
||||
if len(header) < len(prefix) || strings.ToLower(header[:len(prefix)]) != prefix {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(header[len(prefix):]))
|
||||
if err != nil || !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
user, pass, ok := strings.Cut(string(raw), ":")
|
||||
if !ok || user == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return user, pass, true
|
||||
}
|
||||
|
||||
func parseBearer(header string) (string, bool) {
|
||||
const prefix = "bearer "
|
||||
if len(header) < len(prefix) || strings.ToLower(header[:len(prefix)]) != prefix {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(header[len(prefix):])
|
||||
if token == "" || strings.Contains(token, " ") {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func userDTO(u *store.User) map[string]any {
|
||||
return map[string]any{
|
||||
"id": u.ID.String(),
|
||||
"username": u.Username,
|
||||
"display_name": u.DisplayName,
|
||||
"created_at": formatTime(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func chatDTO(c *store.Chat) map[string]any {
|
||||
ids := make([]string, len(c.MemberIDs))
|
||||
for i, id := range c.MemberIDs {
|
||||
ids[i] = id.String()
|
||||
}
|
||||
return map[string]any{
|
||||
"id": c.ID.String(),
|
||||
"title": c.Title,
|
||||
"member_ids": ids,
|
||||
"created_at": formatTime(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func messageDTO(m *store.Message) map[string]any {
|
||||
return map[string]any{
|
||||
"id": m.ID.String(),
|
||||
"chat_id": m.ChatID.String(),
|
||||
"sender_id": m.SenderID.String(),
|
||||
"text": m.Text,
|
||||
"created_at": formatTime(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func pageDTO(items []any, next *store.PageCursor) map[string]any {
|
||||
var cursor any
|
||||
if next != nil {
|
||||
cursor = encodeCursor(next)
|
||||
}
|
||||
if items == nil {
|
||||
items = []any{}
|
||||
}
|
||||
return map[string]any{"items": items, "next_cursor": cursor}
|
||||
}
|
||||
|
||||
func formatTime(t time.Time) string {
|
||||
return t.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z")
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(v)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||
if rid == "" {
|
||||
rid = w.Header().Get("X-Request-Id")
|
||||
}
|
||||
writeJSON(w, status, map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": rid,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func writeAuthError(w http.ResponseWriter, r *http.Request, challenge string) {
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||
}
|
||||
|
||||
// writeStoreErr прячет текст драйвера. fallbackStatus используется для ожидаемой доменной ошибки.
|
||||
func (s *Server) writeStoreErr(w http.ResponseWriter, r *http.Request, err error, fallbackStatus int, fallbackCode, fallbackMessage string) {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
case errors.Is(err, store.ErrIdempotencyConflict):
|
||||
writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body")
|
||||
case errors.Is(err, store.ErrConflict) && fallbackStatus != 0:
|
||||
writeError(w, r, fallbackStatus, fallbackCode, fallbackMessage)
|
||||
case errors.Is(err, store.ErrNotFound) && fallbackStatus != 0:
|
||||
if fallbackCode == "unauthorized" {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
writeError(w, r, fallbackStatus, fallbackCode, fallbackMessage)
|
||||
case errors.Is(err, store.ErrInvalidCursor):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
default:
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "username already taken")
|
||||
return
|
||||
}
|
||||
// В лог — только тип, без SQL и без текста, который драйвер мог вложить в ошибку.
|
||||
log.Printf("request_id=%s store_error_type=%T", requestID(r), err)
|
||||
writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
}
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||
return rid
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Package auth хранит пароли через Argon2id.
|
||||
//
|
||||
// bcrypt отвергнут: библиотека молча режет пароль на 72 байта, а контракт
|
||||
// разрешает до 128 Unicode code points, включая символы вне ASCII.
|
||||
// Argon2id принимает пароль целиком. Параметры — интерактивные, не «серверные»
|
||||
// на сотни миллисекунд: smoke создаёт несколько пользователей подряд.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 2
|
||||
argonMemory = 19 * 1024 // KiB, около 19 MiB
|
||||
argonThreads = 1
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
// Hasher умеет хешировать и проверять. dummy — хеш случайного пароля,
|
||||
// чтобы отсутствующий username занимал примерно столько же CPU, сколько неверный пароль.
|
||||
type Hasher struct {
|
||||
dummy string
|
||||
}
|
||||
|
||||
// NewHasher готовит dummy-хеш один раз на процесс.
|
||||
func NewHasher() (*Hasher, error) {
|
||||
dummy, err := Hash(randomPassword())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Hasher{dummy: dummy}, nil
|
||||
}
|
||||
|
||||
// Hash возвращает PHC-строку. Её пишем в users.password_hash.
|
||||
func Hash(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
|
||||
argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(sum),
|
||||
), nil
|
||||
}
|
||||
|
||||
// Verify сравнивает пароль с PHC-строкой. При битой строке возвращает false, не панику.
|
||||
func (h *Hasher) Verify(encoded, password string) bool {
|
||||
if encoded == "" {
|
||||
encoded = h.dummy
|
||||
}
|
||||
ok, err := verify(encoded, password)
|
||||
if err != nil {
|
||||
// Всё равно тратим время dummy-проверки, чтобы ветка ошибки не была мгновенной.
|
||||
_, _ = verify(h.dummy, password)
|
||||
return false
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// Burn тратит время проверки, когда пользователя нет. Результат всегда false.
|
||||
func (h *Hasher) Burn(password string) {
|
||||
_, _ = verify(h.dummy, password)
|
||||
}
|
||||
|
||||
func verify(encoded, password string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
// ["", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash]
|
||||
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
|
||||
return false, fmt.Errorf("bad hash")
|
||||
}
|
||||
var memory uint32
|
||||
var timeCost uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if memory != argonMemory || timeCost != argonTime || threads != argonThreads {
|
||||
return false, fmt.Errorf("unexpected argon2 parameters")
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, timeCost, memory, threads, uint32(len(want)))
|
||||
// ConstantTimeCompare не даёт выйти на первом несовпавшем байте.
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func randomPassword() string {
|
||||
buf := make([]byte, 24)
|
||||
_, _ = rand.Read(buf)
|
||||
return base64.RawStdEncoding.EncodeToString(buf)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Package config читает настройки процесса из окружения.
|
||||
//
|
||||
// Прямые URL (DATABASE_URL, REDIS_URL) удобны в Compose.
|
||||
// Вариант *_FILE из .env.example нужен, если секрет смонтирован файлом:
|
||||
// тогда в переменной лежит путь, а не сам секрет.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config — всё, что процесс обязан знать до открытия соединений.
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
DatabaseURL string
|
||||
RedisURL string
|
||||
SessionTTL time.Duration
|
||||
InstanceID string
|
||||
MaxConns int32
|
||||
RunMigrations bool
|
||||
IdempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
// Load собирает Config. Пустой URL без файла — ошибка запуска, а не тихий дефолт на чужой хост.
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Env: getenv("APP_ENV", "lab"),
|
||||
}
|
||||
port, err := strconv.Atoi(getenv("APP_PORT", "8080"))
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return cfg, fmt.Errorf("invalid APP_PORT")
|
||||
}
|
||||
cfg.Port = port
|
||||
|
||||
ttlSec, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
if err != nil || ttlSec < 1 || ttlSec > 7*24*3600 {
|
||||
return cfg, fmt.Errorf("invalid SESSION_TTL_SECONDS")
|
||||
}
|
||||
cfg.SessionTTL = time.Duration(ttlSec) * time.Second
|
||||
|
||||
idemTTL, err := strconv.Atoi(getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
if err != nil || idemTTL < 60 || idemTTL > 7*24*3600 {
|
||||
return cfg, fmt.Errorf("invalid IDEMPOTENCY_TTL_SECONDS")
|
||||
}
|
||||
cfg.IdempotencyTTL = time.Duration(idemTTL) * time.Second
|
||||
|
||||
maxConns, err := strconv.Atoi(getenv("DB_MAX_CONNS", "5"))
|
||||
if err != nil || maxConns < 1 || maxConns > 50 {
|
||||
return cfg, fmt.Errorf("invalid DB_MAX_CONNS")
|
||||
}
|
||||
cfg.MaxConns = int32(maxConns)
|
||||
|
||||
cfg.DatabaseURL, err = getenvOrFile("DATABASE_URL", "DATABASE_URL_FILE")
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
cfg.RedisURL, err = getenvOrFile("REDIS_URL", "CACHE_URL_FILE")
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
// X-Instance-Id стабилен на жизнь процесса. В Compose hostname = id контейнера,
|
||||
// поэтому stop-one.sh сопоставляет TARGET_INSTANCE_ID с Config.Hostname.
|
||||
cfg.InstanceID = strings.TrimSpace(os.Getenv("INSTANCE_ID"))
|
||||
if cfg.InstanceID == "" {
|
||||
host, herr := os.Hostname()
|
||||
if herr != nil || strings.TrimSpace(host) == "" {
|
||||
return cfg, fmt.Errorf("set INSTANCE_ID or ensure hostname is available")
|
||||
}
|
||||
cfg.InstanceID = host
|
||||
}
|
||||
|
||||
// Миграции по умолчанию выключены у API-реплик: их гоняет одноразовый сервис migrate.
|
||||
// Для локальных тестов и -migrate флага включается явно.
|
||||
cfg.RunMigrations = truthy(os.Getenv("RUN_MIGRATIONS"))
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Addr — адрес Listen, обычно 0.0.0.0:8080 внутри контейнера.
|
||||
func (c Config) Addr() string {
|
||||
return fmt.Sprintf("%s:%d", c.Host, c.Port)
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getenvOrFile(directKey, fileKey string) (string, error) {
|
||||
if v := strings.TrimSpace(os.Getenv(directKey)); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
path := strings.TrimSpace(os.Getenv(fileKey))
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("set %s or %s", directKey, fileKey)
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", fileKey, err)
|
||||
}
|
||||
v := strings.TrimSpace(string(b))
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("%s is empty", fileKey)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func truthy(v string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Package session хранит opaque Bearer-сессии в Redis.
|
||||
//
|
||||
// PostgreSQL остаётся источником истины для пользователей и сообщений.
|
||||
// Сессия — отдельная роль: случайный токен, срок жизни SESSION_TTL_SECONDS и отзыв.
|
||||
// В Redis лежит не сам токен, а его SHA-256: дамп AOF не содержит значение,
|
||||
// которое клиент предъявляет в Authorization.
|
||||
//
|
||||
// TTL ключа равен оставшемуся сроку сессии. Рестарт API его не продлевает.
|
||||
// Рестарт Redis сессию сохраняет только потому, что включён AOF на volume.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
)
|
||||
|
||||
// Store — клиент Redis с короткими таймаутами.
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// Open разбирает redis:// URL. Пароль в лог не пишется.
|
||||
func Open(redisURL string, ttl time.Duration) (*Store, error) {
|
||||
opt, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||
}
|
||||
opt.DialTimeout = 500 * time.Millisecond
|
||||
opt.ReadTimeout = 500 * time.Millisecond
|
||||
opt.WriteTimeout = 500 * time.Millisecond
|
||||
opt.PoolSize = 20
|
||||
client := redis.NewClient(opt)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{client: client, ttl: ttl}, nil
|
||||
}
|
||||
|
||||
// Close закрывает пул при остановке процесса.
|
||||
func (s *Store) Close() error {
|
||||
return s.client.Close()
|
||||
}
|
||||
|
||||
// Ping — готовность кэша сессий. Недоступный Redis не означает «анонимный доступ».
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Issue выпускает 256 бит случайности (32 байта) и кладёт сессию с TTL.
|
||||
// Наружу уходит hex (64 символа). В Redis — только хеш.
|
||||
func (s *Store) Issue(ctx context.Context, userID uuid.UUID) (token string, expiresAt time.Time, err error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err = rand.Read(buf); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token = hex.EncodeToString(buf)
|
||||
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Millisecond)
|
||||
value := userID.String() + "|" + expiresAt.Format(time.RFC3339Nano)
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
if err = s.client.Set(ctx, key(token), value, time.Until(expiresAt)).Err(); err != nil {
|
||||
return "", time.Time{}, ErrUnavailable
|
||||
}
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
// Lookup возвращает владельца живой сессии.
|
||||
// Промах и истёкший срок — ErrUnauthorized. Сбой Redis — ErrUnavailable (HTTP 503).
|
||||
func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
raw, err := s.client.Get(ctx, key(token)).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrUnavailable
|
||||
}
|
||||
userPart, expPart, ok := strings.Cut(raw, "|")
|
||||
if !ok {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
exp, err := time.Parse(time.RFC3339Nano, expPart)
|
||||
if err != nil || !exp.After(time.Now()) {
|
||||
_ = s.client.Del(ctx, key(token)).Err()
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
id, err := uuid.Parse(userPart)
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// Revoke удаляет текущую сессию. Повторный отзыв — это уже отсутствие ключа.
|
||||
func (s *Store) Revoke(ctx context.Context, token string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
n, err := s.client.Del(ctx, key(token)).Result()
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func key(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "sess:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFS embed.FS
|
||||
|
||||
// Migrate применяет встроенные SQL-файлы по одному разу.
|
||||
// Повторный старт процесса не создаёт вторую копию строк: версия пишется в schema_migrations.
|
||||
func (s *Store) Migrate(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
if _, err := s.pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`); err != nil {
|
||||
return fmt.Errorf("schema_migrations: %w", err)
|
||||
}
|
||||
entries, err := migrationFS.ReadDir("migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() && strings.HasSuffix(e.Name(), ".sql") {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
body, err := migrationFS.ReadFile("migrations/" + name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// pgx в extended protocol не выполняет несколько команд одним Exec.
|
||||
for _, stmt := range splitSQL(string(body)) {
|
||||
if _, err := tx.Exec(ctx, stmt); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("migrate %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// splitSQL делит файл миграции по ';'. В этих файлах нет строк с точкой с запятой внутри литералов.
|
||||
func splitSQL(body string) []string {
|
||||
parts := strings.Split(body, ";")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
stmt := strings.TrimSpace(part)
|
||||
if stmt == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, stmt)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
-- Схема lab2. PostgreSQL — источник истины для пользователей, чатов и сообщений.
|
||||
-- Сессии здесь намеренно нет: их держит Redis с AOF, TTL не продлевается рестартом API.
|
||||
-- Повторный запуск безопасен: все объекты создаются через IF NOT EXISTS.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
-- Argon2id PHC-строка. Не SHA-256 и не plaintext. Наружу не отдаётся.
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT users_username_unique UNIQUE (username)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
-- Составной первичный ключ не даёт вставить участника дважды.
|
||||
-- Внешние ключи не дают сослаться на несуществующего пользователя или чат.
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
-- Список чатов пользователя начинается с фильтра «где я участник».
|
||||
CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members (user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
sender_id uuid NOT NULL REFERENCES users (id),
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
-- Keyset истории: WHERE chat_id = ? AND (created_at, id) > (?, ?) ORDER BY created_at, id.
|
||||
-- Составной индекс покрывает и фильтр, и порядок. Слабый индекс только по chat_id
|
||||
-- заставил бы сортировать историю чата. Его нет в продовой схеме, он появляется
|
||||
-- лишь на время эксперимента трека 2.
|
||||
CREATE INDEX IF NOT EXISTS messages_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Идемпотентность POST сообщения (lab3).
|
||||
-- Область ключа: (user_id, method, path, key).
|
||||
-- Разные пользователи и чаты могут независимо использовать одну строку Idempotency-Key.
|
||||
-- request_hash — SHA-256 канонического тела.
|
||||
-- Другой body при том же ключе даёт HTTP 409.
|
||||
-- response_* фиксируются только для успешного 201 в той же транзакции, что и INSERT messages.
|
||||
-- Транзиентный 5xx не сохраняется как окончательный результат.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
method text NOT NULL,
|
||||
path text NOT NULL,
|
||||
key text NOT NULL,
|
||||
request_hash text NOT NULL,
|
||||
response_status integer NOT NULL,
|
||||
response_body jsonb NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages (id),
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, method, path, key)
|
||||
);
|
||||
|
||||
-- Индекс по времени — для будущей очистки хвоста старше 24 часов.
|
||||
CREATE INDEX IF NOT EXISTS idempotency_keys_created_idx ON idempotency_keys (created_at);
|
||||
@@ -0,0 +1,641 @@
|
||||
// Package store — пользователи, чаты, сообщения и ключи идемпотентности в PostgreSQL.
|
||||
//
|
||||
// Источник истины — только эти таблицы. Память процесса после рестарта пуста,
|
||||
// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2):
|
||||
// текст сообщения не склеивается в SQL.
|
||||
//
|
||||
// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе
|
||||
// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка
|
||||
// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке).
|
||||
//
|
||||
// Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики:
|
||||
// два параллельных POST с одним ключом через разные API-контейнеры видят один PK.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab3/internal/auth"
|
||||
)
|
||||
|
||||
const queryTimeout = 3 * time.Second
|
||||
|
||||
// Ошибки домена. HTTP-слой переводит их в коды контракта и не показывает SQL.
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
// ErrIdempotencyConflict — тот же ключ, но другое тело запроса.
|
||||
ErrIdempotencyConflict = errors.New("idempotency conflict")
|
||||
)
|
||||
|
||||
// User — публичные поля пользователя. Hash пароля в эту структуру не попадает.
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Chat — чат и явный состав участников.
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Message — одно подтверждённое сообщение. sender_id назначает сервер.
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api.
|
||||
type PageCursor struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
Scope string
|
||||
}
|
||||
|
||||
// Store — пул соединений. Пул ограничен, у каждого запроса свой таймаут.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
hasher *auth.Hasher
|
||||
}
|
||||
|
||||
// Open поднимает пул. ConnectTimeout короткий, чтобы недоступная БД быстро стала 503,
|
||||
// а не висела до клиентского таймаута теста.
|
||||
// maxConns — на одну реплику; при N репликах суммарный пул ≈ N*maxConns.
|
||||
func Open(ctx context.Context, databaseURL string, hasher *auth.Hasher, maxConns int32) (*Store, error) {
|
||||
if maxConns < 1 {
|
||||
maxConns = 5
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database url: %w", err)
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
||||
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
// UTC, чтобы timestamptz читался так же, как мы его записали.
|
||||
// statement_timeout обрывает запрос, который внезапно решил сканировать всё.
|
||||
_, err := conn.Exec(ctx, `SET TIME ZONE 'UTC'; SET statement_timeout = '3s'`)
|
||||
return err
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{pool: pool, hasher: hasher}, nil
|
||||
}
|
||||
|
||||
// Close освобождает соединения при остановке процесса.
|
||||
func (s *Store) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
// Ping — проверка для /health/ready. Ошибка здесь значит «не готов», не «жив».
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateUser пишет пользователя. Повтор username → ErrConflict благодаря UNIQUE.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
||||
hash, err := auth.Hash(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u := &User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, hash, u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// Authenticate проверяет Basic-логин. Нет пользователя и неверный пароль
|
||||
// выглядят одинаково: оба дают false без отдельной ошибки «такого логина нет».
|
||||
func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var u User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = $1`, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
s.hasher.Burn(password)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if !s.hasher.Verify(hash, password) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// GetUser нужен, чтобы ответ /users/me совпал с объектом из регистрации.
|
||||
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var u User
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// CreateChat атомарно создаёт чат и состав. Неизвестный участник откатывает всё:
|
||||
// в таблице chats не остаётся «пустой» строки без полного состава.
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (*Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
chat := &Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
for _, uid := range memberIDs {
|
||||
// INSERT ... SELECT вставит 0 строк, если пользователя нет, и не нарушит FK.
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, id FROM users WHERE id = $2`, chat.ID, uid)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
// GetChat возвращает чат только участнику. Чужому — ErrNotFound (HTTP 404, не 403).
|
||||
func (s *Store) GetChat(ctx context.Context, chatID, userID uuid.UUID) (*Chat, error) {
|
||||
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.loadChat(ctx, chatID)
|
||||
}
|
||||
|
||||
// ListChats — keyset по (created_at, id) только среди чатов этого пользователя.
|
||||
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, after *PageCursor) ([]Chat, *PageCursor, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2`, userID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1
|
||||
AND (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []Chat
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
items = append(items, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
next, items := trimPage(items, limit, func(c Chat) (time.Time, uuid.UUID) {
|
||||
return c.CreatedAt, c.ID
|
||||
})
|
||||
for i := range items {
|
||||
members, err := s.memberIDs(ctx, items[i].ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
items[i].MemberIDs = members
|
||||
}
|
||||
var cursor *PageCursor
|
||||
if next {
|
||||
last := items[len(items)-1]
|
||||
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return items, cursor, nil
|
||||
}
|
||||
|
||||
// CreateMessage пишет сообщение только если отправитель состоит в чате.
|
||||
// Подтверждение — это COMMIT строки. Следующее чтение видит её без кэша истории.
|
||||
// Без идемпотентности — только для внутренних/тестовых случаев; HTTP использует CreateMessageIdempotent.
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (*Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3
|
||||
)`, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// IdempotentMessage — либо только что созданное, либо ранее сохранённое по ключу сообщение.
|
||||
type IdempotentMessage struct {
|
||||
Message *Message
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу.
|
||||
//
|
||||
// Алгоритм (общая БД, любые реплики):
|
||||
// 1. BEGIN;
|
||||
// 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов
|
||||
// ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения;
|
||||
// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message;
|
||||
// 4. иначе INSERT message + INSERT idempotency_keys в той же транзакции;
|
||||
// 5. COMMIT (advisory lock снимается вместе с транзакцией).
|
||||
//
|
||||
// Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает:
|
||||
// запись ключа только после успешной подготовки 201.
|
||||
func (s *Store) CreateMessageIdempotent(
|
||||
ctx context.Context,
|
||||
chatID, senderID uuid.UUID,
|
||||
text string,
|
||||
method, path, idemKey, requestHash string,
|
||||
) (*IdempotentMessage, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
lockKey := idempotencyLockKey(senderID, method, path, idemKey)
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockKey); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
var (
|
||||
storedHash string
|
||||
msgID uuid.UUID
|
||||
msgChat uuid.UUID
|
||||
msgSender uuid.UUID
|
||||
msgText string
|
||||
msgCreated time.Time
|
||||
)
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT i.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM idempotency_keys i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1 AND i.method = $2 AND i.path = $3 AND i.key = $4`,
|
||||
senderID, method, path, idemKey,
|
||||
).Scan(&storedHash, &msgID, &msgChat, &msgSender, &msgText, &msgCreated)
|
||||
if err == nil {
|
||||
if storedHash != requestHash {
|
||||
return nil, ErrIdempotencyConflict
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &IdempotentMessage{
|
||||
Message: &Message{
|
||||
ID: msgID,
|
||||
ChatID: msgChat,
|
||||
SenderID: msgSender,
|
||||
Text: msgText,
|
||||
CreatedAt: msgCreated,
|
||||
},
|
||||
Replayed: true,
|
||||
}, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
var member int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
// response_body заполняем каноническим Message JSON уже здесь, чтобы replay
|
||||
// не зависел от повторной сериализации в HTTP-слое с другим порядком полей.
|
||||
bodyJSON, err := json.Marshal(map[string]any{
|
||||
"id": msg.ID.String(),
|
||||
"chat_id": msg.ChatID.String(),
|
||||
"sender_id": msg.SenderID.String(),
|
||||
"text": msg.Text,
|
||||
"created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `
|
||||
INSERT INTO idempotency_keys (
|
||||
user_id, method, path, key, request_hash,
|
||||
response_status, response_body, message_id, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
||||
senderID, method, path, idemKey, requestHash,
|
||||
201, bodyJSON, msg.ID, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &IdempotentMessage{Message: msg, Replayed: false}, nil
|
||||
}
|
||||
|
||||
// idempotencyLockKey — стабильный int64 для pg_advisory_xact_lock из области ключа.
|
||||
func idempotencyLockKey(userID uuid.UUID, method, path, key string) int64 {
|
||||
sum := sha256.Sum256([]byte(userID.String() + "|" + method + "|" + path + "|" + key))
|
||||
return int64(binary.BigEndian.Uint64(sum[:8]))
|
||||
}
|
||||
|
||||
// ListMessages — keyset по индексу messages_history_idx. Берём limit+1 строку,
|
||||
// чтобы next_cursor был null, когда следующей записи уже нет.
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limit int, after *PageCursor) ([]Message, *PageCursor, error) {
|
||||
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, 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(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Message
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) {
|
||||
return m.CreatedAt, m.ID
|
||||
})
|
||||
var cursor *PageCursor
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return items, cursor, nil
|
||||
}
|
||||
|
||||
// ChatExistsForTitle помогает тесту отката: после ошибки создания чата строки нет.
|
||||
func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var n int
|
||||
err := s.pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&n)
|
||||
if err != nil {
|
||||
return 0, mapWriteErr(err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (s *Store) ensureMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var one int
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&one)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) loadChat(ctx context.Context, chatID uuid.UUID) (*Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var c Chat
|
||||
err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, chatID).
|
||||
Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
c.MemberIDs, err = s.memberIDs(ctx, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (s *Store) memberIDs(ctx context.Context, chatID uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id`, chatID)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []uuid.UUID
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
func trimPage[T any](items []T, limit int, _ func(T) (time.Time, uuid.UUID)) (bool, []T) {
|
||||
if len(items) > limit {
|
||||
return true, items[:limit]
|
||||
}
|
||||
return false, items
|
||||
}
|
||||
|
||||
func nowUTC() time.Time {
|
||||
// Миллисекунда — точность, которую мы же и печатаем в JSON.
|
||||
return time.Now().UTC().Truncate(time.Millisecond)
|
||||
}
|
||||
|
||||
func mapWriteErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return ErrConflict
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || isConn(err) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isConn(err error) bool {
|
||||
msg := err.Error()
|
||||
// Не логируем и не возвращаем клиенту эту строку. Здесь только классификация.
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return false
|
||||
default:
|
||||
if stringsContains(msg, "connection refused") ||
|
||||
stringsContains(msg, "failed to connect") ||
|
||||
stringsContains(msg, "conn closed") ||
|
||||
stringsContains(msg, "closed pool") ||
|
||||
stringsContains(msg, "broken pipe") ||
|
||||
stringsContains(msg, "connection reset") ||
|
||||
stringsContains(msg, "SQLSTATE 57P01") ||
|
||||
stringsContains(msg, "SQLSTATE 08006") ||
|
||||
stringsContains(msg, "SQLSTATE 08001") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func stringsContains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (s == sub || len(sub) == 0 ||
|
||||
(func() bool { return contains(s, sub) })())
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Перезапуск API (всех реплик), LB и обоих хранилищ без удаления volumes.
|
||||
# Важно: именно restart, а не up -d — иначе PID/StartedAt у живых контейнеров не меняются.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
docker compose --env-file .env restart postgres redis api lb
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# Поднимает недостающие / остановленные API-реплики до API_REPLICAS после stop-one.
|
||||
# Не трогает volumes и не делает down -v. Миграции уже применены — не пересоздаём migrate.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
API_REPLICAS=$(grep -E '^API_REPLICAS=' .env 2>/dev/null | cut -d= -f2- || true)
|
||||
API_REPLICAS=${API_REPLICAS:-2}
|
||||
|
||||
# Стартуем остановленные контейнеры сервиса api и добираем scale при нехватке.
|
||||
docker compose --env-file .env start api 2>/dev/null || true
|
||||
docker compose --env-file .env up -d --no-deps --scale "api=${API_REPLICAS}" api
|
||||
|
||||
deadline=$(( $(date +%s) + 90 ))
|
||||
while :; do
|
||||
if curl -fsS "http://127.0.0.1:8080/health/ready" >/dev/null 2>&1; then
|
||||
# Ждём, пока LB реально видит ≥2 instance id (не только один backend).
|
||||
ids=$(
|
||||
python3 - <<'PY'
|
||||
import urllib.request
|
||||
ids=set()
|
||||
for _ in range(24):
|
||||
try:
|
||||
with urllib.request.urlopen('http://127.0.0.1:8080/health/live', timeout=1) as r:
|
||||
i=r.headers.get('X-Instance-Id')
|
||||
if i: ids.add(i)
|
||||
except Exception:
|
||||
pass
|
||||
print(len(ids))
|
||||
PY
|
||||
)
|
||||
if [ "$ids" -ge 2 ] || [ "$API_REPLICAS" -lt 2 ]; then
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
if [ "$(date +%s)" -ge "$deadline" ]; then
|
||||
echo "restore timeout (replicas visible via LB: ${ids:-0})" >&2
|
||||
docker compose --env-file .env ps >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/bin/sh
|
||||
# Трек 1 lab3: цена масштабирования при фиксированном суммарном CPU/RAM.
|
||||
#
|
||||
# Гипотеза: при фиксированном бюджете (2.0 CPU / 1024 MiB на все API) рост N
|
||||
# 1→2 помогает; 2→4 упирается в PostgreSQL/пул/LB. На практике на одном
|
||||
# Docker-host один «толстый» процесс часто быстрее нарезки того же бюджета —
|
||||
# это тоже результат эксперимента (см. evidence/track1/summary.md).
|
||||
#
|
||||
# Методика: один bootstrap стенда, дальше только rescale api+lb (без down -v),
|
||||
# стабильный ready, tests/load.py 30с concurrency=8. Затем grow при N=2.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
OUT=evidence/track1
|
||||
mkdir -p "$OUT"
|
||||
python3 -m pip install -q -r requirements-dev.txt >/dev/null 2>&1 || true
|
||||
|
||||
cp .env.example .env
|
||||
docker compose --env-file .env down --remove-orphans >/dev/null 2>&1 || true
|
||||
bash scripts/up.sh
|
||||
|
||||
rescale() {
|
||||
n="$1"
|
||||
cpus="$2"
|
||||
mem="$3"
|
||||
tmp=$(mktemp)
|
||||
sed -e "s/^API_REPLICAS=.*/API_REPLICAS=$n/" \
|
||||
-e "s/^API_CPUS=.*/API_CPUS=$cpus/" \
|
||||
-e "s/^API_MEMORY=.*/API_MEMORY=$mem/" \
|
||||
-e "s/^DB_MAX_CONNS=.*/DB_MAX_CONNS=5/" \
|
||||
.env.example > "$tmp"
|
||||
mv "$tmp" .env
|
||||
docker compose --env-file .env stop api >/dev/null 2>&1 || true
|
||||
docker compose --env-file .env rm -f api >/dev/null 2>&1 || true
|
||||
docker compose --env-file .env up -d --no-deps --scale "api=${n}" api
|
||||
docker compose --env-file .env up -d --no-deps --force-recreate lb
|
||||
ok=0
|
||||
tries=0
|
||||
while [ "$ok" -lt 10 ]; do
|
||||
tries=$((tries+1))
|
||||
if [ "$tries" -gt 120 ]; then
|
||||
echo "warmup timeout n=$n" >&2
|
||||
docker compose --env-file .env ps >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
if curl -fsS "http://127.0.0.1:8080/health/ready" >/dev/null 2>&1; then
|
||||
ok=$((ok+1))
|
||||
else
|
||||
ok=0
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
}
|
||||
|
||||
run_one() {
|
||||
n="$1"
|
||||
cpus="$2"
|
||||
mem="$3"
|
||||
label="$4"
|
||||
echo "=== track1 $label replicas=$n cpus_each=$cpus mem_each=$mem ==="
|
||||
rescale "$n" "$cpus" "$mem"
|
||||
out="$OUT/${label}.json"
|
||||
python3 tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 8 --output "$out"
|
||||
docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.MemUsage}}' > "$OUT/${label}.stats.txt" || true
|
||||
docker compose --env-file .env ps > "$OUT/${label}.ps.txt" || true
|
||||
echo "saved $out"
|
||||
}
|
||||
|
||||
run_one 1 2.00 1024M fixed_budget_n1
|
||||
run_one 2 1.00 512M fixed_budget_n2
|
||||
run_one 4 0.50 256M fixed_budget_n4
|
||||
run_one 2 0.50 256M grow_n2_small
|
||||
run_one 2 1.00 512M grow_n2_medium
|
||||
run_one 2 1.50 768M grow_n2_large
|
||||
|
||||
python3 scripts/summarize_track1.py
|
||||
cp .env.example .env
|
||||
bash scripts/up.sh >/dev/null
|
||||
echo "track1 done → $OUT; stand restored to API_REPLICAS=2"
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/sh
|
||||
# Останавливает РОВНО одну API-реплику, чей X-Instance-Id = TARGET_INSTANCE_ID.
|
||||
# Реплика остаётся остановленной; восстановление — scripts/restore-one.sh или compose up.
|
||||
# Не трогает postgres/redis/lb/volumes. Должен завершиться за <10 с.
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
ids=$(docker compose --env-file .env ps -q api)
|
||||
if [ -z "$ids" ]; then
|
||||
echo "no api containers" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
found=0
|
||||
for id in $ids; do
|
||||
# Совпадает с config.InstanceID: hostname контейнера, если INSTANCE_ID не задан.
|
||||
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$id")
|
||||
env_id=$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$id" | sed -n 's/^INSTANCE_ID=//p' | head -n1)
|
||||
match=$hostname
|
||||
if [ -n "$env_id" ]; then
|
||||
match=$env_id
|
||||
fi
|
||||
if [ "$match" = "$TARGET_INSTANCE_ID" ]; then
|
||||
# Явный stop контейнера; restart: "no" у api гарантирует, что он не вернётся сам.
|
||||
docker stop -t 8 "$id" >/dev/null
|
||||
# Подтверждаем, что контейнер действительно не running — иначе failover-тест врёт.
|
||||
state=$(docker inspect -f '{{.State.Running}}' "$id")
|
||||
if [ "$state" = "true" ]; then
|
||||
echo "container still running after stop" >&2
|
||||
exit 1
|
||||
fi
|
||||
found=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$found" -ne 1 ]; then
|
||||
echo "TARGET_INSTANCE_ID not found among api replicas" >&2
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сводка JSON-прогонов трека 1 в evidence/track1/summary.md и summary.json."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence" / "track1"
|
||||
|
||||
ORDER = [
|
||||
"fixed_budget_n1",
|
||||
"fixed_budget_n2",
|
||||
"fixed_budget_n4",
|
||||
"grow_n2_small",
|
||||
"grow_n2_medium",
|
||||
"grow_n2_large",
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
rows = []
|
||||
for name in ORDER:
|
||||
path = OUT / f"{name}.json"
|
||||
if not path.exists():
|
||||
continue
|
||||
data = json.loads(path.read_text())
|
||||
rows.append(
|
||||
{
|
||||
"label": name,
|
||||
"successful_rps": data.get("successful_rps"),
|
||||
"error_ratio": data.get("error_ratio"),
|
||||
"p50_ms": (data.get("successful_latency_ms") or {}).get("p50"),
|
||||
"p95_ms": (data.get("successful_latency_ms") or {}).get("p95"),
|
||||
"p99_ms": (data.get("successful_latency_ms") or {}).get("p99"),
|
||||
"successful_requests": data.get("successful_requests"),
|
||||
"failed_requests": data.get("failed_requests"),
|
||||
"concurrency": data.get("concurrency"),
|
||||
"elapsed_seconds": data.get("elapsed_seconds"),
|
||||
}
|
||||
)
|
||||
summary = {"runs": rows}
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
(OUT / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
lines = [
|
||||
"# Track 1 summary",
|
||||
"",
|
||||
"Closed-loop `tests/load.py` (duration=30, concurrency=8). RPS — только успешные HTTP 201.",
|
||||
"",
|
||||
"| label | RPS | err_ratio | p50 ms | p95 ms | p99 ms | ok | fail |",
|
||||
"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
|
||||
]
|
||||
for r in rows:
|
||||
lines.append(
|
||||
"| {label} | {successful_rps} | {error_ratio} | {p50_ms} | {p95_ms} | {p99_ms} | {successful_requests} | {failed_requests} |".format(
|
||||
**r
|
||||
)
|
||||
)
|
||||
lines.append("")
|
||||
(OUT / "summary.md").write_text("\n".join(lines) + "\n")
|
||||
print((OUT / "summary.md").read_text())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
# Единая последовательность запуска стенда lab3.
|
||||
# 1) postgres+redis 2) однократные миграции 3) API×N 4) HAProxy
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
cp .env.example .env
|
||||
echo "created .env from .env.example" >&2
|
||||
fi
|
||||
|
||||
API_REPLICAS=$(grep -E '^API_REPLICAS=' .env | cut -d= -f2- || true)
|
||||
API_REPLICAS=${API_REPLICAS:-2}
|
||||
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build postgres redis
|
||||
docker compose --env-file .env run --rm --build migrate
|
||||
docker compose --env-file .env up -d --build --scale "api=${API_REPLICAS}" --no-deps api
|
||||
docker compose --env-file .env up -d --no-deps lb
|
||||
|
||||
echo "waiting for http://127.0.0.1:8080/health/ready via LB..."
|
||||
deadline=$(( $(date +%s) + 120 ))
|
||||
while :; do
|
||||
if curl -fsS "http://127.0.0.1:8080/health/ready" >/dev/null 2>&1; then
|
||||
echo "ready"
|
||||
docker compose --env-file .env ps
|
||||
exit 0
|
||||
fi
|
||||
if [ "$(date +%s)" -ge "$deadline" ]; then
|
||||
echo "timeout waiting for readiness" >&2
|
||||
docker compose --env-file .env ps >&2 || true
|
||||
docker compose --env-file .env logs --tail=80 api lb >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
@@ -0,0 +1,653 @@
|
||||
// Собственные проверки lab3 (плюс регрессия lab2). Им нужен уже поднятый
|
||||
// PostgreSQL и Redis (docker compose up / scripts/up.sh): контракт требует
|
||||
// настоящую БД, а не sqlmock. HTTP бьём в httptest.Server поверх того же Store,
|
||||
// что и реплики — идемпотентность и гонки видны без обхода LB.
|
||||
//
|
||||
// Каждый тест пишет в лог, что именно проверяет и какой статус получил.
|
||||
package studenttests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab3/internal/api"
|
||||
"mtusi2026lab3/internal/auth"
|
||||
"mtusi2026lab3/internal/session"
|
||||
"mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
var (
|
||||
sharedStore *store.Store
|
||||
sharedSessions *session.Store
|
||||
sharedRedisURL string
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||||
sharedRedisURL = getenv("REDIS_URL", "redis://127.0.0.1:6379/0")
|
||||
hasher, err := auth.NewHasher()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "hasher:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
sharedStore, err = store.Open(ctx, dsn, hasher, 5)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "postgres:", err)
|
||||
fmt.Fprintln(os.Stderr, "подсказка: docker compose --env-file .env up -d --build")
|
||||
os.Exit(1)
|
||||
}
|
||||
defer sharedStore.Close()
|
||||
if err := sharedStore.Migrate(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "migrate:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// Повтор миграции не должен падать и не должен дублировать данные.
|
||||
if err := sharedStore.Migrate(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "migrate second:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
sharedSessions, err = session.Open(sharedRedisURL, time.Hour)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "redis:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer sharedSessions.Close()
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestMalformedJSONAndValidation(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат")
|
||||
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, "{")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest || !strings.Contains(body, "invalid_request") {
|
||||
t.Fatalf("malformed json: status=%d body=%s", status, body)
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/users", nil,
|
||||
`{"username":"abc","display_name":"Имя","password":"correct-horse-1","extra":1}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("extra field: status=%d", status)
|
||||
}
|
||||
|
||||
user := register(t, srv, "ok_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Чат проверки")
|
||||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||
|
||||
// Decoder.More() это не ловит: один объект декодируется, лишняя скобка остаётся.
|
||||
for _, raw := range []string{`{"text":"valid"}}`, `{"text":"valid"}]`} {
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, raw)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("trailing garbage %q: status=%d body=%s", raw, status, body)
|
||||
}
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":" "}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("blank message: status=%d", status)
|
||||
}
|
||||
|
||||
outsider := register(t, srv, "outsider")
|
||||
outTok := login(t, srv, outsider.username, outsider.password)
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{"Authorization": "Bearer " + outTok}, `{"text":"чужое"}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign chat: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "валидация JSON, хвоста, пустого текста и чужого чата")
|
||||
}
|
||||
|
||||
func TestMessageTextPreservedAndLengthOnOriginal(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "пробелы по краям сохраняются; длина считается по исходному тексту")
|
||||
user := register(t, srv, "text_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Текст")
|
||||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||
|
||||
original := " строка\nс пробелами "
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||||
fmt.Sprintf(`{"text":%q}`, original))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("preserve spaces: status=%d", status)
|
||||
}
|
||||
got := decode(t, body)
|
||||
if got["text"] != original {
|
||||
t.Fatalf("text mutated: got %q want %q", got["text"], original)
|
||||
}
|
||||
|
||||
tooLong := " " + strings.Repeat("a", 4000) // 4001 code points
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||||
fmt.Sprintf(`{"text":%q}`, tooLong))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("length after trim bypass: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "текст сохранён целиком, обход лимита через TrimSpace закрыт")
|
||||
}
|
||||
|
||||
func TestSessionRejectsJSONBody(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "POST /auth/sessions с телом должен быть 400 даже при верном Basic")
|
||||
user := register(t, srv, "body_user")
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, `{"extra":1}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("session with body: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "вход без JSON body")
|
||||
}
|
||||
|
||||
func TestWrongPasswordLogoutAndIgnoredUserHeader(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "неверный пароль, Basic на бизнес-методе, X-User-Id, logout")
|
||||
user := register(t, srv, "auth_user")
|
||||
other := register(t, srv, "auth_other")
|
||||
|
||||
status, body, hdr := doRaw(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, "wrong-password-1"),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Basic") {
|
||||
t.Fatalf("wrong password: status=%d www=%q", status, hdr.Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
token := login(t, srv, user.username, user.password)
|
||||
status, body, hdr = doRaw(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Bearer") {
|
||||
t.Fatalf("basic on business endpoint: status=%d www=%q", status, hdr.Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"X-User-Id": user.id}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("X-User-Id alone: status=%d", status)
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
"X-User-Id": other.id,
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusOK || !strings.Contains(body, user.id) || strings.Contains(body, other.id) {
|
||||
t.Fatalf("X-User-Id overrode bearer: status=%d body=%s", status, body)
|
||||
}
|
||||
|
||||
status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||
t.Logf("logout status=%d", status)
|
||||
if status != http.StatusNoContent {
|
||||
t.Fatalf("logout status=%d", status)
|
||||
}
|
||||
status, _ = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("token still valid after logout: %d", status)
|
||||
}
|
||||
status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("second logout status=%d", status)
|
||||
}
|
||||
logOK(t, "пароль, заголовки и отзыв сессии")
|
||||
}
|
||||
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
srv := newAPI(t, 2*time.Second)
|
||||
defer srv.Close()
|
||||
logStep(t, "SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается")
|
||||
user := register(t, srv, "ttl_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
time.Sleep(2500 * time.Millisecond)
|
||||
status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("expired token status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "истёкшая сессия отклонена")
|
||||
}
|
||||
|
||||
func TestDuplicateUsernameRace(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
name := "race_" + uuid.NewString()[:8]
|
||||
logStep(t, "8 параллельных регистраций username="+name)
|
||||
const n = 8
|
||||
codes := make([]int, n)
|
||||
var wg sync.WaitGroup
|
||||
body := fmt.Sprintf(`{"username":%q,"display_name":"Гонка","password":"correct-horse-1"}`, name)
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
status, _ := do(t, srv, http.MethodPost, "/api/v1/users", nil, body)
|
||||
codes[i] = status
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
ok, conflict := 0, 0
|
||||
for _, c := range codes {
|
||||
switch c {
|
||||
case http.StatusCreated:
|
||||
ok++
|
||||
case http.StatusConflict:
|
||||
conflict++
|
||||
default:
|
||||
t.Errorf("unexpected status %d", c)
|
||||
}
|
||||
}
|
||||
t.Logf("created=%d conflict=%d", ok, conflict)
|
||||
if ok != 1 || conflict != n-1 {
|
||||
t.Fatalf("race result created=%d conflict=%d", ok, conflict)
|
||||
}
|
||||
logOK(t, "UNIQUE username выдержал гонку")
|
||||
}
|
||||
|
||||
func TestChatCreateRollsBack(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
user := register(t, srv, "roll_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
title := "rollback-" + uuid.NewString()
|
||||
missing := uuid.NewString()
|
||||
logStep(t, "создание чата с несуществующим участником должно откатиться, title="+title)
|
||||
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q,%q]}`, title, user.id, missing)
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d", status)
|
||||
}
|
||||
n, err := sharedStore.CountChatsByTitle(context.Background(), title)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("строк chats с этим title после ошибки: %d", n)
|
||||
if n != 0 {
|
||||
t.Fatalf("chat row survived rollback: %d", n)
|
||||
}
|
||||
logOK(t, "транзакция создания чата откатилась")
|
||||
}
|
||||
|
||||
func TestPaginationPages(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "три сообщения, две страницы limit=2, затем последняя")
|
||||
user := register(t, srv, "page_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Страницы")
|
||||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||
for _, text := range []string{"раз", "два", "три"} {
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, fmt.Sprintf(`{"text":%q}`, text))
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("post message %s: %d %s", text, status, body)
|
||||
}
|
||||
}
|
||||
status, body := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2", auth, "")
|
||||
logResult(t, status, body)
|
||||
page := decode(t, body)
|
||||
items, _ := page["items"].([]any)
|
||||
if status != http.StatusOK || len(items) != 2 || page["next_cursor"] == nil {
|
||||
t.Fatalf("page1: %+v", page)
|
||||
}
|
||||
cursor, _ := page["next_cursor"].(string)
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2&cursor="+cursor, auth, "")
|
||||
logResult(t, status, body)
|
||||
page = decode(t, body)
|
||||
items, _ = page["items"].([]any)
|
||||
if len(items) != 1 || page["next_cursor"] != nil {
|
||||
t.Fatalf("page2: %+v", page)
|
||||
}
|
||||
logOK(t, "keyset обошёл историю без зависания cursor")
|
||||
}
|
||||
|
||||
func TestRedisDownIsNotAnonymous(t *testing.T) {
|
||||
logStep(t, "закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима")
|
||||
closed, err := session.Open(sharedRedisURL, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := closed.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(api.New(sharedStore, closed, "test-closed-redis").Handler())
|
||||
defer srv.Close()
|
||||
regSrv := newAPI(t, time.Hour)
|
||||
defer regSrv.Close()
|
||||
user := register(t, regSrv, "redis_down")
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("login with dead redis: status=%d body=%s", status, body)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Bearer " + strings.Repeat("ab", 32),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("bearer with dead redis: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "сбой Redis не стал анонимным доступом")
|
||||
}
|
||||
|
||||
func TestPostgresDownIsNotAnonymous(t *testing.T) {
|
||||
logStep(t, "закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя")
|
||||
regSrv := newAPI(t, time.Hour)
|
||||
defer regSrv.Close()
|
||||
user := register(t, regSrv, "pg_down")
|
||||
token := login(t, regSrv, user.username, user.password)
|
||||
|
||||
hasher, err := auth.NewHasher()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||||
broken, err := store.Open(context.Background(), dsn, hasher, 5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broken.Close()
|
||||
sessions, err := session.Open(sharedRedisURL, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
srv := httptest.NewServer(api.New(broken, sessions, "test-broken-pg").Handler())
|
||||
defer srv.Close()
|
||||
|
||||
status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("ready with dead postgres: %d", status)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable || strings.Contains(body, `"username"`) {
|
||||
t.Fatalf("me with dead postgres: status=%d body=%s", status, body)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("login with dead postgres: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "сбой PostgreSQL не стал анонимным доступом")
|
||||
}
|
||||
|
||||
|
||||
func TestIdempotencyReplayAndConflict(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409")
|
||||
user := register(t, srv, "idem_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Идемпотентность")
|
||||
key := "key-" + uuid.NewString()
|
||||
auth := map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
"Idempotency-Key": key,
|
||||
}
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"один раз"}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("first: %d %s", status, body)
|
||||
}
|
||||
first := decode(t, body)
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"один раз"}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("replay: %d %s", status, body)
|
||||
}
|
||||
second := decode(t, body)
|
||||
if first["id"] != second["id"] || first["text"] != second["text"] {
|
||||
t.Fatalf("replay differs: first=%v second=%v", first, second)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"другой body"}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusConflict {
|
||||
t.Fatalf("conflict: %d %s", status, body)
|
||||
}
|
||||
logOK(t, "replay и conflict по Idempotency-Key")
|
||||
}
|
||||
|
||||
func TestIdempotencyKeyRequiredAndConcurrent(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение")
|
||||
user := register(t, srv, "idem_race")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Гонка ключа")
|
||||
|
||||
// Явно без ключа: хелпер doRaw подставляет ключ только если заголовок пуст —
|
||||
// поэтому бьём в doRaw с пустым Idempotency-Key, переопределив после...
|
||||
// Проще: отдельный raw-запрос.
|
||||
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat+"/messages", strings.NewReader(`{"text":"без ключа"}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
logResult(t, resp.StatusCode, string(b))
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("missing key: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
key := "race-" + uuid.NewString()
|
||||
const n = 8
|
||||
ids := make([]string, n)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
"Idempotency-Key": key,
|
||||
}, `{"text":"параллельно"}`)
|
||||
if status != http.StatusCreated {
|
||||
t.Errorf("worker %d status=%d body=%s", i, status, body)
|
||||
return
|
||||
}
|
||||
ids[i] = decode(t, body)["id"].(string)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
uniq := map[string]struct{}{}
|
||||
for _, id := range ids {
|
||||
if id == "" {
|
||||
t.Fatalf("empty id in race")
|
||||
}
|
||||
uniq[id] = struct{}{}
|
||||
}
|
||||
t.Logf("unique message ids=%d", len(uniq))
|
||||
if len(uniq) != 1 {
|
||||
t.Fatalf("expected 1 message, got %d ids=%v", len(uniq), ids)
|
||||
}
|
||||
logOK(t, "ключ обязателен; конкурентный повтор не плодит дубли")
|
||||
}
|
||||
|
||||
func TestInstanceIDHeaderPresent(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "каждый ответ содержит непустой X-Instance-Id")
|
||||
status, body, hdr := doRaw(t, srv, http.MethodGet, "/health/live", nil, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusOK || hdr.Get("X-Instance-Id") == "" {
|
||||
t.Fatalf("live instance header missing: %q status=%d", hdr.Get("X-Instance-Id"), status)
|
||||
}
|
||||
logOK(t, "X-Instance-Id="+hdr.Get("X-Instance-Id"))
|
||||
}
|
||||
|
||||
type account struct {
|
||||
id string
|
||||
username string
|
||||
password string
|
||||
}
|
||||
|
||||
func newAPI(t *testing.T, ttl time.Duration) *httptest.Server {
|
||||
t.Helper()
|
||||
sessions, err := session.Open(sharedRedisURL, ttl)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
return httptest.NewServer(api.New(sharedStore, sessions, "test-instance").Handler())
|
||||
}
|
||||
|
||||
func register(t *testing.T, srv *httptest.Server, prefix string) account {
|
||||
t.Helper()
|
||||
username := prefix + "_" + uuid.NewString()[:8]
|
||||
password := "correct-horse-1"
|
||||
raw := fmt.Sprintf(`{"username":%q,"display_name":"Студент","password":%q}`, username, password)
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, raw)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("register %s: %d %s", username, status, body)
|
||||
}
|
||||
var u struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &u); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("создан %s id=%s", username, u.ID)
|
||||
return account{id: u.ID, username: username, password: password}
|
||||
}
|
||||
|
||||
func login(t *testing.T, srv *httptest.Server, username, password string) string {
|
||||
t.Helper()
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(username, password),
|
||||
}, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("login %s: %d %s", username, status, body)
|
||||
}
|
||||
var s struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Token) < 32 {
|
||||
t.Fatalf("token too short: %d", len(s.Token))
|
||||
}
|
||||
t.Logf("сессия выпущена, длина токена=%d (значение не печатаем)", len(s.Token))
|
||||
return s.Token
|
||||
}
|
||||
|
||||
func createChat(t *testing.T, srv *httptest.Server, token, userID, title string) string {
|
||||
t.Helper()
|
||||
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q]}`, title, userID)
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("chat: %d %s", status, body)
|
||||
}
|
||||
var c struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c.ID
|
||||
}
|
||||
|
||||
func do(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string) {
|
||||
t.Helper()
|
||||
status, body, _ := doRaw(t, srv, method, path, headers, raw)
|
||||
return status, body
|
||||
}
|
||||
|
||||
func doRaw(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string, http.Header) {
|
||||
t.Helper()
|
||||
var rdr io.Reader
|
||||
if raw != "" {
|
||||
rdr = bytes.NewBufferString(raw)
|
||||
}
|
||||
req, err := http.NewRequest(method, srv.URL+path, rdr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw != "" && method != http.MethodGet {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
// Lab3: POST сообщений без ключа — 400. В хелперах подставляем уникальный ключ,
|
||||
// если тест сам его не задал (негативные проверки ключа делают это явно).
|
||||
if method == http.MethodPost && strings.Contains(path, "/messages") && req.Header.Get("Idempotency-Key") == "" {
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(b), resp.Header
|
||||
}
|
||||
|
||||
func decode(t *testing.T, body string) map[string]any {
|
||||
t.Helper()
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func basic(user, pass string) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
|
||||
}
|
||||
|
||||
func logStep(t *testing.T, msg string) { t.Helper(); t.Logf("→ %s", msg) }
|
||||
func logOK(t *testing.T, msg string) { t.Helper(); t.Logf("✓ %s", msg) }
|
||||
func logResult(t *testing.T, status int, body string) {
|
||||
t.Helper()
|
||||
if len(body) > 400 {
|
||||
body = body[:400] + "..."
|
||||
}
|
||||
t.Logf("status=%d body=%s", status, body)
|
||||
}
|
||||
|
||||
func getenv(k, def string) string {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
Reference in New Issue
Block a user