ЛР 3 - БПИ2301 - Булла - на 4 #78
@@ -18,3 +18,4 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
app/tmp
|
||||
|
||||
+39
-8
@@ -1,13 +1,44 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# AGENT: Copy to .env for your LOCAL synthetic test environment; never commit
|
||||
# .env. compose.yaml reads these values. Only POSTGRES_PASSWORD is a secret.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
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
|
||||
DB_POOL_MAX_CONNS=10
|
||||
|
||||
# Local PostgreSQL. The API receives a full DATABASE_URL built by compose.yaml.
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=replace-with-a-local-password
|
||||
POSTGRES_DB=messenger
|
||||
|
||||
# Redis is the shared session store. AOF keeps absolute session TTLs.
|
||||
SESSION_STORE=redis
|
||||
|
||||
# HAProxy is the only public API entrypoint. API replicas use expose, not ports.
|
||||
LB_PORT=8080
|
||||
HAPROXY_STATS_PORT=8404
|
||||
|
||||
# Per-replica and other services' resource limits.
|
||||
API_REPLICAS=2
|
||||
API_CPU_LIMIT=0.50
|
||||
API_MEM_LIMIT=256M
|
||||
POSTGRES_CPU_LIMIT=1.0
|
||||
POSTGRES_MEM_LIMIT=512M
|
||||
REDIS_CPU_LIMIT=0.50
|
||||
REDIS_MEM_LIMIT=256M
|
||||
HAPROXY_CPU_LIMIT=0.50
|
||||
HAPROXY_MEM_LIMIT=128M
|
||||
|
||||
# K6 for detailed tests
|
||||
K6_VUS=10
|
||||
K6_DURATION=60
|
||||
K6_CPU_LIMIT=1.0
|
||||
K6_MEM_LIMIT=512M
|
||||
|
||||
# Optional overrides instead of the compose-generated URLs. A *_FILE value is
|
||||
# read from a file, which is how Docker/Compose secrets are usually mounted.
|
||||
# DATABASE_URL=postgres://messenger:password@localhost:5432/messenger?sslmode=disable
|
||||
# DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# CACHE_URL=redis://localhost:6379/0
|
||||
# CACHE_URL_FILE=/run/secrets/cache_url
|
||||
|
||||
@@ -1,18 +1,48 @@
|
||||
## Лабораторная 3
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
Целевая оценка: 4
|
||||
Commit/PR: ``TODO``
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
Что реализовано и что перенесено:
|
||||
|
||||
- Go/Fiber API перенесён из lab2; PostgreSQL остаётся источником истины,
|
||||
Redis хранит общие сессии.
|
||||
- Добавлены HAProxy как единственная публичная точка входа, две API-реплики
|
||||
без публикации портов, общий `X-Instance-Id` и graceful shutdown.
|
||||
- Реализована общая идемпотентность POST сообщения в PostgreSQL; миграции
|
||||
вынесены в отдельный one-shot сервис `migrate`.
|
||||
- Добавлены `scripts/restart.sh`, `scripts/stop-one.sh` и
|
||||
`scripts/rolling-update.sh`; rolling update проверен под нагрузкой k6.
|
||||
|
||||
Команды запуска из чистого clone:
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
# задать POSTGRES_PASSWORD
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build
|
||||
make wait
|
||||
make test
|
||||
```
|
||||
|
||||
Результаты проверок и ссылка на REPORT.md: `make check`, `make validate`,
|
||||
`make test`, `make test-persistence`, `make test-failover`,
|
||||
`make test-concurrency`; сводка — в `REPORT.md` и
|
||||
`evidence/grade-3-4.md`.
|
||||
|
||||
Ограничения / известные ошибки: один Docker-host; PostgreSQL, Redis и HAProxy
|
||||
остаются единичными точками отказа; TLS и вложения не входят в lab3. Ветки
|
||||
проверки пароля и «пользователь не найден» имеют разное время выполнения —
|
||||
теоретическая временная атака описана в `REPORT.md`.
|
||||
|
||||
Источники и использование ИИ: официальная документация Docker Compose,
|
||||
HAProxy, Go/Fiber; код и инфраструктура подготовлены с помощью
|
||||
DeepSeek V4.1 Flash + OpenCode.
|
||||
|
||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [ ] Контракт и публичные тесты не ослаблены.
|
||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
||||
- [ ] `make check` и `make test` выполнены; приложен реальный вывод.
|
||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
- [ ] README задания сохранён, `REPORT.md` содержит инструкцию именно этого решения.
|
||||
|
||||
+10
-2
@@ -13,6 +13,7 @@ certs/private/
|
||||
volumes/
|
||||
data/
|
||||
backups/
|
||||
|
||||
# Runtime/build artifacts
|
||||
.venv/
|
||||
__pycache__/
|
||||
@@ -28,5 +29,12 @@ coverage/
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
# Local application builds
|
||||
app/tmp/
|
||||
app/server
|
||||
|
||||
# Agent workflow artifacts
|
||||
AGENTS.md
|
||||
TASKS.md
|
||||
CHANGELOG.md
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
FROM golang:1.27.1-alpine AS build
|
||||
|
||||
WORKDIR /src
|
||||
COPY app/go.mod app/go.sum ./
|
||||
RUN go mod download
|
||||
COPY app/ ./
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
||||
|
||||
FROM alpine:3.22
|
||||
|
||||
RUN addgroup -S -g 10001 app && adduser -S -u 10001 -G app app
|
||||
|
||||
COPY --from=build /out/server /usr/local/bin/server
|
||||
|
||||
USER app
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/usr/local/bin/server"]
|
||||
@@ -2,12 +2,18 @@ PYTHON ?= python3
|
||||
BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
COMPOSE ?= docker compose --env-file .env
|
||||
VUS ?= 10
|
||||
DURATION ?= 60s
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
.PHONY: help check validate test load test-persistence test-failover test-concurrency app-test app-build up down wait k6
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API"
|
||||
@echo "test-concurrency: cross-replica idempotency race; test-failover/persistence: explicit hooks"
|
||||
@echo "load: synthetic writes via tests/load.py; k6: k6 write load through HAProxy"
|
||||
@echo "up/down/wait: compose lifecycle; app-test: Go unit tests"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -28,3 +34,30 @@ 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)
|
||||
|
||||
# ---------------------------
|
||||
# Custom convenience commands
|
||||
# ---------------------------
|
||||
|
||||
test-concurrency:
|
||||
$(PYTHON) tests/custom/idempotency.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
app-test:
|
||||
cd app && go test ./...
|
||||
|
||||
app-build:
|
||||
cd app && go build ./cmd/server
|
||||
|
||||
up:
|
||||
$(COMPOSE) up -d --build
|
||||
|
||||
down:
|
||||
$(COMPOSE) down
|
||||
|
||||
wait:
|
||||
@echo "waiting for $(BASE_URL)/health/ready"
|
||||
@until curl -fsS "$(BASE_URL)/health/ready" >/dev/null; do sleep 1; done
|
||||
@echo "ready"
|
||||
|
||||
k6:
|
||||
$(COMPOSE) --profile load run --rm k6 run -e VUS=$(VUS) -e DURATION=$(DURATION) --summary-export /results/last.json /scripts/messages.js
|
||||
|
||||
@@ -1,37 +1,257 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Булла Максим, БПИ2301
|
||||
- Целевая оценка: **4**
|
||||
- Commit/PR: f731f9b
|
||||
- Источники, библиотеки и помощь ИИ: официальная документация Docker Compose,
|
||||
HAProxy, Go/Fiber; код и инфраструктура подготовлены с помощью
|
||||
DeepSeek V4.1 Flash + OpenCode
|
||||
|
||||
## Запуск из чистого clone
|
||||
## 1. Что сделано
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Рабочая база lab2 (Go + Fiber v3, PostgreSQL, Redis-сессии, миграции) доведена
|
||||
до lab3:
|
||||
|
||||
## Архитектура и решения
|
||||
- HAProxy стал единственной публичной точкой входа;
|
||||
- запущены две API-реплики без публикации их портов;
|
||||
- сессии и идемпотентность сообщений вынесены в общие хранилища;
|
||||
- `X-Instance-Id` добавлен во все ответы API;
|
||||
- миграции вынесены в отдельный one-shot сервис;
|
||||
- настроены readiness, graceful shutdown и ограничения CPU/RAM;
|
||||
- добавлены action-скрипты для restart/failover и rolling replacement;
|
||||
- подготовлен профиль k6 для проверки rolling update под нагрузкой.
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Обязательный контракт, `lab.json` и публичные тесты не изменялись. Существующие
|
||||
неочевидные решения отмечены в коде комментариями `AGENT:`; перечень файлов
|
||||
для их проверки и удаления находится в `LEFT_TO_REVIEW.md`. Новые комментарии
|
||||
`AGENT:` в этой итерации не добавлялись: изменения и их обоснование записаны в
|
||||
`CHANGELOG.md`.
|
||||
|
||||
## Доказательства критериев
|
||||
## 2. Запуск из чистого clone
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
Требуется Docker Engine с Compose v2 и свободный порт `8080` (или другой
|
||||
`LB_PORT`). Версии образов зафиксированы в `compose.yaml`.
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
# задать локальный POSTGRES_PASSWORD; остальное можно оставить по умолчанию
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build
|
||||
make wait
|
||||
```
|
||||
|
||||
Порядок запуска:
|
||||
|
||||
1. PostgreSQL и Redis проходят healthcheck.
|
||||
2. Сервис `migrate` один раз применяет миграции и завершается.
|
||||
3. Запускаются API-реплики с `RUN_MIGRATIONS=false`.
|
||||
4. HAProxy начинает отдавать `/health/ready` только после готовности API.
|
||||
|
||||
Проверки:
|
||||
|
||||
```sh
|
||||
make test
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
make test-concurrency
|
||||
```
|
||||
|
||||
Дополнительно:
|
||||
|
||||
```sh
|
||||
make k6 VUS=20 DURATION=60s # нагрузка через HAProxy
|
||||
make validate PYTHON=.venv/bin/python
|
||||
```
|
||||
|
||||
Остановка без удаления данных:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down
|
||||
```
|
||||
|
||||
Намеренное удаление учебных данных (только отдельный стенд):
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down -v
|
||||
```
|
||||
|
||||
`.env` в репозиторий не попадает; в `.env.example` лежит только placeholder
|
||||
пароля.
|
||||
|
||||
## 3. Архитектура и решения
|
||||
|
||||
```text
|
||||
клиент
|
||||
│ HTTP :8080
|
||||
▼
|
||||
HAProxy ── readiness /health/ready, retries, stats :8404, Prometheus /metrics
|
||||
│ Docker DNS, server-template api 1..4
|
||||
├──────────────┐
|
||||
▼ ▼
|
||||
API-1 API-2 ... API-N (Go/Fiber, без публикации портов)
|
||||
│ │
|
||||
└──────┬───────┘
|
||||
▼
|
||||
PostgreSQL ← users/chats/messages + message_idempotency
|
||||
Redis ← общие сессии (AOF)
|
||||
|
||||
migrate — one-shot, RUN_MIGRATIONS / MIGRATE_ONLY
|
||||
```
|
||||
|
||||
### 3.1. Компоненты и лимиты
|
||||
|
||||
| Компонент | Роль | Решение |
|
||||
| --- | --- | --- |
|
||||
| `haproxy` | LB и публичная точка входа | `server-template api 4 api:8080 resolvers docker`; health check `/health/ready` каждые 1 с, `fall 2` |
|
||||
| `api` | бизнес-API | `deploy.replicas: ${API_REPLICAS:-2}`, `expose: 8080`, без `ports` |
|
||||
| `migrate` | миграции | тот же образ, `MIGRATE_ONLY=true`, `restart: "no"` |
|
||||
| `postgres` | источник истины | named volume `pgdata`, healthcheck, версия 16.10 |
|
||||
| `redis` | общие сессии | AOF `everysec`, named volume `redisdata` |
|
||||
| `k6` | нагрузка | профиль `load`, подключается только при явном запуске |
|
||||
|
||||
У API, PostgreSQL, Redis и HAProxy есть CPU/RAM-лимиты
|
||||
(`deploy.resources.limits`, значения из `.env`). У API нет `container_name`,
|
||||
поэтому Compose может масштабировать сервис.
|
||||
|
||||
### 3.2. Миграции
|
||||
|
||||
`app/cmd/server/main.go` поддерживает два режима:
|
||||
|
||||
- обычный API: `RUN_MIGRATIONS=false`, схемой занимается отдельный сервис;
|
||||
- `MIGRATE_ONLY=true`: применить миграции, закрыть пул и выйти, не открывая
|
||||
Redis.
|
||||
|
||||
Это убирает гонку миграций при старте нескольких реплик и при rolling update.
|
||||
Миграция `0002_message_idempotency` аддитивная: старая версия приложения может
|
||||
работать с уже созданной таблицей, новая версия требует её наличия. Поэтому
|
||||
порядок «сначала migrate, потом новые API» безопасен.
|
||||
|
||||
### 3.3. `X-Instance-Id`
|
||||
|
||||
Middleware в `app/internal/app.go` ставит заголовок на каждый ответ, включая
|
||||
health и ошибки. Значение берётся из `INSTANCE_ID`, а если он не задан — из
|
||||
hostname процесса. В Compose hostname уникален для контейнера, поэтому
|
||||
реплики различимы; значение не меняется в течение жизни процесса.
|
||||
|
||||
Если hostname получить нельзя и `INSTANCE_ID` не задан, конфигурация
|
||||
завершается ошибкой. Раньше в этом случае молча подставлялось литеральное
|
||||
значение `api`, из-за чего несколько процессов могли получить одинаковый
|
||||
идентификатор.
|
||||
|
||||
### 3.4. Идемпотентность сообщений
|
||||
|
||||
Таблица `message_idempotency`:
|
||||
|
||||
- PK `(sender_id, chat_id, idempotency_key)` — ровно область «пользователь +
|
||||
путь чата + ключ»; метод в текущем API только один;
|
||||
- `request_hash` — SHA-256 текста сообщения;
|
||||
- `message_id` — ссылка на уже созданное сообщение;
|
||||
- `created_at`, `expires_at` — окно хранения (по умолчанию 24 часа).
|
||||
|
||||
Алгоритм в `app/internal/store/messages.go`:
|
||||
|
||||
1. Быстрый lookup по ключу. Если запись не истекла и hash совпал — вернуть тот же
|
||||
`Message` с `201`.
|
||||
2. Иначе открыть транзакцию, вставить сообщение с проверкой членства в чате,
|
||||
вставить ключ через `ON CONFLICT`.
|
||||
3. Если конкурентная реплика уже вставила этот ключ, транзакция текущего
|
||||
запроса откатывается, и читается результат победившей реплики. При другом
|
||||
hash — `409`.
|
||||
4. Транзиентная ошибка не фиксирует ключ: транзакция откатывается, клиент может
|
||||
повторить с тем же ключом.
|
||||
|
||||
Так один ключ создаёт ровно одно сообщение даже при параллельных запросах через
|
||||
разные реплики. Повтор снова проходит аутентификацию и проверку доступа к чату.
|
||||
|
||||
### 3.5. HAProxy и graceful shutdown
|
||||
|
||||
- backend discovery: Docker DNS `127.0.0.11:53`, `server-template api 4`, поэтому
|
||||
`docker compose up --scale api=N` не требует правки конфига;
|
||||
- health check: `GET /health/ready`, `inter 1s`, `fall 2` — обнаружение отказа
|
||||
около 2 секунд (при бюджете 10 секунд);
|
||||
- `retries 2`, `option redispatch` — короткие ошибки соединения не роняют запрос;
|
||||
- при SIGTERM приложение сначала перестаёт отдавать `200` на readiness, затем
|
||||
ждёт до 10 секунд; у контейнера `stop_grace_period: 15s`;
|
||||
- stats UI/CSV на `:8404/stats`, Prometheus на `:8404/metrics`.
|
||||
|
||||
### 3.6. Readiness и транзакции
|
||||
|
||||
`/health/ready` проверяет PostgreSQL и Redis и не захватывает прикладных
|
||||
блокировок. `pgxpool.Ping` берёт соединение из пула и возвращает его через
|
||||
`defer`; `store.Ping` ограничивает проверку двумя секундами.
|
||||
|
||||
Отдельно проверены транзакции в `CreateChat` и `CreateMessage`. Откат больше не
|
||||
выполняется на неограниченном `context.Background()`: используется контекст с
|
||||
таймаутом. Если PostgreSQL перестал отвечать, соединение закрывается, а
|
||||
PostgreSQL трактует закрытие соединения как откат и снимает блокировки строк.
|
||||
Это не даёт неудачной транзакции удерживать соединение пула и мешать readiness
|
||||
других запросов. Единственная явная advisory-блокировка — миграционная; она
|
||||
снимается в `defer` с собственным таймаутом.
|
||||
|
||||
## 4. Доказательства критериев
|
||||
|
||||
| Критерий | Команда/сценарий | Наблюдаемый результат | Файл |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Публичный smoke | `make test` | `PASS: lab3 public API scenario` | `evidence/grade-3-4.md` |
|
||||
| Офлайн-проверки | `make check` | `PASS: offline skeleton...` | `evidence/grade-3-4.md` |
|
||||
| OpenAPI | `make validate PYTHON=.venv/bin/python` | `PASS: full OpenAPI 3.1...` | `evidence/grade-3-4.md` |
|
||||
| ≥2 реплики, одна сессия | 10 запросов `/health/live` через LB | 2 разных `X-Instance-Id` | `evidence/grade-3-4.md` |
|
||||
| Остановка одной реплики | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 120–121 запись, 0–1 ошибка, восстановление 2.54–2.93 с | `evidence/grade-3-4.md` |
|
||||
| Сохранность после restart | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | данные и bearer-токен сохранились | `evidence/grade-3-4.md` |
|
||||
| Конкурентная идемпотентность | `make test-concurrency` | 12 запросов, 2 реплики, 1 сообщение, другой body → 409 | `evidence/grade-3-4.md` |
|
||||
| CPU/RAM-лимиты, API без host ports | `compose.yaml`, `docker compose ps` | API только `expose`, лимиты заданы | `compose.yaml` |
|
||||
| Rolling update под нагрузкой | `scripts/rolling-update.sh 2` + k6 20 VU/60 с | 41 605 итераций, 0 failed checks, p95 55.27 мс | `evidence/k6-rolling-20vu-60s.json` |
|
||||
| Миграции однократно | `migrate` service, API `RUN_MIGRATIONS=false` | `migrate` завершился, API healthy | `compose.yaml`, `app/cmd/server/main.go` |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Проверки HTTP запускались из контейнера в сети стенда: в рабочей оболочке
|
||||
published ports были изолированы от хоста. Это ограничение среды, а не
|
||||
приложения; на обычной машине команды `make test`/`make test-failover`
|
||||
запускаются с хоста.
|
||||
|
||||
## Эксперименты и отказы
|
||||
## 5. Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
### 5.1. Отказ одной API-реплики
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| Что сделано | Ожидание | Наблюдение | Восстановление |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Остановлена одна API-реплика при живой второй | LB исключает её, подтверждённые данные и сессия целы | 2 реплики до отказа; 120–121 успешная запись; 0–1 краткая ошибка | 2.54–2.93 с до первой успешной записи |
|
||||
| Вручную остановлена вторая реплика | Трафик переходит на оставшуюся | 1698 успешных записей, 1 ошибка; обе реплики наблюдались до отказа | вторая реплика восстановлена через `up` |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Ошибка на границе отказа ожидаема: клиент мог отправить запрос в момент, когда
|
||||
процесс уже остановлен, но HAProxy ещё не убрал backend. Повтор с тем же
|
||||
`Idempotency-Key` не создал дубль.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
### 5.2. Rolling update под нагрузкой
|
||||
|
||||
`scripts/rolling-update.sh 2` собирает образ и поочерёдно заменяет контейнеры:
|
||||
останавливает один, удаляет, создаёт replacement, ждёт health и только потом
|
||||
переходит к следующему. Во время этого k6 писал сообщения 20 VU в течение 60 с.
|
||||
|
||||
| Метрика | Значение |
|
||||
| --- | ---: |
|
||||
| Всего запросов | 41 608 |
|
||||
| Итераций | 41 605 |
|
||||
| Ошибок проверок | 0 |
|
||||
| p95 | 55.27 мс |
|
||||
| p99 | 71.15 мс |
|
||||
|
||||
Это подтверждает, что последовательная замена не рвёт поток целиком: HAProxy
|
||||
успевает исключить остановленный backend. Сырой summary:
|
||||
`evidence/k6-rolling-20vu-60s.json`.
|
||||
|
||||
## 6. Ограничения
|
||||
|
||||
- Один Docker-host: потеря узла не переживается. HAProxy, PostgreSQL и Redis
|
||||
остаются единичными точками отказа; API-реплики не делают БД
|
||||
высокодоступной.
|
||||
- PostgreSQL не реплицирован. При потере `pgdata` данные теряются; Redis AOF
|
||||
спасает сессии от рестарта, но не от потери диска.
|
||||
- Compose — не Swarm: rolling-скрипт делает поочерёдную замену, но не даёт
|
||||
маршрутизации между узлами.
|
||||
- Профиль k6 — write-only. Он выбран намеренно: проверяется запись,
|
||||
идемпотентность и БД; чтение и смешанный профиль — отдельный эксперимент.
|
||||
- `X-Instance-Id` здесь — hostname контейнера, не скрыт.
|
||||
- Проверка пароля и ветка «пользователь не найден» имеют разное время
|
||||
выполнения: для неизвестного username Argon2 не запускается. Теоретически
|
||||
это позволяет перечислять имена по времени ответа. Контракт требует только
|
||||
одинаковый `401` и challenge; в lab3 временная атака не устраняется.
|
||||
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#:schema https://json.schemastore.org/any.json
|
||||
|
||||
env_files = []
|
||||
root = "."
|
||||
testdata_dir = "testdata"
|
||||
tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = []
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -o ./tmp/main ./cmd/server/"
|
||||
delay = 1000
|
||||
entrypoint = ["./tmp/main"]
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
exclude_unchanged = false
|
||||
follow_symlink = false
|
||||
full_bin = ""
|
||||
ignore_dangerous_root_dir = false
|
||||
include_dir = []
|
||||
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||
include_file = []
|
||||
kill_delay = "0s"
|
||||
log = "build-errors.log"
|
||||
poll = false
|
||||
poll_interval = 0
|
||||
post_cmd = []
|
||||
pre_cmd = []
|
||||
rerun = false
|
||||
rerun_delay = 500
|
||||
send_interrupt = false
|
||||
stop_on_error = false
|
||||
|
||||
[color]
|
||||
app = ""
|
||||
build = "yellow"
|
||||
main = "magenta"
|
||||
mode = ""
|
||||
runner = "green"
|
||||
watcher = "cyan"
|
||||
|
||||
[log]
|
||||
main_only = false
|
||||
silent = false
|
||||
time = false
|
||||
|
||||
[misc]
|
||||
clean_on_exit = false
|
||||
|
||||
[proxy]
|
||||
app_port = 0
|
||||
app_start_timeout = 0
|
||||
enabled = false
|
||||
proxy_port = 0
|
||||
|
||||
[screen]
|
||||
clear_on_rebuild = false
|
||||
keep_scroll = true
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
// Command server starts the messenger HTTP API, applies optional migrations,
|
||||
// and shuts down gracefully on SIGINT/SIGTERM.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/config"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/database"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("configuration: %v", err)
|
||||
}
|
||||
|
||||
rootCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
pool, err := database.Connect(rootCtx, cfg.DatabaseURL, cfg.DBMaxConns, cfg.StartupWait)
|
||||
if err != nil {
|
||||
log.Fatalf("database: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
if cfg.MigrateOnly || cfg.RunMigrations {
|
||||
migrateCtx, cancelMigrate := context.WithTimeout(rootCtx, 60*time.Second)
|
||||
err = database.Migrate(migrateCtx, pool, cfg.DatabaseURL)
|
||||
cancelMigrate()
|
||||
if err != nil {
|
||||
log.Fatalf("migrations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.MigrateOnly {
|
||||
log.Printf("migrations applied; migrate-only process exiting")
|
||||
return
|
||||
}
|
||||
|
||||
sessions, err := session.New(cfg.CacheURL, cfg.SessionTTL, cfg.RedisTimeout)
|
||||
if err != nil {
|
||||
log.Fatalf("session store: %v", err)
|
||||
}
|
||||
defer sessions.Close()
|
||||
|
||||
app := internal.New(cfg, pool, sessions)
|
||||
|
||||
addr := net.JoinHostPort(cfg.Host, cfg.Port)
|
||||
listenErr := make(chan error, 1)
|
||||
go func() {
|
||||
listenErr <- app.Listen(addr)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err = <-listenErr:
|
||||
if err != nil {
|
||||
log.Fatalf("server: %v", err)
|
||||
}
|
||||
case <-rootCtx.Done():
|
||||
}
|
||||
|
||||
log.Printf("shutting down")
|
||||
internal.SignalGracefulShutdown()
|
||||
if err = app.ShutdownWithTimeout(10 * time.Second); err != nil {
|
||||
log.Printf("shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
module gitflic.ru/project/bulla-max/mtusi2026lab
|
||||
|
||||
go 1.27.1
|
||||
|
||||
require (
|
||||
github.com/gofiber/fiber/v3 v3.5.0
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/gofiber/schema v1.8.8 // indirect
|
||||
github.com/gofiber/utils/v2 v2.6.1 // indirect
|
||||
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.20.1 // indirect
|
||||
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/molecule-man/go-brrr v1.1.1 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.5 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.74.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
golang.org/x/net v0.59.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
golang.org/x/tools v0.50.0 // indirect
|
||||
)
|
||||
Executable
+131
@@ -0,0 +1,131 @@
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dhui/dktest v0.4.6 h1:+DPKyScKSEp3VLtbMDHcUq6V5Lm5zfZZVb0Sk7Ahom4=
|
||||
github.com/dhui/dktest v0.4.6/go.mod h1:JHTSYDtKkvFNFHJKqCzVzqXecyv+tKt8EzceOmQOgbU=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaftjlSWt4AFexzM=
|
||||
github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/fxamacker/cbor/v2 v2.9.4 h1:xwjVlxEMR3S605oUlgBjKLTTeGFciYPGYCtF/35LKGo=
|
||||
github.com/fxamacker/cbor/v2 v2.9.4/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/gofiber/fiber/v3 v3.5.0 h1:dk7TOUH6DXJGtOLsN2XEG+0ZML7cznzHILTVozbNEK8=
|
||||
github.com/gofiber/fiber/v3 v3.5.0/go.mod h1:GOVDTW+gjJvfe0iJyVujbQ1Lnx+JUjFySJRI/9/xX/w=
|
||||
github.com/gofiber/schema v1.8.8 h1:md5t65+Z9LttOuj7FdMcQ63D2+6GniT2ganLXwvTJM4=
|
||||
github.com/gofiber/schema v1.8.8/go.mod h1:Hzf0L/fTPP1IwOAwKipKflm9C2722aebnSKJCMOgb1I=
|
||||
github.com/gofiber/utils/v2 v2.6.1 h1:x3zsS/oUQz0ia2Zx8XXtG/7naR5a+/95FRO8mwQ5QQ4=
|
||||
github.com/gofiber/utils/v2 v2.6.1/go.mod h1:tc9KqdRAQZRD/u0mN2d1ZHROGheSZv+0FcC9cg5OEdw=
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1 h1:2N/ToVTKrKl58ynBpgeVJ4In7VcLCjWTZtm4eP1LxhU=
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1/go.mod h1:DDPgKVb4ovSWc4FwSPfV2Uz1160f4XBiTHTrAJtljmM=
|
||||
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/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw=
|
||||
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
|
||||
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY=
|
||||
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg=
|
||||
github.com/moby/moby/api v1.54.2/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
|
||||
github.com/moby/moby/client v0.4.1 h1:DMQgisVoMkmMs7fp3ROSdiBnoAu8+vo3GggFl06M/wY=
|
||||
github.com/moby/moby/client v0.4.1/go.mod h1:z52C9O2POPOsnxZAy//WtKcQ32P+jT/NGeXu/7nfjGQ=
|
||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||
github.com/molecule-man/go-brrr v1.1.1 h1:KYwusQhjtV3smALnhmafZf4OBrh7vP4p8O47DyUmmuY=
|
||||
github.com/molecule-man/go-brrr v1.1.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
|
||||
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
github.com/shamaton/msgpack/v3 v3.2.3 h1:0r0aZtrXDFOPpwWJTEOpFq+Ih/JmMLm0pqLN5mSilrw=
|
||||
github.com/shamaton/msgpack/v3 v3.2.3/go.mod h1:sgBYvEiyz8JR1NC3yGRoPVME9xXovpnh3l/plW1nfRo=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tinylib/msgp v1.6.5 h1:iAH6XTP7BpzErjBZlujJQXxA+GmRi2YWs6M4KdLtNbE=
|
||||
github.com/tinylib/msgp v1.6.5/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.74.0 h1:wMS9fnO2QTALozYx5pId2Vi7ZwU/epUkY8i/KPWCHoU=
|
||||
github.com/valyala/fasthttp v1.74.0/go.mod h1:3ARmLamUcw7ElxVtC8PXaGzQ6VEuvnetlkrwIklQBSE=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
|
||||
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
|
||||
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=
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
// Package internal wires HTTP routes, middleware and storage into one Fiber
|
||||
// application and owns the process-wide error handler.
|
||||
package internal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/chats"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/config"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/health"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/messages"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/users"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/recover"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func SignalGracefulShutdown() {
|
||||
health.SignalShutdown()
|
||||
}
|
||||
|
||||
func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.App {
|
||||
st := store.New(pool, cfg.DBTimeout, cfg.IdempotencyTTL)
|
||||
|
||||
app := fiber.New(fiber.Config{
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
BodyLimit: 1 * 1024 * 1024,
|
||||
ErrorHandler: handleError,
|
||||
})
|
||||
|
||||
app.Use(recover.New())
|
||||
app.Use(requestid.New())
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
c.Set("X-Instance-Id", cfg.InstanceID)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
health.RegisterRoutes(app.Group("/health"), st, sessions)
|
||||
|
||||
api := app.Group("/api/v1")
|
||||
users.RegisterPublicRoutes(api, st)
|
||||
auth.RegisterPublicRoutes(api, st, sessions)
|
||||
|
||||
protected := api.Group("")
|
||||
protected.Use(auth.BearerAuth(sessions))
|
||||
auth.RegisterProtectedRoutes(protected, st, sessions)
|
||||
users.RegisterProtectedRoutes(protected, st)
|
||||
chats.RegisterProtectedRoutes(protected, st)
|
||||
messages.RegisterProtectedRoutes(protected, st)
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
func handleError(c fiber.Ctx, err error) error {
|
||||
if appErr, ok := errors.AsType[*common.AppError](err); ok {
|
||||
return common.SendError(c, appErr.Status, appErr.Code, appErr.Message)
|
||||
}
|
||||
|
||||
if fiberErr, ok := errors.AsType[*fiber.Error](err); ok {
|
||||
return common.SendError(c, fiberErr.Code,
|
||||
common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message)
|
||||
}
|
||||
|
||||
return common.SendError(c, fiber.StatusInternalServerError,
|
||||
common.ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Package auth implements password hashing, Basic login, Bearer session
|
||||
// middleware and the authentication routes.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/log"
|
||||
)
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.Store
|
||||
sessions *session.Store
|
||||
}
|
||||
|
||||
func NewHandler(st *store.Store, sessions *session.Store) *Handler {
|
||||
return &Handler{store: st, sessions: sessions}
|
||||
}
|
||||
|
||||
func (h *Handler) CreateSession(c fiber.Ctx) error {
|
||||
username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization))
|
||||
if !ok {
|
||||
return common.SendChallenge(c, basicChallenge, "invalid credentials")
|
||||
}
|
||||
|
||||
user, err := h.store.GetUserByUsername(c.Context(), username)
|
||||
if err != nil {
|
||||
if common.IsCode(err, common.ErrorCodeNotFound) {
|
||||
// An unknown username returns before Argon2 runs, while a known
|
||||
// username with a wrong password runs VerifyPassword. The branches
|
||||
// therefore take different time, so username enumeration through
|
||||
// response timing is theoretically possible. The contract only
|
||||
// requires the same 401 body and challenge.
|
||||
return common.SendChallenge(c, basicChallenge, "invalid credentials")
|
||||
}
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
valid, err := VerifyPassword(user.PasswordHash, password)
|
||||
if err != nil || !valid {
|
||||
return common.SendChallenge(c, basicChallenge, "invalid credentials")
|
||||
}
|
||||
|
||||
token, expiresAt, err := h.sessions.Create(c.Context(), user.ID)
|
||||
if err != nil {
|
||||
log.Errorf("create session: %v", err)
|
||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
||||
common.ErrorCodeUnavailable, "session store unavailable")
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).JSON(model.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: common.RFCFormTime(expiresAt),
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) RevokeSession(c fiber.Ctx) error {
|
||||
token, ok := common.SessionToken(c)
|
||||
if !ok {
|
||||
return common.SendChallenge(c, bearerChallenge, "authentication required")
|
||||
}
|
||||
|
||||
if err := h.sessions.Revoke(c.Context(), token); err != nil {
|
||||
log.Errorf("revoke session: %v", err)
|
||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
||||
common.ErrorCodeUnavailable, "session store unavailable")
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
func BearerAuth(sessions *session.Store) fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
header := strings.TrimSpace(c.Get(fiber.HeaderAuthorization))
|
||||
scheme, token, found := strings.Cut(header, " ")
|
||||
token = strings.TrimSpace(token)
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t") {
|
||||
return common.SendChallenge(c, bearerChallenge, "authentication required")
|
||||
}
|
||||
|
||||
userID, err := sessions.Lookup(c.Context(), token)
|
||||
if err != nil {
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
return common.SendChallenge(c, bearerChallenge, "session expired or revoked")
|
||||
}
|
||||
log.Errorf("session lookup: %v", err)
|
||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
||||
common.ErrorCodeUnavailable, "session store unavailable")
|
||||
}
|
||||
|
||||
c.Locals(common.KeyUserID, userID)
|
||||
c.Locals(common.KeySessionToken, token)
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func parseBasic(header string) (string, string, bool) {
|
||||
scheme, encoded, found := strings.Cut(strings.TrimSpace(header), " ")
|
||||
if !found || !strings.EqualFold(scheme, "Basic") || encoded == "" {
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
if decoded, err = base64.RawStdEncoding.DecodeString(encoded); err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 7617: split at the first colon; a colon is legal inside the password.
|
||||
username, password, found := strings.Cut(string(decoded), ":")
|
||||
if !found || username == "" || password == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return username, password, true
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory = 64 * 1024
|
||||
argonIterations = 2
|
||||
argonParallelism = 4
|
||||
argonKeyLength = 32
|
||||
argonSaltLength = 16
|
||||
)
|
||||
|
||||
var ErrInvalidHash = errors.New("invalid password hash")
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate salt: %w", err)
|
||||
}
|
||||
|
||||
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
|
||||
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonIterations, argonParallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(encoded, password string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
var memory uint32
|
||||
var iterations uint32
|
||||
var parallelism uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
// argon2.IDKey panics when the cost parameters are outside its supported
|
||||
// range. A corrupted row or an attacker-supplied encoding must be rejected
|
||||
// with ErrInvalidHash instead of taking the process down.
|
||||
if iterations < 1 || parallelism < 1 || memory < 8*uint32(parallelism) {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) == 0 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(expected) == 0 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(expected)))
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordRoundTripPreservesFullRange(t *testing.T) {
|
||||
passwords := []string{
|
||||
"simple-password-123",
|
||||
"colon:inside:password",
|
||||
"пароль-с-кириллицей-12",
|
||||
strings.Repeat("😀", 128),
|
||||
}
|
||||
for _, password := range passwords {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword: %v", err)
|
||||
}
|
||||
ok, err := VerifyPassword(hash, password)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("VerifyPassword rejected the correct password (ok=%v err=%v)", ok, err)
|
||||
}
|
||||
ok, err = VerifyPassword(hash, password+"x")
|
||||
if err != nil || ok {
|
||||
t.Fatalf("VerifyPassword accepted a different password (ok=%v err=%v)", ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashIsSalted(t *testing.T) {
|
||||
first, err := HashPassword("same-password-123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := HashPassword("same-password-123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("two hashes of the same password are identical")
|
||||
}
|
||||
if _, err := VerifyPassword("not-a-hash", "same-password-123"); err == nil {
|
||||
t.Fatal("invalid encoded hash was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPasswordRejectsMalformedCostAndEmptyDigest(t *testing.T) {
|
||||
malformed := []string{
|
||||
// Empty digest would make argon2 derive a zero-length key.
|
||||
"$argon2id$v=19$m=65536,t=2,p=4$c2FsdA$",
|
||||
// Zero cost parameters are outside argon2's supported range and would
|
||||
// otherwise panic inside the KDF.
|
||||
"$argon2id$v=19$m=65536,t=0,p=4$c2FsdA$YWJjZA",
|
||||
"$argon2id$v=19$m=65536,t=2,p=0$c2FsdA$YWJjZA",
|
||||
"$argon2id$v=19$m=1,t=2,p=4$c2FsdA$YWJjZA",
|
||||
}
|
||||
for _, encoded := range malformed {
|
||||
ok, err := VerifyPassword(encoded, "same-password-123")
|
||||
if err == nil || ok {
|
||||
t.Fatalf("VerifyPassword(%q) = (%v, %v), want ErrInvalidHash", encoded, ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
func RegisterPublicRoutes(router fiber.Router, st *store.Store, sessions *session.Store) {
|
||||
handler := NewHandler(st, sessions)
|
||||
router.Post("/auth/sessions", handler.CreateSession)
|
||||
}
|
||||
|
||||
func RegisterProtectedRoutes(router fiber.Router, st *store.Store, sessions *session.Store) {
|
||||
handler := NewHandler(st, sessions)
|
||||
router.Delete("/auth/sessions/current", handler.RevokeSession)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Package chats implements chat creation, lookup and cursor-paginated listing.
|
||||
package chats
|
||||
|
||||
import (
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.Store
|
||||
}
|
||||
|
||||
func NewHandler(st *store.Store) *Handler {
|
||||
return &Handler{store: st}
|
||||
}
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(c fiber.Ctx) error {
|
||||
userID := common.MustUserID(c)
|
||||
|
||||
var req CreateChatRequest
|
||||
if err := common.BindJSON(c, &req); err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
if msg := common.ValidateChatTitle(req.Title); msg != "" {
|
||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
||||
}
|
||||
if msg := common.ValidateMemberIDs(req.MemberIDs, userID); msg != "" {
|
||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
||||
}
|
||||
|
||||
chat, err := h.store.CreateChat(c.Context(), req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).JSON(chat)
|
||||
}
|
||||
|
||||
func (h *Handler) ListChats(c fiber.Ctx) error {
|
||||
userID := common.MustUserID(c)
|
||||
|
||||
limit, err := common.ParseLimit(c, 50)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
cursor, err := common.ParseCursor(c)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
if cursor != nil && cursor.ContextID != userID {
|
||||
return common.SendError(c, fiber.StatusBadRequest,
|
||||
common.ErrorCodeInvalidRequest, "bad cursor value")
|
||||
}
|
||||
|
||||
page, err := h.store.ListChats(c.Context(), userID, limit, cursor)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
return c.JSON(page)
|
||||
}
|
||||
|
||||
func (h *Handler) GetChat(c fiber.Ctx) error {
|
||||
userID := common.MustUserID(c)
|
||||
|
||||
chatID, err := uuid.Parse(c.Params("chat_id"))
|
||||
if err != nil {
|
||||
return common.SendError(c, fiber.StatusBadRequest,
|
||||
common.ErrorCodeInvalidRequest, "invalid chat_id format")
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChatForUser(c.Context(), userID, chatID)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
return c.JSON(chat)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package chats
|
||||
|
||||
import (
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
func RegisterProtectedRoutes(router fiber.Router, st *store.Store) {
|
||||
handler := NewHandler(st)
|
||||
router.Post("/chats", handler.CreateChat)
|
||||
router.Get("/chats", handler.ListChats)
|
||||
router.Get("/chats/:chat_id", handler.GetChat)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
func BindJSON(c fiber.Ctx, dst any) error {
|
||||
if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") {
|
||||
return UnsupportedMedia("invalid JSON body")
|
||||
}
|
||||
|
||||
body := c.Body()
|
||||
if len(body) == 0 {
|
||||
return BadRequest("request body is empty")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(dst); err != nil {
|
||||
return BadRequest("invalid JSON body")
|
||||
}
|
||||
|
||||
var extra json.RawMessage
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
return BadRequest("request body has extra trailing bytes")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// Package common contains cross-cutting HTTP helpers: contract errors, JSON
|
||||
// binding, validation, cursor pagination and timestamp formatting.
|
||||
package common
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
ErrorCodeInvalidRequest = "invalid_request"
|
||||
ErrorCodeUnauthorized = "unauthorized"
|
||||
ErrorCodeNotFound = "not_found"
|
||||
ErrorCodeConflict = "conflict"
|
||||
ErrorCodePayloadTooLarge = "payload_too_large"
|
||||
ErrorCodeUnsupportedMedia = "unsupported_media_type"
|
||||
ErrorCodeRateLimited = "rate_limited"
|
||||
ErrorCodeUnavailable = "unavailable"
|
||||
ErrorCodeInternal = "internal_error"
|
||||
)
|
||||
|
||||
type APIErrorResponse struct {
|
||||
Error APIError `json:"error"`
|
||||
}
|
||||
|
||||
type APIError struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func NewError(code, message, requestID string) APIErrorResponse {
|
||||
return APIErrorResponse{
|
||||
Error: APIError{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type AppError struct {
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func NewAppError(status int, code, message string) *AppError {
|
||||
return &AppError{
|
||||
Status: status,
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
}
|
||||
|
||||
func BadRequest(message string) *AppError {
|
||||
return NewAppError(fiber.StatusBadRequest, ErrorCodeInvalidRequest, message)
|
||||
}
|
||||
|
||||
func Unauthorized(message string) *AppError {
|
||||
return NewAppError(fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
||||
}
|
||||
|
||||
func NotFound(message string) *AppError {
|
||||
return NewAppError(fiber.StatusNotFound, ErrorCodeNotFound, message)
|
||||
}
|
||||
|
||||
func Conflict(message string) *AppError {
|
||||
return NewAppError(fiber.StatusConflict, ErrorCodeConflict, message)
|
||||
}
|
||||
|
||||
func UnsupportedMedia(message string) *AppError {
|
||||
return NewAppError(fiber.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
|
||||
}
|
||||
|
||||
func Internal() *AppError {
|
||||
return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
func Unavailable(message string) *AppError {
|
||||
return NewAppError(fiber.StatusServiceUnavailable, ErrorCodeUnavailable, message)
|
||||
}
|
||||
|
||||
// IsCode reports whether err is an AppError with the given contract code.
|
||||
func IsCode(err error, code string) bool {
|
||||
appErr, ok := errors.AsType[*AppError](err)
|
||||
return ok && appErr.Code == code
|
||||
}
|
||||
|
||||
func ErrorCodeFromStatus(status int) string {
|
||||
switch status {
|
||||
case fiber.StatusBadRequest:
|
||||
return ErrorCodeInvalidRequest
|
||||
case fiber.StatusUnauthorized:
|
||||
return ErrorCodeUnauthorized
|
||||
case fiber.StatusNotFound:
|
||||
return ErrorCodeNotFound
|
||||
case fiber.StatusConflict:
|
||||
return ErrorCodeConflict
|
||||
case fiber.StatusRequestEntityTooLarge:
|
||||
return ErrorCodePayloadTooLarge
|
||||
case fiber.StatusUnsupportedMediaType:
|
||||
return ErrorCodeUnsupportedMedia
|
||||
case fiber.StatusTooManyRequests:
|
||||
return ErrorCodeRateLimited
|
||||
case fiber.StatusServiceUnavailable:
|
||||
return ErrorCodeUnavailable
|
||||
default:
|
||||
return ErrorCodeInternal
|
||||
}
|
||||
}
|
||||
|
||||
func getRequestID(c fiber.Ctx) string {
|
||||
if id := string(c.Response().Header.Peek("X-Request-Id")); id != "" {
|
||||
return id
|
||||
}
|
||||
return requestid.FromContext(c)
|
||||
}
|
||||
|
||||
func SendError(c fiber.Ctx, status int, code, message string) error {
|
||||
return c.Status(status).JSON(NewError(code, message, getRequestID(c)))
|
||||
}
|
||||
|
||||
func SendAppError(c fiber.Ctx, err error) error {
|
||||
if appErr, ok := errors.AsType[*AppError](err); ok {
|
||||
return SendError(c, appErr.Status, appErr.Code, appErr.Message)
|
||||
}
|
||||
|
||||
return SendError(c, fiber.StatusInternalServerError,
|
||||
ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
func SendChallenge(c fiber.Ctx, challenge, message string) error {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, challenge)
|
||||
return SendError(c, fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateIdempotencyKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
ok bool
|
||||
}{
|
||||
{name: "hex", key: "4f8c2d1e", ok: true},
|
||||
{name: "allowed punctuation", key: "load-1_a.b:c", ok: true},
|
||||
{name: "empty", key: "", ok: false},
|
||||
{name: "space", key: "two words", ok: false},
|
||||
{name: "slash", key: "a/b", ok: false},
|
||||
{name: "too long", key: strings.Repeat("a", 129), ok: false},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := ValidateIdempotencyKey(test.key) == ""
|
||||
if got != test.ok {
|
||||
t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
KeyUserID = "userID"
|
||||
KeySessionToken = "sessionToken"
|
||||
)
|
||||
|
||||
func UserID(c fiber.Ctx) (uuid.UUID, bool) {
|
||||
userID, ok := c.Locals(KeyUserID).(uuid.UUID)
|
||||
return userID, ok
|
||||
}
|
||||
|
||||
func MustUserID(c fiber.Ctx) uuid.UUID {
|
||||
userID, ok := UserID(c)
|
||||
if !ok {
|
||||
panic("common: authenticated user ID is missing from the request context")
|
||||
}
|
||||
return userID
|
||||
}
|
||||
|
||||
func SessionToken(c fiber.Ctx) (string, bool) {
|
||||
token, ok := c.Locals(KeySessionToken).(string)
|
||||
return token, ok && token != ""
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CursorKeyCtx struct {
|
||||
Time time.Time
|
||||
ID uuid.UUID
|
||||
ContextID uuid.UUID
|
||||
}
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ParseLimit(c fiber.Ctx, defaultLimit int) (int, error) {
|
||||
limitStr, exists := c.Queries()["limit"]
|
||||
if !exists {
|
||||
return defaultLimit, nil
|
||||
}
|
||||
if strings.TrimSpace(limitStr) == "" {
|
||||
return 0, BadRequest("limit param declared but empty")
|
||||
}
|
||||
|
||||
limit, err := strconv.Atoi(limitStr)
|
||||
if err != nil || limit < 1 || limit > 100 {
|
||||
return 0, BadRequest("limit must be an integer between 1 and 100")
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func ParseCursor(c fiber.Ctx) (*CursorKeyCtx, error) {
|
||||
cursorStr, exists := c.Queries()["cursor"]
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
if strings.TrimSpace(cursorStr) == "" {
|
||||
return nil, BadRequest("cursor param declared but empty")
|
||||
}
|
||||
|
||||
cursor, ok := DecodeCursor(cursorStr)
|
||||
if !ok {
|
||||
return nil, BadRequest("invalid cursor format")
|
||||
}
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
func EncodeCursor(key CursorKeyCtx) string {
|
||||
raw := key.Time.UTC().Format(time.RFC3339Nano) + "|" + key.ID.String() + "|" + key.ContextID.String()
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
parsedID, err := uuid.Parse(parts[1])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
parsedContext, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &CursorKeyCtx{Time: parsedTime, ID: parsedID, ContextID: parsedContext}, true
|
||||
}
|
||||
|
||||
func NextCursor[T interface {
|
||||
GetID() uuid.UUID
|
||||
GetCreatedAt() time.Time
|
||||
}](items []T, hasMore bool, contextID uuid.UUID) *string {
|
||||
if !hasMore || len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
last := items[len(items)-1]
|
||||
encoded := EncodeCursor(CursorKeyCtx{
|
||||
Time: last.GetCreatedAt(),
|
||||
ID: last.GetID(),
|
||||
ContextID: contextID,
|
||||
})
|
||||
return &encoded
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
want := CursorKeyCtx{
|
||||
Time: time.Date(2026, 10, 20, 12, 30, 45, 123456789, time.UTC),
|
||||
ID: uuid.MustParse("11111111-1111-4111-8111-111111111111"),
|
||||
ContextID: uuid.MustParse("22222222-2222-4222-8222-222222222222"),
|
||||
}
|
||||
|
||||
encoded := EncodeCursor(want)
|
||||
got, ok := DecodeCursor(encoded)
|
||||
if !ok {
|
||||
t.Fatal("cursor did not decode")
|
||||
}
|
||||
if !got.Time.Equal(want.Time) || got.ID != want.ID || got.ContextID != want.ContextID {
|
||||
t.Fatalf("cursor round trip changed the key: %+v", got)
|
||||
}
|
||||
|
||||
for _, invalid := range []string{"not-base64!", "", "aGVsbG8"} {
|
||||
if _, ok := DecodeCursor(invalid); ok {
|
||||
t.Fatalf("invalid cursor %q was accepted", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package common
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidatePasswordRange(t *testing.T) {
|
||||
cases := []struct {
|
||||
password string
|
||||
valid bool
|
||||
}{
|
||||
{"short", false},
|
||||
{"12345678901", false},
|
||||
{"123456789012", true},
|
||||
{"пароль-из-двенадцати", true},
|
||||
{"😀", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ValidatePassword(tc.password) == ""; got != tc.valid {
|
||||
t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PostgreSQL stores microseconds, so keeping the same boundary in Go
|
||||
// prevents a create response from showing more precision
|
||||
// than a later read can reproduce.
|
||||
const storageTimePrecision = time.Microsecond
|
||||
|
||||
type RFCFormTime time.Time
|
||||
|
||||
func (t RFCFormTime) MarshalJSON() ([]byte, error) {
|
||||
// RFC 3339 permits an optional fractional second.
|
||||
utc := time.Time(t).UTC().Truncate(storageTimePrecision)
|
||||
layout := "2006-01-02T15:04:05Z"
|
||||
if utc.Nanosecond() != 0 {
|
||||
layout = "2006-01-02T15:04:05.000000Z"
|
||||
}
|
||||
return json.Marshal(utc.Format(layout))
|
||||
}
|
||||
|
||||
func NowUTC() RFCFormTime {
|
||||
return RFCFormTime(time.Now().UTC().Truncate(storageTimePrecision))
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNowUTCHasMicrosecondPrecision(t *testing.T) {
|
||||
now := time.Time(NowUTC())
|
||||
if now.Nanosecond()%1000 != 0 {
|
||||
t.Fatalf("NowUTC() kept precision below a microsecond: %v", now)
|
||||
}
|
||||
if now.Location() != time.UTC {
|
||||
t.Fatalf("NowUTC() location = %v, want UTC", now.Location())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRFCFormTimeSerializesFractionalSeconds(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
value time.Time
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "microseconds",
|
||||
value: time.Date(2026, 10, 26, 12, 34, 56, 123456789, time.UTC),
|
||||
want: `"2026-10-26T12:34:56.123456Z"`,
|
||||
},
|
||||
{
|
||||
name: "exact second",
|
||||
value: time.Date(2026, 10, 26, 12, 34, 56, 0, time.UTC),
|
||||
want: `"2026-10-26T12:34:56Z"`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
encoded, err := json.Marshal(RFCFormTime(tc.value))
|
||||
if err != nil {
|
||||
t.Fatalf("marshal RFC form time: %v", err)
|
||||
}
|
||||
if string(encoded) != tc.want {
|
||||
t.Fatalf("RFC form time = %s, want %s", encoded, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
idempotencyKeyRegex = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
)
|
||||
|
||||
func blank(s string) bool {
|
||||
return strings.TrimSpace(s) == ""
|
||||
}
|
||||
|
||||
func strLenBetween(s string, min, max int) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func ValidateCreateUser(username, displayName string) string {
|
||||
if !usernameRegex.MatchString(username) {
|
||||
return "username must match ^[a-z0-9_]{3,32}$"
|
||||
}
|
||||
|
||||
if blank(displayName) {
|
||||
return "display_name must not be empty or only whitespace"
|
||||
}
|
||||
|
||||
if !strLenBetween(displayName, 1, 100) {
|
||||
return "display_name must be between 1 and 100 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidatePassword(password string) string {
|
||||
if blank(password) {
|
||||
return "password must not be empty or only whitespace"
|
||||
}
|
||||
|
||||
if !strLenBetween(password, 12, 128) {
|
||||
return "password must be between 12 and 128 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateChatTitle(title string) string {
|
||||
if blank(title) {
|
||||
return "title must not be empty or only whitespace"
|
||||
}
|
||||
|
||||
if !strLenBetween(title, 1, 100) {
|
||||
return "title must be between 1 and 100 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateMessageText(text string) string {
|
||||
if blank(text) {
|
||||
return "text must not be empty or only whitespace"
|
||||
}
|
||||
|
||||
if !strLenBetween(text, 1, 4000) {
|
||||
return "text must be between 1 and 4000 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateIdempotencyKey(key string) string {
|
||||
if key == "" {
|
||||
return "Idempotency-Key header is required"
|
||||
}
|
||||
if !idempotencyKeyRegex.MatchString(key) {
|
||||
return "Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
|
||||
if len(ids) < 1 || len(ids) > 100 {
|
||||
return "member_ids must contain between 1 and 100 members"
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]bool, len(ids))
|
||||
callerFound := false
|
||||
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
return "member_ids must not contain duplicates"
|
||||
}
|
||||
|
||||
seen[id] = true
|
||||
|
||||
if id == callerID {
|
||||
callerFound = true
|
||||
}
|
||||
}
|
||||
|
||||
if !callerFound {
|
||||
return "caller must be included in member_ids"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Package config loads and validates process configuration from environment
|
||||
// variables and optional *_FILE secrets.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
InstanceID string
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
DBMaxConns int32
|
||||
DBTimeout time.Duration
|
||||
RedisTimeout time.Duration
|
||||
StartupWait time.Duration
|
||||
RunMigrations bool
|
||||
MigrateOnly bool
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
instance, err := instanceID()
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
cfg := Config{
|
||||
Host: envOr("APP_HOST", "0.0.0.0"),
|
||||
Port: envOr("APP_PORT", "8080"),
|
||||
InstanceID: instance,
|
||||
DBMaxConns: 10,
|
||||
DBTimeout: 5 * time.Second,
|
||||
RedisTimeout: 2 * time.Second,
|
||||
StartupWait: 30 * time.Second,
|
||||
RunMigrations: true,
|
||||
}
|
||||
|
||||
ttlSeconds, err := strconv.Atoi(envOr("SESSION_TTL_SECONDS", "3600"))
|
||||
if err != nil || ttlSeconds < 1 {
|
||||
return cfg, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer")
|
||||
}
|
||||
cfg.SessionTTL = time.Duration(ttlSeconds) * time.Second
|
||||
|
||||
idempotencySeconds, err := strconv.Atoi(envOr("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
if err != nil || idempotencySeconds < 1 {
|
||||
return cfg, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be a positive integer")
|
||||
}
|
||||
cfg.IdempotencyTTL = time.Duration(idempotencySeconds) * time.Second
|
||||
|
||||
if cfg.RunMigrations, err = envBool("RUN_MIGRATIONS", true); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if cfg.MigrateOnly, err = envBool("MIGRATE_ONLY", false); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
if value := envOr("DB_POOL_MAX_CONNS", ""); value != "" {
|
||||
n, convErr := strconv.Atoi(value)
|
||||
if convErr != nil || n < 1 || n > 100 {
|
||||
return cfg, fmt.Errorf("DB_POOL_MAX_CONNS must be an integer between 1 and 100")
|
||||
}
|
||||
cfg.DBMaxConns = int32(n)
|
||||
}
|
||||
|
||||
cfg.DatabaseURL, err = secret("DATABASE_URL")
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if cfg.DatabaseURL == "" {
|
||||
return cfg, fmt.Errorf("DATABASE_URL or DATABASE_URL_FILE is required")
|
||||
}
|
||||
|
||||
if cfg.MigrateOnly {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
cfg.CacheURL, err = secret("CACHE_URL")
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if cfg.CacheURL == "" {
|
||||
cfg.CacheURL, err = secret("REDIS_URL")
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
}
|
||||
if cfg.CacheURL == "" {
|
||||
return cfg, fmt.Errorf("CACHE_URL or CACHE_URL_FILE is required")
|
||||
}
|
||||
|
||||
if value := strings.ToLower(envOr("SESSION_STORE", "redis")); value != "redis" {
|
||||
return cfg, fmt.Errorf("SESSION_STORE must be redis (got %q)", value)
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func instanceID() (string, error) {
|
||||
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
|
||||
return value, nil
|
||||
}
|
||||
name, err := os.Hostname()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("determine INSTANCE_ID: %w", err)
|
||||
}
|
||||
if name = strings.TrimSpace(name); name == "" {
|
||||
return "", fmt.Errorf("determine INSTANCE_ID: hostname is empty and INSTANCE_ID is not set")
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func envBool(name string, fallback bool) (bool, error) {
|
||||
value := os.Getenv(name)
|
||||
if value == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s must be true or false", name)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func envOr(name, fallback string) string {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func secret(name string) (string, error) {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
path := os.Getenv(name + "_FILE")
|
||||
if path == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s_FILE: %w", name, err)
|
||||
}
|
||||
|
||||
value := strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s_FILE is empty", name)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestInstanceIDUsesConfiguredValue(t *testing.T) {
|
||||
t.Setenv("INSTANCE_ID", " api-1 ")
|
||||
|
||||
got, err := instanceID()
|
||||
if err != nil {
|
||||
t.Fatalf("instanceID: %v", err)
|
||||
}
|
||||
if got != "api-1" {
|
||||
t.Fatalf("instanceID = %q, want api-1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDFallsBackToHostname(t *testing.T) {
|
||||
t.Setenv("INSTANCE_ID", " ")
|
||||
|
||||
got, err := instanceID()
|
||||
if err != nil {
|
||||
t.Fatalf("instanceID: %v", err)
|
||||
}
|
||||
if got == "" {
|
||||
t.Fatal("instanceID returned an empty value")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Package database owns the PostgreSQL connection pool and schema migrations.
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
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 = 3 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(wait)
|
||||
for {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err = pool.Ping(pingCtx)
|
||||
cancel()
|
||||
if err == nil {
|
||||
return pool, nil
|
||||
}
|
||||
if time.Now().After(deadline) || ctx.Err() != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("postgres is not reachable: %w", err)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
const (
|
||||
legacyMigrationLockID int64 = 728_2026
|
||||
migrationsTable = "schema_migrations"
|
||||
)
|
||||
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error {
|
||||
if err := upgradeLegacyMigrationsTable(ctx, pool); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
source, err := iofs.New(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("load embedded migrations: %w", err)
|
||||
}
|
||||
|
||||
connConfig, err := pgx.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
_ = source.Close()
|
||||
return fmt.Errorf("parse DATABASE_URL for migrations: %w", err)
|
||||
}
|
||||
if connConfig.RuntimeParams == nil {
|
||||
connConfig.RuntimeParams = make(map[string]string)
|
||||
}
|
||||
connConfig.RuntimeParams["lock_timeout"] = "30000"
|
||||
connConfig.ConnectTimeout = 3 * time.Second
|
||||
|
||||
db := stdlib.OpenDB(*connConfig)
|
||||
db.SetMaxOpenConns(1)
|
||||
db.SetMaxIdleConns(1)
|
||||
|
||||
driver, err := pgxmigrate.WithInstance(db, &pgxmigrate.Config{
|
||||
MigrationsTable: migrationsTable,
|
||||
StatementTimeout: 30 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
_ = source.Close()
|
||||
_ = db.Close()
|
||||
return fmt.Errorf("create migration driver: %w", err)
|
||||
}
|
||||
|
||||
migrator, err := migrate.NewWithInstance("iofs", source, "pgx5", driver)
|
||||
if err != nil {
|
||||
_ = source.Close()
|
||||
_ = driver.Close()
|
||||
return fmt.Errorf("create migrator: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
// Close closes both the embedded source and the database connection.
|
||||
_, _ = migrator.Close()
|
||||
}()
|
||||
|
||||
if err := migrator.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
||||
return fmt.Errorf("apply migrations: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// upgradeLegacyMigrationsTable replaces the table written by the previous
|
||||
// in-house runner (version text, applied_at) with the golang-migrate schema
|
||||
// (version bigint, dirty boolean). The data schema itself is left untouched and the
|
||||
// highest applied version is carried over, so a preserved volume does not need
|
||||
// to be recreated. The migration DDL is idempotent, but preserving the version
|
||||
// keeps the migration history truthful.
|
||||
//
|
||||
// AGENT: This is a one-time compatibility bridge, not a permanent second
|
||||
// migration format. It runs under the old advisory lock before golang-migrate
|
||||
// creates its own lock and metadata.
|
||||
func upgradeLegacyMigrationsTable(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
conn, err := pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("acquire migration connection: %w", err)
|
||||
}
|
||||
defer conn.Release()
|
||||
|
||||
if _, err := conn.Exec(ctx, "SELECT pg_advisory_lock($1)", legacyMigrationLockID); err != nil {
|
||||
return fmt.Errorf("acquire migration lock: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
unlockCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
_, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", legacyMigrationLockID)
|
||||
}()
|
||||
|
||||
var legacy bool
|
||||
if err := conn.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = current_schema()
|
||||
AND table_name = $1
|
||||
AND column_name = 'applied_at'
|
||||
)`, migrationsTable).Scan(&legacy); err != nil {
|
||||
return fmt.Errorf("inspect %s: %w", migrationsTable, err)
|
||||
}
|
||||
if !legacy {
|
||||
return nil
|
||||
}
|
||||
|
||||
tx, err := conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin migration table upgrade: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
rollbackCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = tx.Rollback(rollbackCtx)
|
||||
}()
|
||||
|
||||
const upgrade = `
|
||||
DROP TABLE IF EXISTS schema_migrations_migrate_tmp;
|
||||
|
||||
CREATE TABLE schema_migrations_migrate_tmp (
|
||||
version bigint NOT NULL PRIMARY KEY,
|
||||
dirty boolean NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO schema_migrations_migrate_tmp (version, dirty)
|
||||
SELECT MAX(substring(version FROM '^[0-9]+')::bigint), false
|
||||
FROM schema_migrations
|
||||
WHERE version ~ '^[0-9]+'
|
||||
HAVING COUNT(*) > 0;
|
||||
|
||||
DROP TABLE schema_migrations;
|
||||
ALTER TABLE schema_migrations_migrate_tmp RENAME TO schema_migrations;`
|
||||
|
||||
if _, err := tx.Exec(ctx, upgrade); err != nil {
|
||||
return fmt.Errorf("upgrade legacy %s: %w", migrationsTable, err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit migration table upgrade: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
DROP TABLE IF EXISTS messages;
|
||||
DROP TABLE IF EXISTS chat_members;
|
||||
DROP TABLE IF EXISTS chats;
|
||||
DROP TABLE IF EXISTS users;
|
||||
@@ -0,0 +1,38 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT users_username_key UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS chat_members_user_idx
|
||||
ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS message_idempotency;
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS message_idempotency (
|
||||
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
idempotency_key text NOT NULL,
|
||||
request_hash bytea NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (sender_id, chat_id, idempotency_key),
|
||||
CONSTRAINT message_idempotency_key_len CHECK (char_length(idempotency_key) BETWEEN 1 AND 128)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS message_idempotency_expires_at_idx
|
||||
ON message_idempotency (expires_at);
|
||||
@@ -0,0 +1,53 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"testing"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
)
|
||||
|
||||
func TestEmbeddedMigrationsParse(t *testing.T) {
|
||||
entries, err := fs.ReadDir(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
t.Fatalf("read embedded migrations: %v", err)
|
||||
}
|
||||
|
||||
names := make(map[string]bool, len(entries))
|
||||
for _, entry := range entries {
|
||||
names[entry.Name()] = true
|
||||
}
|
||||
for _, want := range []string{
|
||||
"0001_init.up.sql", "0001_init.down.sql",
|
||||
"0002_message_idempotency.up.sql", "0002_message_idempotency.down.sql",
|
||||
} {
|
||||
if !names[want] {
|
||||
t.Fatalf("migration %q is missing from the embedded filesystem", want)
|
||||
}
|
||||
}
|
||||
|
||||
source, err := iofs.New(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
t.Fatalf("parse migrations with golang-migrate: %v", err)
|
||||
}
|
||||
defer func() { _ = source.Close() }()
|
||||
|
||||
version, err := source.First()
|
||||
if err != nil {
|
||||
t.Fatalf("read first migration: %v", err)
|
||||
}
|
||||
if version != 1 {
|
||||
t.Fatalf("first migration version = %d, want 1", version)
|
||||
}
|
||||
version, err = source.Next(version)
|
||||
if err != nil {
|
||||
t.Fatalf("read second migration: %v", err)
|
||||
}
|
||||
if version != 2 {
|
||||
t.Fatalf("second migration version = %d, want 2", version)
|
||||
}
|
||||
if _, err := source.Next(version); !errors.Is(err, fs.ErrNotExist) {
|
||||
t.Fatalf("expected 0002 to be the last migration, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Package health exposes liveness and readiness endpoints plus the process
|
||||
// shutdown flag used by readiness.
|
||||
package health
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.Store
|
||||
sessions *session.Store
|
||||
}
|
||||
|
||||
func NewHandler(st *store.Store, sessions *session.Store) *Handler {
|
||||
return &Handler{store: st, sessions: sessions}
|
||||
}
|
||||
|
||||
var shuttingDown atomic.Bool
|
||||
|
||||
func SignalShutdown() {
|
||||
shuttingDown.Store(true)
|
||||
}
|
||||
|
||||
type Status struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func (h *Handler) Live(c fiber.Ctx) error {
|
||||
return c.JSON(Status{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *Handler) Ready(c fiber.Ctx) error {
|
||||
if shuttingDown.Load() {
|
||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
||||
common.ErrorCodeUnavailable, "service is shutting down")
|
||||
}
|
||||
|
||||
if err := h.store.Ping(c.Context()); err != nil {
|
||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
||||
common.ErrorCodeUnavailable, "database unavailable")
|
||||
}
|
||||
|
||||
if err := h.sessions.Ping(c.Context()); err != nil {
|
||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
||||
common.ErrorCodeUnavailable, "session store unavailable")
|
||||
}
|
||||
|
||||
return c.JSON(Status{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
func RegisterRoutes(router fiber.Router, st *store.Store, sessions *session.Store) {
|
||||
handler := NewHandler(st, sessions)
|
||||
router.Get("/live", handler.Live)
|
||||
router.Get("/ready", handler.Ready)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Package messages implements message creation with idempotency and message
|
||||
// history pagination.
|
||||
package messages
|
||||
|
||||
import (
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.Store
|
||||
}
|
||||
|
||||
func NewHandler(st *store.Store) *Handler {
|
||||
return &Handler{store: st}
|
||||
}
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateMessage(c fiber.Ctx) error {
|
||||
userID := common.MustUserID(c)
|
||||
|
||||
chatID, err := uuid.Parse(c.Params("chat_id"))
|
||||
if err != nil {
|
||||
return common.SendError(c, fiber.StatusBadRequest,
|
||||
common.ErrorCodeInvalidRequest, "invalid chat_id format")
|
||||
}
|
||||
|
||||
idempotencyKey := c.Get("Idempotency-Key")
|
||||
if msg := common.ValidateIdempotencyKey(idempotencyKey); msg != "" {
|
||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
||||
}
|
||||
|
||||
var req CreateMessageRequest
|
||||
if err := common.BindJSON(c, &req); err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
if msg := common.ValidateMessageText(req.Text); msg != "" {
|
||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
||||
}
|
||||
|
||||
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).JSON(message)
|
||||
}
|
||||
|
||||
func (h *Handler) ListMessages(c fiber.Ctx) error {
|
||||
userID := common.MustUserID(c)
|
||||
|
||||
chatID, err := uuid.Parse(c.Params("chat_id"))
|
||||
if err != nil {
|
||||
return common.SendError(c, fiber.StatusBadRequest,
|
||||
common.ErrorCodeInvalidRequest, "invalid chat_id format")
|
||||
}
|
||||
|
||||
limit, err := common.ParseLimit(c, 50)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
cursor, err := common.ParseCursor(c)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
page, err := h.store.ListMessages(c.Context(), userID, chatID, limit, cursor)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
return c.JSON(page)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package messages
|
||||
|
||||
import (
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
func RegisterProtectedRoutes(router fiber.Router, st *store.Store) {
|
||||
handler := NewHandler(st)
|
||||
router.Post("/chats/:chat_id/messages", handler.CreateMessage)
|
||||
router.Get("/chats/:chat_id/messages", handler.ListMessages)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Package model defines the JSON-facing domain types shared by handlers,
|
||||
// storage and the public contract.
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
PasswordHash string `json:"-"`
|
||||
CreatedAt common.RFCFormTime `json:"created_at"`
|
||||
}
|
||||
|
||||
func (u User) GetID() uuid.UUID { return u.ID }
|
||||
func (u User) GetCreatedAt() time.Time { return time.Time(u.CreatedAt) }
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
CreatedAt common.RFCFormTime `json:"created_at"`
|
||||
}
|
||||
|
||||
func (c Chat) GetID() uuid.UUID { return c.ID }
|
||||
func (c Chat) GetCreatedAt() time.Time { return time.Time(c.CreatedAt) }
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
ChatID uuid.UUID `json:"chat_id"`
|
||||
SenderID uuid.UUID `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt common.RFCFormTime `json:"created_at"`
|
||||
}
|
||||
|
||||
func (m Message) GetID() uuid.UUID { return m.ID }
|
||||
func (m Message) GetCreatedAt() time.Time { return time.Time(m.CreatedAt) }
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt common.RFCFormTime `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// Package session stores bearer sessions in Redis. Tokens are hashed before
|
||||
// they become keys, and the configured TTL is absolute.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("session not found")
|
||||
|
||||
const keyPrefix = "messenger:session:"
|
||||
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func New(rawURL string, ttl, timeout time.Duration) (*Store, error) {
|
||||
options, err := redis.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse CACHE_URL: %w", err)
|
||||
}
|
||||
options.PoolSize = 10
|
||||
options.DialTimeout = timeout
|
||||
options.ReadTimeout = timeout
|
||||
options.WriteTimeout = timeout
|
||||
options.MaxRetries = 0
|
||||
|
||||
return &Store{
|
||||
client: redis.NewClient(options),
|
||||
ttl: ttl,
|
||||
timeout: timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error {
|
||||
return s.client.Close()
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
return s.client.Ping(pingCtx).Err()
|
||||
}
|
||||
|
||||
func (s *Store) Create(ctx context.Context, userID uuid.UUID) (string, time.Time, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
expiresAt := time.Now().UTC().Add(s.ttl)
|
||||
|
||||
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
if err := s.client.Set(opCtx, keyFor(token), userID.String(), s.ttl).Err(); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
|
||||
value, err := s.client.Get(opCtx, keyFor(token)).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return uuid.Nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
|
||||
userID, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrNotFound
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func (s *Store) Revoke(ctx context.Context, token string) error {
|
||||
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
return s.client.Del(opCtx, keyFor(token)).Err()
|
||||
}
|
||||
|
||||
func keyFor(token string) string {
|
||||
sum := sha256.Sum256([]byte(strings.TrimSpace(token)))
|
||||
return keyPrefix + hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
for _, memberID := range memberIDs {
|
||||
var exists int
|
||||
err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, common.BadRequest("member_id refers to non-existent user")
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
}
|
||||
|
||||
chat := model.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
|
||||
CreatedAt: common.NowUTC(),
|
||||
}
|
||||
|
||||
if _, err = tx.Exec(ctx,
|
||||
`INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
|
||||
for _, memberID := range memberIDs {
|
||||
if _, err = tx.Exec(ctx,
|
||||
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`,
|
||||
chat.ID, memberID); err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
chat, err := scanChat(s.pool.QueryRow(ctx, `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
|
||||
WHERE c.id = $1`, chatID, userID))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, common.NotFound("chat not found")
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
cursorTime, cursorID := cursorValues(cursor)
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1
|
||||
WHERE (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`, userID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats := make([]model.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
chat, scanErr := scanChat(rows)
|
||||
if scanErr != nil {
|
||||
return nil, dbError(scanErr)
|
||||
}
|
||||
chats = append(chats, chat)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
|
||||
hasMore := len(chats) > limit
|
||||
if hasMore {
|
||||
chats = chats[:limit]
|
||||
}
|
||||
|
||||
return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil
|
||||
}
|
||||
|
||||
func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var exists int
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
|
||||
chatID, userID).Scan(&exists)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func scanChat(row rowScanner) (model.Chat, error) {
|
||||
var chat model.Chat
|
||||
var createdAt time.Time
|
||||
if err := row.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
chat.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return chat, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
pgErr, ok := errors.AsType[*pgconn.PgError](err)
|
||||
return ok && pgErr.Code == "23505"
|
||||
}
|
||||
|
||||
func dbError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return common.Conflict("resource already exists")
|
||||
case "23503", "23514", "22P02":
|
||||
return common.BadRequest("request conflicts with stored data")
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := errors.AsType[net.Error](err); ok || errors.Is(err, context.DeadlineExceeded) ||
|
||||
errors.Is(err, context.Canceled) ||
|
||||
pgconn.SafeToRetry(err) ||
|
||||
errors.Is(err, pgx.ErrTxClosed) {
|
||||
return common.Unavailable("database unavailable")
|
||||
}
|
||||
|
||||
return common.Internal()
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text, idempotencyKey string) (model.Message, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
fingerprint := sha256.Sum256([]byte(text))
|
||||
|
||||
if message, found, err := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint[:]); err != nil {
|
||||
return model.Message{}, err
|
||||
} else if found {
|
||||
return message, nil
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: common.NowUTC(),
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
tag, err := tx.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)`,
|
||||
message.ID, message.ChatID, message.SenderID, message.Text, time.Time(message.CreatedAt))
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return model.Message{}, common.NotFound("chat not found")
|
||||
}
|
||||
|
||||
expiresAt := time.Time(message.CreatedAt).Add(s.idempotencyTTL)
|
||||
tag, err = tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency
|
||||
(sender_id, chat_id, idempotency_key, request_hash, message_id, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (sender_id, chat_id, idempotency_key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
message_id = EXCLUDED.message_id,
|
||||
created_at = EXCLUDED.created_at,
|
||||
expires_at = EXCLUDED.expires_at
|
||||
WHERE message_idempotency.expires_at <= now()`,
|
||||
senderID, chatID, idempotencyKey, fingerprint[:], message.ID,
|
||||
time.Time(message.CreatedAt), expiresAt)
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
|
||||
if tag.RowsAffected() == 0 {
|
||||
rollback(tx)
|
||||
stored, found, lookupErr := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint[:])
|
||||
if lookupErr != nil {
|
||||
return model.Message{}, lookupErr
|
||||
}
|
||||
if !found {
|
||||
return model.Message{}, common.Internal()
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *Store) findIdempotentMessage(ctx context.Context, senderID, chatID uuid.UUID, idempotencyKey string, expectedHash []byte) (model.Message, bool, error) {
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
var storedHash []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, i.request_hash
|
||||
FROM message_idempotency i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
JOIN chat_members cm ON cm.chat_id = i.chat_id AND cm.user_id = i.sender_id
|
||||
WHERE i.sender_id = $1
|
||||
AND i.chat_id = $2
|
||||
AND i.idempotency_key = $3
|
||||
AND i.expires_at > now()`,
|
||||
senderID, chatID, idempotencyKey).Scan(
|
||||
&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &storedHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, false, dbError(err)
|
||||
}
|
||||
if !bytes.Equal(storedHash, expectedHash) {
|
||||
return model.Message{}, false, common.Conflict("idempotency key reused with a different message")
|
||||
}
|
||||
|
||||
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return message, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) {
|
||||
isMember, err := s.IsMember(ctx, userID, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !isMember {
|
||||
return nil, common.NotFound("chat not found")
|
||||
}
|
||||
// AGENT: Cursor context is checked only after membership, so a foreign
|
||||
// caller gets 404 and cannot probe cursor validity against someone else's chat.
|
||||
if cursor != nil && cursor.ContextID != chatID {
|
||||
return nil, common.BadRequest("bad cursor value")
|
||||
}
|
||||
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
cursorTime, cursorID := cursorValues(cursor)
|
||||
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, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages := make([]model.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
message, scanErr := scanMessage(rows)
|
||||
if scanErr != nil {
|
||||
return nil, dbError(scanErr)
|
||||
}
|
||||
messages = append(messages, message)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
|
||||
hasMore := len(messages) > limit
|
||||
if hasMore {
|
||||
messages = messages[:limit]
|
||||
}
|
||||
|
||||
return &common.Page[model.Message]{
|
||||
Items: messages,
|
||||
NextCursor: common.NextCursor(messages, hasMore, chatID),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func scanMessage(row rowScanner) (model.Message, error) {
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return message, nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// cursorValues converts an optional page cursor to the two keyset columns used
|
||||
// by every paginated query. A nil cursor means "start from the beginning".
|
||||
func cursorValues(cursor *common.CursorKeyCtx) (time.Time, uuid.UUID) {
|
||||
if cursor == nil {
|
||||
return time.Time{}, uuid.Nil
|
||||
}
|
||||
return cursor.Time, cursor.ID
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Package store contains the PostgreSQL persistence layer. It uses plain
|
||||
// parameterized SQL, one bounded pool and explicit transaction boundaries.
|
||||
// Contract errors are returned as common.AppError so HTTP status mapping stays
|
||||
// in one place.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, timeout, idempotencyTTL time.Duration) *Store {
|
||||
return &Store{pool: pool, timeout: timeout, idempotencyTTL: idempotencyTTL}
|
||||
}
|
||||
|
||||
func (s *Store) withTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, s.timeout)
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
return s.pool.Ping(pingCtx)
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const rollbackTimeout = 5 * time.Second
|
||||
|
||||
func rollback(tx pgx.Tx) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rollbackTimeout)
|
||||
defer cancel()
|
||||
_ = tx.Rollback(ctx)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
PasswordHash: passwordHash,
|
||||
CreatedAt: common.NowUTC(),
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt))
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, common.Conflict("username already taken")
|
||||
}
|
||||
return model.User{}, dbError(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByID(ctx context.Context, id uuid.UUID) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.scanUser(s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.scanUser(s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users WHERE username = $1`, username))
|
||||
}
|
||||
|
||||
func (s *Store) scanUser(row rowScanner) (model.User, error) {
|
||||
var user model.User
|
||||
var createdAt time.Time
|
||||
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &createdAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, common.NotFound("user not found")
|
||||
}
|
||||
return model.User{}, dbError(err)
|
||||
}
|
||||
user.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Package users implements registration and the current-user endpoint.
|
||||
package users
|
||||
|
||||
import (
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *store.Store
|
||||
}
|
||||
|
||||
func NewHandler(st *store.Store) *Handler {
|
||||
return &Handler{store: st}
|
||||
}
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateUser(c fiber.Ctx) error {
|
||||
var req CreateUserRequest
|
||||
if err := common.BindJSON(c, &req); err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
if msg := common.ValidateCreateUser(req.Username, req.DisplayName); msg != "" {
|
||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
||||
}
|
||||
if msg := common.ValidatePassword(req.Password); msg != "" {
|
||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
||||
}
|
||||
|
||||
hash, err := auth.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, common.Internal())
|
||||
}
|
||||
|
||||
user, err := h.store.CreateUser(c.Context(), req.Username, req.DisplayName, hash)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).JSON(user)
|
||||
}
|
||||
|
||||
func (h *Handler) GetCurrentUser(c fiber.Ctx) error {
|
||||
userID, ok := common.UserID(c)
|
||||
if !ok {
|
||||
return common.SendChallenge(c, `Bearer realm="messenger"`, "authentication required")
|
||||
}
|
||||
|
||||
user, err := h.store.GetUserByID(c.Context(), userID)
|
||||
if err != nil {
|
||||
return common.SendAppError(c, err)
|
||||
}
|
||||
|
||||
return c.JSON(user)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
func RegisterPublicRoutes(router fiber.Router, st *store.Store) {
|
||||
handler := NewHandler(st)
|
||||
router.Post("/users", handler.CreateUser)
|
||||
}
|
||||
|
||||
func RegisterProtectedRoutes(router fiber.Router, st *store.Store) {
|
||||
handler := NewHandler(st)
|
||||
router.Get("/users/me", handler.GetCurrentUser)
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
name: mtusi2026lab
|
||||
|
||||
x-api-build: &api-build
|
||||
image: mtusi2026lab-api:local
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
|
||||
x-api-environment: &api-environment
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
DB_POOL_MAX_CONNS: ${DB_POOL_MAX_CONNS:-10}
|
||||
DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable
|
||||
CACHE_URL: redis://redis:6379/0
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.10-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 5s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${POSTGRES_CPU_LIMIT:-1.0}"
|
||||
memory: "${POSTGRES_MEM_LIMIT:-512M}"
|
||||
|
||||
redis:
|
||||
image: redis:7.4.7-alpine
|
||||
restart: unless-stopped
|
||||
command:
|
||||
[
|
||||
"redis-server",
|
||||
"--appendonly",
|
||||
"yes",
|
||||
"--appendfsync",
|
||||
"everysec",
|
||||
"--save",
|
||||
"",
|
||||
]
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 3s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${REDIS_CPU_LIMIT:-0.50}"
|
||||
memory: "${REDIS_MEM_LIMIT:-256M}"
|
||||
|
||||
migrate:
|
||||
<<: *api-build
|
||||
restart: "no"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
<<: *api-environment
|
||||
MIGRATE_ONLY: "true"
|
||||
|
||||
api:
|
||||
<<: *api-build
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
environment:
|
||||
<<: *api-environment
|
||||
RUN_MIGRATIONS: "false"
|
||||
expose:
|
||||
- "8080"
|
||||
healthcheck:
|
||||
test:
|
||||
["CMD", "wget", "-q", "-O", "-", "http://127.0.0.1:8080/health/ready"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 10
|
||||
start_period: 10s
|
||||
stop_grace_period: 15s
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${API_CPU_LIMIT:-0.50}"
|
||||
memory: "${API_MEM_LIMIT:-256M}"
|
||||
|
||||
haproxy:
|
||||
image: haproxy:3.2.6-alpine
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "${LB_PORT:-8080}:8080"
|
||||
- "${HAPROXY_STATS_PORT:-8404}:8404"
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
healthcheck:
|
||||
test:
|
||||
["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/stats"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${HAPROXY_CPU_LIMIT:-0.50}"
|
||||
memory: "${HAPROXY_MEM_LIMIT:-128M}"
|
||||
|
||||
k6:
|
||||
image: grafana/k6:1.3.0
|
||||
profiles: ["load"]
|
||||
depends_on:
|
||||
haproxy:
|
||||
condition: service_healthy
|
||||
user: "0:0"
|
||||
environment:
|
||||
BASE_URL: http://haproxy:8080
|
||||
VUS: ${K6_VUS:-10}
|
||||
DURATION: ${K6_DURATION:-60s}
|
||||
volumes:
|
||||
- ./load:/scripts:ro
|
||||
- ./evidence:/results
|
||||
command: ["run", "/scripts/messages.js"]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${K6_CPU_LIMIT:-1.0}"
|
||||
memory: "${K6_MEM_LIMIT:-512M}"
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
redisdata:
|
||||
@@ -0,0 +1,68 @@
|
||||
# Доказательства уровней 3/4
|
||||
|
||||
Дата: 2026-10-26. Хост: 4 vCPU, 7.5 GiB RAM, Docker 29.3.0, Compose 5.6.0.
|
||||
Стенд: 2 API-реплики, PostgreSQL 16.10, Redis 7.4.7, HAProxy 3.2.6.
|
||||
Секреты и токены в файлы не сохранялись.
|
||||
|
||||
## Публичный smoke и сохранность
|
||||
|
||||
```text
|
||||
make check
|
||||
PASS: offline skeleton structure, local refs and Python syntax
|
||||
|
||||
make validate PYTHON=.venv/bin/python
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation
|
||||
|
||||
make test
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
PASS: persistence preserved confirmed data and existing session.
|
||||
```
|
||||
|
||||
В рабочей оболочке published ports были изолированы от хоста, поэтому
|
||||
HTTP-тесты запускались из контейнера в сети `mtusi2026lab_default`. Команды
|
||||
`Makefile` и проверяемые сценарии те же; на обычной машине они запускаются с
|
||||
хоста.
|
||||
|
||||
## Отказ реплики
|
||||
|
||||
Команда: `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`
|
||||
(эквивалентный запуск из контейнера в сети стенда).
|
||||
|
||||
| Прогон | Реплик до отказа | Успешных записей | Ошибок | Восстановление, с |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| 1 | 2 | 121 | 1 | 2.538 |
|
||||
| 2 | 2 | 121 | 0 | 2.932 |
|
||||
| 3 | 2 | 120 | 1 | 2.787 |
|
||||
| 4 | 2 | 121 | 1 | 2.661 |
|
||||
|
||||
Дополнительно вручную остановлен второй контейнер (`api-10`) через
|
||||
`TARGET_INSTANCE_ID=<hostname> scripts/stop-one.sh`: 1698 успешных записей,
|
||||
1 ошибка, после остановки трафик продолжила вторая реплика. Оба контейнера
|
||||
восстановлены командой `docker compose ... up -d --no-deps --scale api=2 api`.
|
||||
|
||||
## Конкурентная идемпотентность
|
||||
|
||||
`tests/custom/idempotency.py` отправил 12 одновременных POST с одним
|
||||
`Idempotency-Key` через HAProxy. Наблюдались 2 разные реплики; все ответы `201`
|
||||
с одним `message.id`; в истории ровно одна запись; повтор с другим телом — `409`.
|
||||
|
||||
```text
|
||||
PASS: 12 concurrent requests used 2 replicas and stored one message
|
||||
```
|
||||
|
||||
## Rolling update под нагрузкой
|
||||
|
||||
`k6`: 20 VU, 60 с, запись сообщений; во время прогона `scripts/rolling-update.sh 2`
|
||||
поочерёдно заменил обе API-реплики.
|
||||
|
||||
```text
|
||||
http_reqs: 41608
|
||||
iterations: 41605
|
||||
failed checks: 0
|
||||
p95: 55.27 ms
|
||||
p99: 71.15 ms
|
||||
```
|
||||
|
||||
Сырой summary: `evidence/k6-rolling-20vu-60s.json`.
|
||||
@@ -0,0 +1,173 @@
|
||||
{
|
||||
"metrics": {
|
||||
"checks": {
|
||||
"fails": 0,
|
||||
"passes": 83213,
|
||||
"value": 1
|
||||
},
|
||||
"data_received": {
|
||||
"count": 18932152,
|
||||
"rate": 310938.9713237004
|
||||
},
|
||||
"data_sent": {
|
||||
"count": 15354668,
|
||||
"rate": 252182.88300965153
|
||||
},
|
||||
"http_req_blocked": {
|
||||
"avg": 0.019555880263410815,
|
||||
"max": 16.957181,
|
||||
"med": 0.006217,
|
||||
"min": 0.002294,
|
||||
"p(50)": 0.006217,
|
||||
"p(95)": 0.011781500000000014,
|
||||
"p(99)": 0.24456504000000032
|
||||
},
|
||||
"http_req_connecting": {
|
||||
"avg": 0.0001791579023264757,
|
||||
"max": 1.169158,
|
||||
"med": 0,
|
||||
"min": 0,
|
||||
"p(50)": 0,
|
||||
"p(95)": 0,
|
||||
"p(99)": 0
|
||||
},
|
||||
"http_req_duration": {
|
||||
"avg": 28.19379073502721,
|
||||
"max": 1244.395337,
|
||||
"med": 23.995004,
|
||||
"min": 1.917426,
|
||||
"p(50)": 23.995004,
|
||||
"p(95)": 55.274196450000005,
|
||||
"p(99)": 71.1459338
|
||||
},
|
||||
"http_req_duration{expected_response:true}": {
|
||||
"avg": 28.19379073502721,
|
||||
"max": 1244.395337,
|
||||
"med": 23.995004,
|
||||
"min": 1.917426,
|
||||
"p(50)": 23.995004,
|
||||
"p(95)": 55.274196450000005,
|
||||
"p(99)": 71.1459338
|
||||
},
|
||||
"http_req_failed": {
|
||||
"fails": 41608,
|
||||
"passes": 0,
|
||||
"value": 0
|
||||
},
|
||||
"http_req_receiving": {
|
||||
"avg": 0.18104418227264027,
|
||||
"max": 18.158135,
|
||||
"med": 0.064632,
|
||||
"min": 0.020427,
|
||||
"p(50)": 0.064632,
|
||||
"p(95)": 0.6289225000000005,
|
||||
"p(99)": 2.5293797500000004
|
||||
},
|
||||
"http_req_sending": {
|
||||
"avg": 0.09656115958469512,
|
||||
"max": 28.421382,
|
||||
"med": 0.0250795,
|
||||
"min": 0.010067,
|
||||
"p(50)": 0.0250795,
|
||||
"p(95)": 0.2945132000000001,
|
||||
"p(99)": 1.6073071800000003
|
||||
},
|
||||
"http_req_tls_handshaking": {
|
||||
"avg": 0,
|
||||
"max": 0,
|
||||
"med": 0,
|
||||
"min": 0,
|
||||
"p(50)": 0,
|
||||
"p(95)": 0,
|
||||
"p(99)": 0
|
||||
},
|
||||
"http_req_waiting": {
|
||||
"avg": 27.91618539316964,
|
||||
"max": 1244.2995,
|
||||
"med": 23.724883,
|
||||
"min": 1.841486,
|
||||
"p(50)": 23.724883,
|
||||
"p(95)": 54.91490730000001,
|
||||
"p(99)": 70.85231543
|
||||
},
|
||||
"http_reqs": {
|
||||
"count": 41608,
|
||||
"rate": 683.3638732055672
|
||||
},
|
||||
"iteration_duration": {
|
||||
"avg": 28.79506371409711,
|
||||
"max": 1244.572308,
|
||||
"med": 24.606595,
|
||||
"min": 2.078469,
|
||||
"p(50)": 24.606595,
|
||||
"p(95)": 55.85472899999998,
|
||||
"p(99)": 71.58917543999998
|
||||
},
|
||||
"iterations": {
|
||||
"count": 41605,
|
||||
"rate": 683.3146016323213
|
||||
},
|
||||
"vus": {
|
||||
"max": 20,
|
||||
"min": 20,
|
||||
"value": 20
|
||||
},
|
||||
"vus_max": {
|
||||
"max": 20,
|
||||
"min": 20,
|
||||
"value": 20
|
||||
}
|
||||
},
|
||||
"root_group": {
|
||||
"checks": {
|
||||
"instance header": {
|
||||
"fails": 0,
|
||||
"id": "5eee12e230ebaeb27a5ba544fcce920f",
|
||||
"name": "instance header",
|
||||
"passes": 41605,
|
||||
"path": "::instance header"
|
||||
},
|
||||
"message 201": {
|
||||
"fails": 0,
|
||||
"id": "6445aff337e1ade0bc10402fbac79882",
|
||||
"name": "message 201",
|
||||
"passes": 41605,
|
||||
"path": "::message 201"
|
||||
}
|
||||
},
|
||||
"groups": {
|
||||
"setup": {
|
||||
"checks": {
|
||||
"chat 201": {
|
||||
"fails": 0,
|
||||
"id": "1e2d5cbe7afc66d31563ad87ae39a13f",
|
||||
"name": "chat 201",
|
||||
"passes": 1,
|
||||
"path": "::setup::chat 201"
|
||||
},
|
||||
"login 201": {
|
||||
"fails": 0,
|
||||
"id": "6b4ee6c971082051e34713d1c1baafa1",
|
||||
"name": "login 201",
|
||||
"passes": 1,
|
||||
"path": "::setup::login 201"
|
||||
},
|
||||
"register 201": {
|
||||
"fails": 0,
|
||||
"id": "09b4317cf1f0cccb084b00576cc103e4",
|
||||
"name": "register 201",
|
||||
"passes": 1,
|
||||
"path": "::setup::register 201"
|
||||
}
|
||||
},
|
||||
"groups": {},
|
||||
"id": "5c0f8025f7e0b6654089e5b00e950f1a",
|
||||
"name": "setup",
|
||||
"path": "::setup"
|
||||
}
|
||||
},
|
||||
"id": "d41d8cd98f00b204e9800998ecf8427e",
|
||||
"name": "",
|
||||
"path": ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 4096
|
||||
|
||||
defaults
|
||||
log global
|
||||
mode http
|
||||
option httplog
|
||||
option dontlognull
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 30s
|
||||
timeout http-request 10s
|
||||
timeout http-keep-alive 30s
|
||||
retries 2
|
||||
option redispatch
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
|
||||
frontend api_frontend
|
||||
bind *:8080
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2
|
||||
server-template api 4 api:8080 resolvers docker init-addr last,libc,none
|
||||
|
||||
frontend stats
|
||||
bind *:8404
|
||||
http-request use-service prometheus-exporter if { path /metrics }
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 5s
|
||||
@@ -0,0 +1,70 @@
|
||||
import http from 'k6/http';
|
||||
import encoding from 'k6/encoding';
|
||||
import { check } from 'k6';
|
||||
|
||||
const baseURL = __ENV.BASE_URL || 'http://localhost:8080';
|
||||
const vus = Number(__ENV.VUS || 10);
|
||||
const duration = __ENV.DURATION || '60s';
|
||||
|
||||
export const options = {
|
||||
scenarios: {
|
||||
writes: {
|
||||
executor: 'constant-vus',
|
||||
vus,
|
||||
duration,
|
||||
},
|
||||
},
|
||||
summaryTrendStats: ['avg', 'min', 'med', 'p(50)', 'p(95)', 'p(99)', 'max'],
|
||||
};
|
||||
|
||||
function headers(token) {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
};
|
||||
}
|
||||
|
||||
export function setup() {
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
|
||||
const username = `u_load_${suffix}`.slice(0, 32);
|
||||
const password = `Load-${suffix}-pass`;
|
||||
|
||||
const registration = http.post(
|
||||
`${baseURL}/api/v1/users`,
|
||||
JSON.stringify({ username, display_name: 'Load test', password }),
|
||||
{ headers: { 'Content-Type': 'application/json', Accept: 'application/json' } },
|
||||
);
|
||||
check(registration, { 'register 201': (r) => r.status === 201 });
|
||||
const user = registration.json();
|
||||
|
||||
const basic = encoding.b64encode(`${username}:${password}`);
|
||||
const login = http.post(`${baseURL}/api/v1/auth/sessions`, null, {
|
||||
headers: { Authorization: `Basic ${basic}`, Accept: 'application/json' },
|
||||
});
|
||||
check(login, { 'login 201': (r) => r.status === 201 });
|
||||
const token = login.json('token');
|
||||
|
||||
const chat = http.post(
|
||||
`${baseURL}/api/v1/chats`,
|
||||
JSON.stringify({ title: 'Load profile', member_ids: [user.id] }),
|
||||
{ headers: headers(token) },
|
||||
);
|
||||
check(chat, { 'chat 201': (r) => r.status === 201 });
|
||||
|
||||
return { token, chatID: chat.json('id') };
|
||||
}
|
||||
|
||||
export default function (data) {
|
||||
const key = `${__VU}-${__ITER}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
const response = http.post(
|
||||
`${baseURL}/api/v1/chats/${data.chatID}/messages`,
|
||||
JSON.stringify({ text: `load message ${key}` }),
|
||||
{ headers: { ...headers(data.token), 'Idempotency-Key': key } },
|
||||
);
|
||||
|
||||
check(response, {
|
||||
'message 201': (r) => r.status === 201,
|
||||
'instance header': (r) => Boolean(r.headers['X-Instance-Id'] || r.headers['x-instance-id']),
|
||||
});
|
||||
}
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env restart postgres redis haproxy api
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
COMPOSE="docker compose --env-file .env"
|
||||
N=${1:-$($COMPOSE ps -q api | wc -l)}
|
||||
[ "$N" -ge 2 ] || {
|
||||
echo "need at least two API replicas; got $N" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
wait_healthy() {
|
||||
attempts=0
|
||||
while [ "$attempts" -lt 90 ]; do
|
||||
ids=$($COMPOSE ps -q api)
|
||||
count=$(printf '%s\n' "$ids" | sed '/^$/d' | wc -l)
|
||||
healthy=$(for id in $ids; do docker inspect -f '{{.State.Health.Status}}' "$id"; done | grep -c '^healthy$' || true)
|
||||
if [ "$count" -eq "$N" ] && [ "$healthy" -eq "$N" ]; then
|
||||
return 0
|
||||
fi
|
||||
attempts=$((attempts + 1))
|
||||
sleep 1
|
||||
done
|
||||
echo "API replicas did not become healthy in time" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
$COMPOSE build api
|
||||
i=0
|
||||
while [ "$i" -lt "$N" ]; do
|
||||
target=$($COMPOSE ps -q api | head -n 1)
|
||||
[ -n "$target" ] || {
|
||||
echo "no API container to replace" >&2
|
||||
exit 2
|
||||
}
|
||||
echo "replacing $target"
|
||||
docker stop --time 10 "$target" >/dev/null
|
||||
docker rm "$target" >/dev/null
|
||||
$COMPOSE up -d --no-deps --no-recreate --scale api="$N" api
|
||||
wait_healthy
|
||||
i=$((i + 1))
|
||||
done
|
||||
echo "rolling replacement complete for $N replicas"
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
target=""
|
||||
for id in $(docker compose --env-file .env ps -q api); do
|
||||
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$id")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
target="$id"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$target" ]; then
|
||||
echo "no running API replica has instance id $TARGET_INSTANCE_ID" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
docker stop --time 5 "$target" >/dev/null
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
# The public smoke checks sequential replay;
|
||||
# this test checks the cross-replica race.
|
||||
import argparse
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Concurrent idempotency check through the load balancer"
|
||||
)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--ca-file", default=None)
|
||||
parser.add_argument("--requests", type=int, default=12)
|
||||
args = parser.parse_args()
|
||||
|
||||
setup = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = setup.bootstrap()
|
||||
key = "concurrent-" + uuid.uuid4().hex
|
||||
body = {"text": "one concurrent message"}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
results = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker():
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
try:
|
||||
response = client.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
body=body,
|
||||
headers={"Idempotency-Key": key},
|
||||
schema="Message",
|
||||
)
|
||||
with lock:
|
||||
results.append(
|
||||
(response["json"], response["headers"].get("X-Instance-Id"))
|
||||
)
|
||||
except Failure as error:
|
||||
with lock:
|
||||
results.append((error, None))
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(args.requests)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
check(len(results) == args.requests, "not every concurrent request finished")
|
||||
check(
|
||||
all(isinstance(message, dict) for message, _ in results),
|
||||
"a concurrent request failed",
|
||||
)
|
||||
ids = {message["id"] for message, _ in results}
|
||||
check(len(ids) == 1, "concurrent requests returned different message IDs")
|
||||
instances = {instance for _, instance in results if instance}
|
||||
check(
|
||||
len(instances) >= 2, "expected the load balancer to use at least two replicas"
|
||||
)
|
||||
|
||||
page = setup.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")[
|
||||
"json"
|
||||
]
|
||||
stored = [message for message in page["items"] if message["id"] == next(iter(ids))]
|
||||
check(len(stored) == 1, "concurrent requests stored more than one message")
|
||||
|
||||
setup.call(
|
||||
"POST",
|
||||
path,
|
||||
409,
|
||||
actor=alice,
|
||||
body={"text": "different body"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
print(
|
||||
f"PASS: {args.requests} concurrent requests used {len(instances)} replicas and stored one message"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user