forked from mtusi2026/mtusi2026lab3
на оценку 3
This commit is contained in:
+3
-1
@@ -1,9 +1,11 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# The transferred lab2 baseline still needs its Compose topology adapted to lab3.
|
||||
# Compose publishes only the load balancer; API replicas stay on its network.
|
||||
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
# INSTANCE_ID is intentionally unset: each container uses its own hostname.
|
||||
# INSTANCE_ID=api-replica-01
|
||||
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_DB=messenger
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Чурилин, БВТ2301
|
||||
- Текущий завершённый уровень: оценка «3»
|
||||
- Итоговая цель: оценка «5»; трек будет выбран после реализации уровня «4»
|
||||
- Commit/PR: заполняется автором после локального коммита и публикации
|
||||
- Использованные источники и библиотеки: преподавательские README/OpenAPI/tests,
|
||||
документация Go, pgx, PostgreSQL, Docker Compose и Nginx. Для разбора
|
||||
архитектуры, рефакторинга, реализации и проверок использовался OpenAI Codex;
|
||||
решения проверены тестами и описанными ниже воспроизводимыми сценариями.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
@@ -23,8 +27,32 @@ chmod 600 secrets/*.txt
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Полная последовательность запуска, проверки LB и безопасной остановки будет
|
||||
зафиксирована после завершения новой Compose-топологии lab3.
|
||||
Единственная публичная точка входа — `http://localhost:8080`; контейнеры API не
|
||||
публикуют порты на host. Последовательность запуска и проверки:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait
|
||||
make test
|
||||
make test-failover ACTION_SCRIPT=./scripts/stop-one.sh
|
||||
docker compose --env-file .env up -d --wait api
|
||||
make test-persistence ACTION_SCRIPT=./scripts/restart.sh
|
||||
```
|
||||
|
||||
`stop-one.sh` оставляет выбранную тестом реплику остановленной. Команда `up` в
|
||||
примере явно возвращает желаемые две реплики перед следующей проверкой.
|
||||
Обычная остановка не удаляет named volumes:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env down
|
||||
```
|
||||
|
||||
Для демонстрации балансировки одним и тем же клиентом можно многократно вызвать
|
||||
любой API endpoint через `localhost:8080` и сравнить `X-Instance-Id`. В проверке
|
||||
20 последовательных health-запросов наблюдались оба процесса: 10 ответов от
|
||||
одной реплики и 10 от другой. Запрос `/health/ready` непосредственно из Windows
|
||||
PowerShell вернул HTTP 200 и `X-Instance-Id`, поэтому браузер Windows и будущий
|
||||
frontend смогут использовать тот же `http://localhost:8080`.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
@@ -45,6 +73,18 @@ PostgreSQL остаётся источником истины для польз
|
||||
чата; его отказ не делает API неготовым и не отменяет подтверждённую запись в
|
||||
PostgreSQL.
|
||||
|
||||
Compose запускает один сервис `api` с `API_REPLICAS=2`. Реплики не имеют host
|
||||
ports и разделяют PostgreSQL, включая таблицу сессий. Nginx — единственная
|
||||
публичная точка входа; он использует `least_conn` и Docker DNS resolver с
|
||||
повторным разрешением имени `api` раз в секунду. Sticky sessions не применяются.
|
||||
Безопасные методы могут быть перенаправлены на другую реплику при сетевой ошибке.
|
||||
Произвольные POST балансировщик автоматически не повторяет: после
|
||||
неопределённого результата повтор сообщения выполняет клиент с тем же
|
||||
`Idempotency-Key`, а создание пользователя/чата контрактом не идемпотентно.
|
||||
|
||||
Миграции вынесены в одноразовый сервис `migrate`, завершение которого является
|
||||
предусловием запуска API. Поэтому две реплики не конкурируют за изменение схемы.
|
||||
|
||||
Пагинационный курсор теперь формируется в application-слое из канонических
|
||||
полей границы `(created_at, id, scope_id)` и подписывается HMAC-SHA-256. Подпись
|
||||
не скрывает payload, но обнаруживает подмену. В scope входит пользователь для
|
||||
@@ -54,29 +94,78 @@ secret `cursor_signing_key`. Репозитории получают тольк
|
||||
типизированную границу и ничего не знают о формате HTTP-курсора.
|
||||
|
||||
`.env.example` перечисляет реально читаемые приложением параметры PostgreSQL,
|
||||
пула, readiness/shutdown, Redis-кэша и ключа курсора. `API_REPLICAS` и
|
||||
`IDEMPOTENCY_TTL_SECONDS` зарезервированы для следующих этапов lab3. Секретных
|
||||
значений в шаблоне нет: там указаны только пути внутри контейнера.
|
||||
пула, readiness/shutdown, Redis-кэша, числа реплик, TTL идемпотентности и ключа
|
||||
курсора. `API_REPLICAS` используется Compose, а `IDEMPOTENCY_TTL_SECONDS` читает
|
||||
Go-приложение и не допускает значение меньше 86400 секунд. Секретных значений в
|
||||
шаблоне нет: там указаны только пути внутри контейнера.
|
||||
|
||||
Каждый процесс определяет стабильный `instance_id` один раз при загрузке
|
||||
конфигурации. По умолчанию используется hostname контейнера; это одновременно
|
||||
даёт уникальность между Compose-репликами и позволяет инфраструктурному hook
|
||||
сопоставить `X-Instance-Id` с конкретным контейнером. Опциональный `INSTANCE_ID`
|
||||
проверяется по безопасному для HTTP-заголовка шаблону. Сам middleware является
|
||||
внешним относительно router/recovery, поэтому заголовок присутствует также на
|
||||
health, 404/405 и восстановленных 500-ответах.
|
||||
|
||||
POST сообщения принимает только ASCII-ключ по шаблону
|
||||
`[A-Za-z0-9._:-]{1,128}`. HTTP-слой нормализует UUID чата и формирует канонический
|
||||
path, application-слой хэширует SHA-256 не исходные bytes JSON, а типизированное
|
||||
семантическое представление запроса. Поэтому форматирование и порядок JSON-полей
|
||||
не влияют на повтор; задел под `attachment_ids` уже канонизирует отсутствующий
|
||||
список как пустой.
|
||||
|
||||
Область уникальности в `message_idempotency` состоит из пользователя, метода,
|
||||
канонического пути и ключа. В одной PostgreSQL-транзакции сначала захватывается
|
||||
эта область через primary key, затем создаётся Message. Отложенный foreign key
|
||||
позволяет заранее записать будущий `message_id`, но проверяется при commit. При
|
||||
гонке вторая реплика ждёт разрешения уникального конфликта и затем либо возвращает
|
||||
то же сообщение, либо отвечает 409 при другом request hash. Любая ошибка до
|
||||
commit откатывает и бизнес-эффект, и запись ключа, поэтому transient 5xx не
|
||||
фиксируется как успешный результат. Перед replay снова выполняются обычная
|
||||
проверка bearer-сессии и проверка членства в чате.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Воспроизводимая конфигурация и качество Go | `make check && make go-check && make validate PYTHON=../mtusi2026lab2/.venv/bin/python` | форматирование, tests, race detector, vet, Compose config и OpenAPI validation завершились без ошибок | `evidence/lab3-summary.md` |
|
||||
| Две API-реплики за одним LB | `docker compose --env-file .env up -d --build --wait`; 20 health-запросов через `:8080` | наружу опубликован только Nginx; два разных `X-Instance-Id`, по 10 ответов от каждого | `compose.yaml`, `infrastructure/nginx/nginx.conf`, `evidence/lab3-summary.md` |
|
||||
| Публичный smoke lab3 | `make test` | `tests/smoke.py` завершился `PASS: lab3 public API scenario` | `evidence/lab3-summary.md` |
|
||||
| Общая сессия без sticky routing | smoke, затем failover и persistence через тот же bearer token | обе реплики обслуживали запросы; сессия работает после остановки API и рестартов | `evidence/lab3-summary.md` |
|
||||
| Идемпотентность сообщения | `go test ./student_tests -run Idempotency`; 32 конкурентных POST с одним ключом через LB | один Message и ровно одна строка в PostgreSQL; другой payload даёт 409 | `student_tests/idempotency_test.go`, `evidence/lab3-summary.md` |
|
||||
| Failover каждой API-реплики | два последовательных запуска `make test-failover ACTION_SCRIPT=./scripts/stop-one.sh` с восстановлением между ними | реально остановлены `api-2`, затем `api-1`; получено 142/143 успешных записи, 0 ошибок, восстановление 0.963/0.750 с | `scripts/stop-one.sh`, `evidence/lab3-summary.md` |
|
||||
| Persistence после рестартов | `make test-persistence ACTION_SCRIPT=./scripts/restart.sh` | PASS; прежняя сессия и данные доступны после рестарта PostgreSQL, Redis, API и LB | `scripts/restart.sh`, `evidence/lab3-summary.md` |
|
||||
| Миграции перед API | `docker compose --env-file .env ps -a` и логи `migrate` | миграции 1 и 2 применены; one-shot контейнер завершился с кодом 0; API healthy | `migrations/000002_message_idempotency.up.sql`, `evidence/lab3-summary.md` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Проведены функциональные эксперименты устойчивости, а не capacity benchmark.
|
||||
Окружение: Windows + WSL2, Docker Engine 29.7.2, Docker Compose 5.5.0, две
|
||||
API-реплики; лимиты CPU/RAM пока не задавались, максимальный пул БД —
|
||||
10 соединений на реплику. Использовались синтетические данные; отдельного прогрева
|
||||
и серии повторов не было. Поэтому результаты подтверждают корректность failover,
|
||||
идемпотентности и сохранности данных, но не предельный RPS или p50/p95/p99.
|
||||
Нагрузочный профиль с лимитами и повторами относится к следующему уровню.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Последовательная остановка `api-2` и `api-1` с восстановлением между тестами | LB обслуживает через оставшуюся реплику не позднее 10 с | 142 и 143 успешные записи; в обоих запусках 0 ошибок | первое восстановление 0.963 и 0.750 с; подтверждённой потери или дублей нет |
|
||||
| Рестарт PostgreSQL, Redis, API и LB без удаления volumes | прежний token и данные сохраняются | `test-persistence` завершился PASS | уложилось в тайм-аут 90 с; потери данных нет |
|
||||
| 32 одновременных POST с одним `Idempotency-Key` | один бизнес-эффект | 32 ответа 201 с одним Message ID; в БД одно сообщение | дубли отсутствуют |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Топология однохостовая: Nginx и PostgreSQL остаются single points of failure.
|
||||
Репликация БД и несколько балансировщиков в требования уровня «3» не входят.
|
||||
- Redis содержит только кэш, поэтому его потеря допустима. Отдельная
|
||||
персистентность Redis для корректности API не требуется.
|
||||
- Истёкшие записи идемпотентности удаляются лениво при повторном обращении к той
|
||||
же области ключа. Индекс по `expires_at` оставлен для будущей периодической
|
||||
очистки без изменения схемы.
|
||||
- Resource limits, количественный нагрузочный эксперимент и сценарий rolling
|
||||
update ещё не реализованы; это следующий этап уровня «4».
|
||||
- Frontend на React + TypeScript + Vite будет отдельным этапом и отдельным
|
||||
коммитом после фиксации уровня «3». Тогда же будет спроектирована cookie-based
|
||||
авторизация с учётом текущего bearer-контракта API.
|
||||
- Трек уровня «5» пока не заявлен: сначала необходимо завершить и измерить
|
||||
обязательный уровень «4».
|
||||
|
||||
+12
-2
@@ -85,7 +85,12 @@ func main() {
|
||||
log.Fatalf("[FATAL] Invalid cursor configuration: %v", err)
|
||||
}
|
||||
|
||||
service, err := application.NewService(applicationStore, cursorCodec, cfg.SessionTTL)
|
||||
service, err := application.NewService(
|
||||
applicationStore,
|
||||
cursorCodec,
|
||||
cfg.SessionTTL,
|
||||
application.WithIdempotencyTTL(cfg.IdempotencyTTL),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatalf("[FATAL] Application initialization failed: %v", err)
|
||||
}
|
||||
@@ -149,6 +154,7 @@ func main() {
|
||||
rootHandler = middleware.Recovery(rootHandler)
|
||||
rootHandler = middleware.Logger(rootHandler)
|
||||
rootHandler = middleware.RequestID(rootHandler)
|
||||
rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: cfg.HTTPAddress(),
|
||||
@@ -161,7 +167,11 @@ func main() {
|
||||
serverErrors := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Printf("[INFO] Server starting on %s", server.Addr)
|
||||
log.Printf(
|
||||
"[INFO] Server instance %s starting on %s",
|
||||
cfg.InstanceID,
|
||||
server.Addr,
|
||||
)
|
||||
serverErrors <- server.ListenAndServe()
|
||||
}()
|
||||
|
||||
|
||||
+29
-2
@@ -1,4 +1,26 @@
|
||||
services:
|
||||
load-balancer:
|
||||
image: nginx:1.30.6-alpine@sha256:970364228b1e4f932abc22d321932816782cca8a20b85a77552a7cfe9acfb3b5
|
||||
ports:
|
||||
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
||||
volumes:
|
||||
- ./infrastructure/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD-SHELL",
|
||||
"wget -qO- http://127.0.0.1:8080/health/ready || exit 1",
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 3s
|
||||
stop_grace_period: 10s
|
||||
restart: unless-stopped
|
||||
|
||||
postgres:
|
||||
image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
|
||||
environment:
|
||||
@@ -72,6 +94,7 @@ services:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
SESSION_STORE: ${SESSION_STORE:-postgres}
|
||||
CURSOR_SIGNING_KEY_FILE: ${CURSOR_SIGNING_KEY_FILE:-/run/secrets/cursor_signing_key}
|
||||
|
||||
@@ -95,13 +118,17 @@ services:
|
||||
secrets:
|
||||
- database_url
|
||||
- cursor_signing_key
|
||||
ports:
|
||||
- "${APP_PORT:-8080}:${APP_PORT:-8080}"
|
||||
expose:
|
||||
- "8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# Lab 3 verification summary
|
||||
|
||||
Дата проверки: 2026-10-20.
|
||||
|
||||
Файл содержит обезличенную сводку воспроизводимых проверок. Bearer tokens,
|
||||
пароли, ключи идемпотентности, UUID пользователей/чатов/сообщений и содержимое
|
||||
локальных Docker secrets намеренно не сохранены.
|
||||
|
||||
## Окружение
|
||||
|
||||
- Windows + WSL2;
|
||||
- Docker Engine 29.7.2;
|
||||
- Docker Compose 5.5.0;
|
||||
- две Compose-реплики сервиса `api`;
|
||||
- единственный опубликованный endpoint: Nginx на `127.0.0.1:8080`;
|
||||
- PostgreSQL и Redis доступны только внутри Compose network.
|
||||
|
||||
## Статические проверки
|
||||
|
||||
```text
|
||||
go test ./... PASS
|
||||
go test -race ./... PASS
|
||||
go vet ./... PASS
|
||||
make check PASS
|
||||
make validate PASS
|
||||
docker compose config PASS
|
||||
shell syntax for hooks PASS
|
||||
```
|
||||
|
||||
`make validate` запускался с Python virtual environment, где установлены
|
||||
зависимости преподавательского validator.
|
||||
|
||||
## Топология и smoke
|
||||
|
||||
- migration 1 and migration 2 applied successfully;
|
||||
- one-shot service `migrate` exited with code 0;
|
||||
- оба API-контейнера перешли в `healthy`;
|
||||
- 20 последовательных запросов к health через LB вернули два разных
|
||||
`X-Instance-Id`: распределение 10/10;
|
||||
- Windows PowerShell получил HTTP 200 и `X-Instance-Id` с
|
||||
`http://localhost:8080/health/ready`;
|
||||
- преподавательский `python3 tests/smoke.py` завершился строкой
|
||||
`PASS: lab3 public API scenario`.
|
||||
|
||||
## Failover API
|
||||
|
||||
Команда:
|
||||
|
||||
```bash
|
||||
make test-failover ACTION_SCRIPT=./scripts/stop-one.sh
|
||||
```
|
||||
|
||||
Наблюдение преподавательского теста:
|
||||
|
||||
```text
|
||||
run 1:
|
||||
stopped container: api-2
|
||||
observed instances before action: 2
|
||||
successful writes / failures: 142 / 0
|
||||
first recovery: 0.963 seconds
|
||||
run 2, after restoring api-2:
|
||||
stopped container: api-1
|
||||
observed instances before action: 2
|
||||
successful writes / failures: 143 / 0
|
||||
first recovery: 0.750 seconds
|
||||
both results: PASS
|
||||
```
|
||||
|
||||
После первого запуска реплика была восстановлена; один health-запрос сдвинул
|
||||
очередь LB, чтобы следующий synthetic message выбрал второй target. Hook
|
||||
сопоставил `TARGET_INSTANCE_ID` с hostname контейнера и в каждом запуске
|
||||
остановил только выбранную API-реплику. После тестов желаемое число
|
||||
реплик было восстановлено командой `docker compose up -d --wait api`.
|
||||
|
||||
## Persistence и идемпотентность
|
||||
|
||||
- `make test-persistence ACTION_SCRIPT=./scripts/restart.sh`: PASS; после
|
||||
рестарта PostgreSQL, Redis, всех API-реплик и Nginx прежние bearer session и
|
||||
созданные данные сохранились;
|
||||
- 32 конкурентных POST сообщения с одинаковыми semantic payload и
|
||||
`Idempotency-Key` через Nginx вернули один Message ID;
|
||||
- прямой запрос PostgreSQL подтвердил ровно одну строку сообщения;
|
||||
- повтор с тем же scope/key и другим payload возвращает HTTP 409.
|
||||
@@ -0,0 +1,41 @@
|
||||
worker_processes auto;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
resolver 127.0.0.11 valid=1s ipv6=off;
|
||||
|
||||
upstream api_backend {
|
||||
zone api_backend 64k;
|
||||
least_conn;
|
||||
server api:8080 resolve max_fails=1 fail_timeout=1s;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
|
||||
location / {
|
||||
proxy_pass http://api_backend;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 1s;
|
||||
proxy_send_timeout 20s;
|
||||
proxy_read_timeout 20s;
|
||||
|
||||
# Safe methods may transparently move to another healthy peer.
|
||||
# Nginx deliberately does not retry non-idempotent POST requests:
|
||||
# the client retries message POSTs with its Idempotency-Key.
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,21 +15,36 @@ type memorySession struct {
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type memoryIdempotencyScope struct {
|
||||
actorID string
|
||||
method string
|
||||
canonicalPath string
|
||||
key string
|
||||
}
|
||||
|
||||
type memoryIdempotencyResult struct {
|
||||
requestHash [32]byte
|
||||
message domain.Message
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type MemoryRepository struct {
|
||||
legacy *MemoryStore
|
||||
|
||||
mu sync.RWMutex
|
||||
passwordByUserID map[string]string
|
||||
userIDByUsername map[string]string
|
||||
sessionsByHashKey map[[32]byte]memorySession
|
||||
mu sync.RWMutex
|
||||
passwordByUserID map[string]string
|
||||
userIDByUsername map[string]string
|
||||
sessionsByHashKey map[[32]byte]memorySession
|
||||
idempotencyByScope map[memoryIdempotencyScope]memoryIdempotencyResult
|
||||
}
|
||||
|
||||
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
|
||||
return &MemoryRepository{
|
||||
legacy: legacy,
|
||||
passwordByUserID: make(map[string]string),
|
||||
userIDByUsername: make(map[string]string),
|
||||
sessionsByHashKey: make(map[[32]byte]memorySession),
|
||||
legacy: legacy,
|
||||
passwordByUserID: make(map[string]string),
|
||||
userIDByUsername: make(map[string]string),
|
||||
sessionsByHashKey: make(map[[32]byte]memorySession),
|
||||
idempotencyByScope: make(map[memoryIdempotencyScope]memoryIdempotencyResult),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,17 +144,49 @@ func (r *MemoryRepository) GetChatsForUser(
|
||||
return r.legacy.GetChatsForUser(userID, limit, cursor)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateMessage(
|
||||
func (r *MemoryRepository) CreateMessageIdempotently(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
write application.IdempotentMessageWrite,
|
||||
) (domain.Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
return r.legacy.CreateMessage(chatID, senderID, text)
|
||||
scope := memoryIdempotencyScope{
|
||||
actorID: write.ActorID,
|
||||
method: write.Method,
|
||||
canonicalPath: write.CanonicalPath,
|
||||
key: write.Key,
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
if stored, exists := r.idempotencyByScope[scope]; exists {
|
||||
if stored.expiresAt.After(now) {
|
||||
if stored.requestHash != write.RequestHash {
|
||||
return domain.Message{}, application.ErrIdempotencyConflict
|
||||
}
|
||||
return stored.message, nil
|
||||
}
|
||||
delete(r.idempotencyByScope, scope)
|
||||
}
|
||||
|
||||
message, err := r.legacy.CreateMessage(write.ChatID, write.ActorID, write.Text)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
r.idempotencyByScope[scope] = memoryIdempotencyResult{
|
||||
requestHash: write.RequestHash,
|
||||
message: message,
|
||||
expiresAt: now.Add(write.TTL),
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetMessages(
|
||||
|
||||
@@ -1,33 +1,172 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab3/internal/application"
|
||||
"mtusi2026lab3/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateMessage(
|
||||
func (s *PostgreSQLStore) CreateMessageIdempotently(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
write application.IdempotentMessageWrite,
|
||||
) (domain.Message, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
message := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("begin idempotent message transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = transaction.Rollback(queryContext) }()
|
||||
|
||||
var isMember bool
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
`,
|
||||
write.ChatID,
|
||||
write.ActorID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
_, err = transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1
|
||||
AND method = $2
|
||||
AND canonical_path = $3
|
||||
AND idempotency_key = $4
|
||||
AND expires_at <= CURRENT_TIMESTAMP
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("delete expired idempotency key: %w", err)
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: write.ChatID,
|
||||
SenderID: write.ActorID,
|
||||
Text: write.Text,
|
||||
}
|
||||
|
||||
var storedHash []byte
|
||||
var storedMessageID string
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO message_idempotency (
|
||||
user_id,
|
||||
method,
|
||||
canonical_path,
|
||||
idempotency_key,
|
||||
request_hash,
|
||||
message_id,
|
||||
expires_at
|
||||
)
|
||||
VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
CURRENT_TIMESTAMP + $7 * INTERVAL '1 second'
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING request_hash, message_id::text
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
write.RequestHash[:],
|
||||
message.ID,
|
||||
int64(write.TTL/time.Second),
|
||||
).Scan(&storedHash, &storedMessageID)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT request_hash, message_id::text
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1
|
||||
AND method = $2
|
||||
AND canonical_path = $3
|
||||
AND idempotency_key = $4
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
).Scan(&storedHash, &storedMessageID)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("read idempotency result: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(storedHash, write.RequestHash[:]) {
|
||||
return domain.Message{}, application.ErrIdempotencyConflict
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE id = $1
|
||||
`,
|
||||
storedMessageID,
|
||||
).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("commit idempotency replay: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("claim idempotency key: %w", err)
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO messages (
|
||||
@@ -36,14 +175,7 @@ func (s *PostgreSQLStore) CreateMessage(
|
||||
sender_id,
|
||||
text
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4
|
||||
FROM chat_members
|
||||
WHERE chat_id = $2
|
||||
AND user_id = $3
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at
|
||||
`,
|
||||
message.ID,
|
||||
@@ -51,18 +183,15 @@ func (s *PostgreSQLStore) CreateMessage(
|
||||
message.SenderID,
|
||||
message.Text,
|
||||
).Scan(&message.CreatedAt)
|
||||
|
||||
if err == nil {
|
||||
return message, nil
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
// INSERT ... SELECT возвращает zero rows, если отправитель
|
||||
// не является участником указанного чата.
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, ErrNotFound
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
|
||||
}
|
||||
|
||||
return domain.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetMessages(
|
||||
|
||||
@@ -18,7 +18,10 @@ type CreateChatCommand struct {
|
||||
}
|
||||
|
||||
type SendMessageCommand struct {
|
||||
ActorID string
|
||||
ChatID string
|
||||
Text string
|
||||
ActorID string
|
||||
ChatID string
|
||||
Text string
|
||||
Method string
|
||||
CanonicalPath string
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
@@ -3,8 +3,9 @@ package application
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrCredentialState = errors.New("invalid stored credential state")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrCredentialState = errors.New("invalid stored credential state")
|
||||
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
|
||||
)
|
||||
|
||||
@@ -2,16 +2,41 @@ package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab3/internal/domain"
|
||||
)
|
||||
|
||||
type canonicalMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
|
||||
if err := domain.ValidateMessageText(command.Text); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
return s.repository.CreateMessage(ctx, command.ChatID, command.ActorID, command.Text)
|
||||
|
||||
canonicalBody, err := json.Marshal(canonicalMessageRequest{
|
||||
Text: command.Text,
|
||||
AttachmentIDs: make([]string, 0),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
|
||||
}
|
||||
|
||||
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
|
||||
ActorID: command.ActorID,
|
||||
ChatID: command.ChatID,
|
||||
Text: command.Text,
|
||||
Method: command.Method,
|
||||
CanonicalPath: command.CanonicalPath,
|
||||
Key: command.IdempotencyKey,
|
||||
RequestHash: sha256.Sum256(canonicalBody),
|
||||
TTL: s.idempotencyTTL,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ListMessages(
|
||||
|
||||
@@ -24,8 +24,19 @@ type ChatRepository interface {
|
||||
GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error)
|
||||
}
|
||||
|
||||
type IdempotentMessageWrite struct {
|
||||
ActorID string
|
||||
ChatID string
|
||||
Text string
|
||||
Method string
|
||||
CanonicalPath string
|
||||
Key string
|
||||
RequestHash [32]byte
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
CreateMessage(ctx context.Context, chatID, senderID, text string) (domain.Message, error)
|
||||
CreateMessageIdempotently(ctx context.Context, write IdempotentMessageWrite) (domain.Message, error)
|
||||
GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error)
|
||||
}
|
||||
|
||||
|
||||
@@ -5,14 +5,19 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const MinimumIdempotencyTTL = 24 * time.Hour
|
||||
|
||||
type ServiceOption func(*Service) error
|
||||
|
||||
type Service struct {
|
||||
repository Repository
|
||||
cursors *CursorCodec
|
||||
sessionTTL time.Duration
|
||||
now func() time.Time
|
||||
repository Repository
|
||||
cursors *CursorCodec
|
||||
sessionTTL time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration) (*Service, error) {
|
||||
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
|
||||
if repository == nil {
|
||||
return nil, fmt.Errorf("repository is required")
|
||||
}
|
||||
@@ -22,10 +27,27 @@ func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Dur
|
||||
if sessionTTL <= 0 {
|
||||
return nil, fmt.Errorf("session TTL must be positive")
|
||||
}
|
||||
return &Service{
|
||||
repository: repository,
|
||||
cursors: cursors,
|
||||
sessionTTL: sessionTTL,
|
||||
now: func() time.Time { return time.Now().UTC() },
|
||||
}, nil
|
||||
service := &Service{
|
||||
repository: repository,
|
||||
cursors: cursors,
|
||||
sessionTTL: sessionTTL,
|
||||
idempotencyTTL: MinimumIdempotencyTTL,
|
||||
now: func() time.Time { return time.Now().UTC() },
|
||||
}
|
||||
for _, option := range options {
|
||||
if err := option(service); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return service, nil
|
||||
}
|
||||
|
||||
func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
|
||||
return func(service *Service) error {
|
||||
if ttl < MinimumIdempotencyTTL {
|
||||
return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL)
|
||||
}
|
||||
service.idempotencyTTL = ttl
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,16 +5,19 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
HTTPHost string
|
||||
HTTPPort string
|
||||
HTTPHost string
|
||||
HTTPPort string
|
||||
InstanceID string
|
||||
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
CursorSigningKey string
|
||||
|
||||
DatabaseURL string
|
||||
@@ -36,6 +39,11 @@ type Config struct {
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
instanceID, err := instanceIDFromEnv()
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
sessionTTL, err := secondsDurationFromEnv(
|
||||
"SESSION_TTL_SECONDS",
|
||||
3600,
|
||||
@@ -44,6 +52,14 @@ func Load() (Config, error) {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
idempotencyTTL, err := secondsDurationFromEnv(
|
||||
"IDEMPOTENCY_TTL_SECONDS",
|
||||
86400,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseURL, err := requiredValueOrFile(
|
||||
"DATABASE_URL",
|
||||
"DATABASE_URL_FILE",
|
||||
@@ -158,10 +174,18 @@ func Load() (Config, error) {
|
||||
)
|
||||
}
|
||||
|
||||
if idempotencyTTL < 24*time.Hour {
|
||||
return Config{}, errors.New(
|
||||
"IDEMPOTENCY_TTL_SECONDS must be at least 86400",
|
||||
)
|
||||
}
|
||||
|
||||
return Config{
|
||||
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
|
||||
HTTPPort: envOrDefault("APP_PORT", "8080"),
|
||||
InstanceID: instanceID,
|
||||
SessionTTL: sessionTTL,
|
||||
IdempotencyTTL: idempotencyTTL,
|
||||
CursorSigningKey: cursorSigningKey,
|
||||
|
||||
DatabaseURL: databaseURL,
|
||||
@@ -183,6 +207,27 @@ func Load() (Config, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
||||
|
||||
func instanceIDFromEnv() (string, error) {
|
||||
instanceID := strings.TrimSpace(os.Getenv("INSTANCE_ID"))
|
||||
if instanceID == "" {
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve instance id from hostname: %w", err)
|
||||
}
|
||||
instanceID = hostname
|
||||
}
|
||||
|
||||
if !instanceIDPattern.MatchString(instanceID) {
|
||||
return "", errors.New(
|
||||
"INSTANCE_ID or hostname must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}",
|
||||
)
|
||||
}
|
||||
|
||||
return instanceID, nil
|
||||
}
|
||||
|
||||
func (c Config) HTTPAddress() string {
|
||||
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestInstanceIDFromEnvironment(t *testing.T) {
|
||||
t.Setenv("INSTANCE_ID", "api-replica_01")
|
||||
|
||||
instanceID, err := instanceIDFromEnv()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if instanceID != "api-replica_01" {
|
||||
t.Fatalf("got %q, want api-replica_01", instanceID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDRejectsUnsafeHeaderValue(t *testing.T) {
|
||||
t.Setenv("INSTANCE_ID", "api-1\r\nX-Forged: true")
|
||||
|
||||
if _, err := instanceIDFromEnv(); err == nil {
|
||||
t.Fatal("expected unsafe instance ID to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDFallsBackToHostname(t *testing.T) {
|
||||
t.Setenv("INSTANCE_ID", "")
|
||||
|
||||
instanceID, err := instanceIDFromEnv()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if instanceID == "" {
|
||||
t.Fatal("hostname fallback returned an empty instance ID")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package handlers
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab3/internal/application"
|
||||
@@ -14,15 +15,25 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
chatID := parsedChatID.String()
|
||||
|
||||
idempotencyKey := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyPattern.MatchString(idempotencyKey) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"Idempotency-Key must match [A-Za-z0-9._:-]{1,128}", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
var request dto.CreateMessageRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
@@ -30,8 +41,18 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
message, err := h.service.SendMessage(r.Context(), application.SendMessageCommand{
|
||||
ActorID: currentUser.ID, ChatID: chatID, Text: request.Text,
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: chatID,
|
||||
Text: request.Text,
|
||||
Method: http.MethodPost,
|
||||
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
|
||||
IdempotencyKey: idempotencyKey,
|
||||
})
|
||||
if errors.Is(err, application.ErrIdempotencyConflict) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"Idempotency-Key is already used for another request", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
const InstanceIDHeader = "X-Instance-Id"
|
||||
|
||||
// InstanceID identifies the process that actually produced the response.
|
||||
// It must wrap recovery and routing so even errors, health checks and 404/405
|
||||
// responses carry the same stable process identifier.
|
||||
func InstanceID(instanceID string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(InstanceIDHeader, instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := InstanceID("api-01", mux)
|
||||
|
||||
for _, test := range []struct {
|
||||
path string
|
||||
wantStatus int
|
||||
}{
|
||||
{path: "/ok", wantStatus: http.StatusNoContent},
|
||||
{path: "/missing", wantStatus: http.StatusNotFound},
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
|
||||
|
||||
if recorder.Code != test.wantStatus {
|
||||
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
|
||||
}
|
||||
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
|
||||
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
|
||||
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
panic("test panic")
|
||||
})
|
||||
handler := InstanceID("api-panic", Recovery(panicking))
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
|
||||
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("got status %d, want 500", recorder.Code)
|
||||
}
|
||||
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
|
||||
t.Fatalf("got instance ID %q, want api-panic", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
BEGIN;
|
||||
|
||||
DROP TABLE IF EXISTS message_idempotency;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,54 @@
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE message_idempotency (
|
||||
user_id UUID NOT NULL,
|
||||
method VARCHAR(8) NOT NULL,
|
||||
canonical_path TEXT NOT NULL,
|
||||
idempotency_key VARCHAR(128) NOT NULL,
|
||||
request_hash BYTEA NOT NULL,
|
||||
message_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT message_idempotency_primary_key
|
||||
PRIMARY KEY (
|
||||
user_id,
|
||||
method,
|
||||
canonical_path,
|
||||
idempotency_key
|
||||
),
|
||||
|
||||
CONSTRAINT message_idempotency_user_foreign_key
|
||||
FOREIGN KEY (user_id)
|
||||
REFERENCES users (id)
|
||||
ON DELETE RESTRICT,
|
||||
|
||||
CONSTRAINT message_idempotency_message_foreign_key
|
||||
FOREIGN KEY (message_id)
|
||||
REFERENCES messages (id)
|
||||
ON DELETE RESTRICT
|
||||
DEFERRABLE INITIALLY DEFERRED,
|
||||
|
||||
CONSTRAINT message_idempotency_message_unique
|
||||
UNIQUE (message_id),
|
||||
|
||||
CONSTRAINT message_idempotency_method_format
|
||||
CHECK (method = 'POST'),
|
||||
|
||||
CONSTRAINT message_idempotency_key_format
|
||||
CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
|
||||
CONSTRAINT message_idempotency_path_not_blank
|
||||
CHECK (btrim(canonical_path) <> ''),
|
||||
|
||||
CONSTRAINT message_idempotency_request_hash_length
|
||||
CHECK (octet_length(request_hash) = 32),
|
||||
|
||||
CONSTRAINT message_idempotency_expiry_after_creation
|
||||
CHECK (expires_at >= created_at + INTERVAL '24 hours')
|
||||
);
|
||||
|
||||
CREATE INDEX message_idempotency_expires_at_idx
|
||||
ON message_idempotency (expires_at);
|
||||
|
||||
COMMIT;
|
||||
+13
-4
@@ -5,11 +5,20 @@ project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
env_file=${ENV_FILE:-.env}
|
||||
compose() {
|
||||
docker compose --env-file "$env_file" "$@"
|
||||
}
|
||||
|
||||
# PostgreSQL хранит все обязательные данные и сессии в named volume.
|
||||
# Redis содержит только восстанавливаемый кеш и намеренно не имеет volume.
|
||||
docker compose --env-file "$env_file" restart postgres redis
|
||||
docker compose --env-file "$env_file" up -d --wait postgres redis
|
||||
compose restart postgres redis
|
||||
compose up -d --wait postgres redis
|
||||
|
||||
# API перезапускается после восстановления обязательной БД и кеша.
|
||||
docker compose --env-file "$env_file" restart api
|
||||
# up восстанавливает желаемое число реплик, включая ранее вручную остановленную.
|
||||
compose up -d --no-deps api
|
||||
compose restart api
|
||||
compose up -d --wait --no-deps api
|
||||
|
||||
# Публичная точка входа перезапускается последней, когда API уже готовы.
|
||||
compose restart load-balancer
|
||||
compose up -d --wait --no-deps load-balancer
|
||||
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
env_file=${ENV_FILE:-.env}
|
||||
matched_container=
|
||||
|
||||
for container_id in $(docker compose --env-file "$env_file" ps -a -q api); do
|
||||
instance_id=$(docker inspect --format '{{.Config.Hostname}}' "$container_id")
|
||||
if [ "$instance_id" = "$TARGET_INSTANCE_ID" ]; then
|
||||
if [ -n "$matched_container" ]; then
|
||||
printf '%s\n' "multiple API containers match instance $TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
matched_container=$container_id
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$matched_container" ]; then
|
||||
printf '%s\n' "API instance not found: $TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# A manual docker stop suppresses the container restart policy until the next
|
||||
# explicit start, so the selected replica remains down for the whole test.
|
||||
docker stop --time 5 "$matched_container" >/dev/null
|
||||
|
||||
printf '%s\n' "stopped API instance $TARGET_INSTANCE_ID"
|
||||
@@ -0,0 +1,275 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
store "mtusi2026lab3/internal/adapter/memory"
|
||||
"mtusi2026lab3/internal/domain"
|
||||
"mtusi2026lab3/internal/transport/http/dto"
|
||||
)
|
||||
|
||||
func sendMessageRequest(
|
||||
t *testing.T,
|
||||
serverURL string,
|
||||
chatID string,
|
||||
actorID string,
|
||||
key string,
|
||||
body string,
|
||||
) (int, []byte) {
|
||||
t.Helper()
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", serverURL, chatID),
|
||||
bytes.NewBufferString(body),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create message request: %v", err)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-User-Id", actorID)
|
||||
if key != "" {
|
||||
request.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send message request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
payload, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read message response: %v", err)
|
||||
}
|
||||
return response.StatusCode, payload
|
||||
}
|
||||
|
||||
func decodeMessageResponse(t *testing.T, payload []byte) dto.MessageResponse {
|
||||
t.Helper()
|
||||
|
||||
var message dto.MessageResponse
|
||||
if err := json.Unmarshal(payload, &message); err != nil {
|
||||
t.Fatalf("decode message response: %v; body=%s", err, payload)
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func createMessageFixture(t *testing.T) (*store.MemoryStore, string, domain.User, string) {
|
||||
t.Helper()
|
||||
|
||||
server, memoryStore := setupTestServer()
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
user, err := memoryStore.CreateUser("idempotency_user", "Idempotency User")
|
||||
if err != nil {
|
||||
t.Fatalf("create fixture user: %v", err)
|
||||
}
|
||||
chat, err := memoryStore.CreateChat("Idempotency Chat", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create fixture chat: %v", err)
|
||||
}
|
||||
|
||||
return memoryStore, server.URL, user, chat.ID
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyKeyValidation(t *testing.T) {
|
||||
_, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
key string
|
||||
}{
|
||||
{name: "missing", key: ""},
|
||||
{name: "space", key: "invalid key"},
|
||||
{name: "non ascii", key: "ключ"},
|
||||
{name: "too long", key: string(bytes.Repeat([]byte{'a'}, 129))},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
status, _ := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
testCase.key,
|
||||
`{"text":"hello"}`,
|
||||
)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyReplayAndConflict(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
status, firstPayload := sendMessageRequest(
|
||||
t, serverURL, chatID, user.ID, "replay-key", `{"text":"hello"}`,
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("first request: expected 201, got %d: %s", status, firstPayload)
|
||||
}
|
||||
|
||||
status, replayPayload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"replay-key",
|
||||
"{\n \"text\": \"hello\"\n}",
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("replay: expected 201, got %d: %s", status, replayPayload)
|
||||
}
|
||||
|
||||
first := decodeMessageResponse(t, firstPayload)
|
||||
replay := decodeMessageResponse(t, replayPayload)
|
||||
if first != replay {
|
||||
t.Fatalf("replay changed message: first=%+v replay=%+v", first, replay)
|
||||
}
|
||||
|
||||
status, _ = sendMessageRequest(
|
||||
t, serverURL, chatID, user.ID, "replay-key", `{"text":"different"}`,
|
||||
)
|
||||
if status != http.StatusConflict {
|
||||
t.Fatalf("different body: expected 409, got %d", status)
|
||||
}
|
||||
|
||||
messages, _, err := memoryStore.GetMessages(chatID, user.ID, 10, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("list messages: %v", err)
|
||||
}
|
||||
if len(messages) != 1 {
|
||||
t.Fatalf("expected one stored message, got %d", len(messages))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyScopesAreIndependent(t *testing.T) {
|
||||
server, memoryStore := setupTestServer()
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
alice, _ := memoryStore.CreateUser("scope_alice", "Alice")
|
||||
bob, _ := memoryStore.CreateUser("scope_bob", "Bob")
|
||||
firstChat, _ := memoryStore.CreateChat("First", []string{alice.ID, bob.ID})
|
||||
secondChat, _ := memoryStore.CreateChat("Second", []string{alice.ID, bob.ID})
|
||||
|
||||
testCases := []struct {
|
||||
actorID string
|
||||
chatID string
|
||||
text string
|
||||
}{
|
||||
{actorID: alice.ID, chatID: firstChat.ID, text: "alice first"},
|
||||
{actorID: bob.ID, chatID: firstChat.ID, text: "bob first"},
|
||||
{actorID: alice.ID, chatID: secondChat.ID, text: "alice second"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
status, payload := sendMessageRequest(
|
||||
t,
|
||||
server.URL,
|
||||
testCase.chatID,
|
||||
testCase.actorID,
|
||||
"shared-key",
|
||||
fmt.Sprintf(`{"text":%q}`, testCase.text),
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("independent scope: expected 201, got %d: %s", status, payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessageIdempotencyCreatesExactlyOneMessage(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
const clients = 32
|
||||
start := make(chan struct{})
|
||||
results := make(chan dto.MessageResponse, clients)
|
||||
errors := make(chan error, clients)
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
for index := 0; index < clients; index++ {
|
||||
waitGroup.Add(1)
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
<-start
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", serverURL, chatID),
|
||||
bytes.NewBufferString(`{"text":"concurrent replay"}`),
|
||||
)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-User-Id", user.ID)
|
||||
request.Header.Set("Idempotency-Key", "one-concurrent-key")
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
payload, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
errors <- fmt.Errorf("expected 201, got %d: %s", response.StatusCode, payload)
|
||||
return
|
||||
}
|
||||
|
||||
var message dto.MessageResponse
|
||||
if err = json.Unmarshal(payload, &message); err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
results <- message
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
waitGroup.Wait()
|
||||
close(results)
|
||||
close(errors)
|
||||
|
||||
for err := range errors {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
var expected dto.MessageResponse
|
||||
count := 0
|
||||
for message := range results {
|
||||
if count == 0 {
|
||||
expected = message
|
||||
} else if message != expected {
|
||||
t.Fatalf("concurrent replay returned different message: %+v != %+v", message, expected)
|
||||
}
|
||||
count++
|
||||
}
|
||||
if count != clients {
|
||||
t.Fatalf("expected %d successful responses, got %d", clients, count)
|
||||
}
|
||||
|
||||
messages, _, err := memoryStore.GetMessages(chatID, user.ID, clients+1, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("list messages: %v", err)
|
||||
}
|
||||
if len(messages) != 1 {
|
||||
t.Fatalf("expected exactly one stored message, got %d", len(messages))
|
||||
}
|
||||
}
|
||||
@@ -137,6 +137,7 @@ func TestEmptyMessageValidation(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":""}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", u.ID)
|
||||
req.Header.Set("Idempotency-Key", "empty-text")
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
@@ -147,6 +148,7 @@ func TestEmptyMessageValidation(t *testing.T) {
|
||||
reqSpaces, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":" "}`))
|
||||
reqSpaces.Header.Set("Content-Type", "application/json")
|
||||
reqSpaces.Header.Set("X-User-Id", u.ID)
|
||||
reqSpaces.Header.Set("Idempotency-Key", "spaces-text")
|
||||
|
||||
resSpaces, _ := http.DefaultClient.Do(reqSpaces)
|
||||
if resSpaces.StatusCode != http.StatusBadRequest {
|
||||
@@ -494,6 +496,10 @@ func TestConcurrent100MessagesFrom10Clients(t *testing.T) {
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", senderID)
|
||||
req.Header.Set(
|
||||
"Idempotency-Key",
|
||||
fmt.Sprintf("concurrent-%d-%d", clientIndex, m),
|
||||
)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil || res.StatusCode != http.StatusCreated {
|
||||
@@ -638,6 +644,7 @@ func TestUnicodeLimits(t *testing.T) {
|
||||
req1, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyValid))
|
||||
req1.Header.Set("Content-Type", "application/json")
|
||||
req1.Header.Set("X-User-Id", u.ID)
|
||||
req1.Header.Set("Idempotency-Key", "unicode-valid")
|
||||
res1, _ := http.DefaultClient.Do(req1)
|
||||
if res1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201 for 4000 unicode runes, got %d", res1.StatusCode)
|
||||
@@ -652,6 +659,7 @@ func TestUnicodeLimits(t *testing.T) {
|
||||
req2, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyTooLong))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
req2.Header.Set("X-User-Id", u.ID)
|
||||
req2.Header.Set("Idempotency-Key", "unicode-too-long")
|
||||
res2, _ := http.DefaultClient.Do(req2)
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for 4001 runes, got %d", res2.StatusCode)
|
||||
|
||||
Reference in New Issue
Block a user