ЛР 3 — БПИ2301 — Спесивцев — на 4 #103
@@ -18,3 +18,14 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
assets
|
||||
contracts
|
||||
examples
|
||||
scripts
|
||||
tests
|
||||
*.md
|
||||
Makefile
|
||||
lab.json
|
||||
requirements-dev.txt
|
||||
Dockerfile*
|
||||
.dockerignore
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ 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
|
||||
SESSION_STORE=redis
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
FROM golang:1.27.1-alpine3.24 AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
RUN CGO_ENABLED=0 go build -trimpath -o /out/server ./cmd/server
|
||||
|
||||
FROM alpine:3.24.1
|
||||
ARG BUILD_ID=dev
|
||||
LABEL org.opencontainers.image.revision=$BUILD_ID
|
||||
RUN adduser -D -H -u 10001 app
|
||||
COPY --from=build /out/server /usr/local/bin/server
|
||||
USER app
|
||||
ENV APP_HOST=0.0.0.0 APP_PORT=8080
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget -q -O /dev/null "http://127.0.0.1:${APP_PORT}/health/ready" || exit 1
|
||||
ENTRYPOINT ["/usr/local/bin/server"]
|
||||
@@ -2,12 +2,23 @@ PYTHON ?= python3
|
||||
BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
ENGINE ?= $(shell command -v podman >/dev/null 2>&1 && echo podman || echo docker)
|
||||
COMPOSE ?= $(if $(filter podman,$(ENGINE)),podman-compose,docker compose)
|
||||
TEST_DATABASE_URL ?= $(shell sed 's/@postgres:5432/@127.0.0.1:55432/' secrets/database_url 2>/dev/null)
|
||||
TEST_REDIS_URL ?= redis://127.0.0.1:56379/0
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
.PHONY: help up down check validate test load test-persistence test-failover test-idempotency test-go
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "up/down: start/stop the stand, volumes kept; test-idempotency: one key in parallel via LB; test-go: Go tests against the running stand"
|
||||
|
||||
up:
|
||||
$(COMPOSE) up -d --build
|
||||
|
||||
down:
|
||||
$(COMPOSE) down
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -28,3 +39,10 @@ test-persistence:
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-idempotency:
|
||||
BASE_URL="$(BASE_URL)" $(PYTHON) scripts/idempotency-race.py
|
||||
|
||||
test-go:
|
||||
@TEST_DATABASE_URL="$(TEST_DATABASE_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" go test -count=1 -v ./...
|
||||
|
||||
|
||||
@@ -1,37 +1,126 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Автор, группа: Спесивцев Даниил БПИ2301
|
||||
- Целевая оценка 4; выбранный трек 5, если нужен: не заявлен
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Использованные источники, библиотеки и помощь ИИ: Go 1.27.1 (стандартная библиотека). Для консультации, реализации некоторых фич, написания отчета использовались LLM. Библиотеки и компоненты:
|
||||
- [go-chi/chi v5.3.2](https://github.com/go-chi/chi) — HTTP-роутинг;
|
||||
- [jackc/pgx v5.11.0](https://github.com/jackc/pgx) — драйвер PostgreSQL и пул `pgxpool`, транзакция идемпотентной отправки;
|
||||
- [redis/go-redis v9.23.0](https://github.com/redis/go-redis) — клиент Redis для общих сессий;
|
||||
- [golang.org/x/crypto v0.58.0](https://pkg.go.dev/golang.org/x/crypto/argon2) — Argon2id для паролей;
|
||||
- образ [migrate/migrate v4.20.1](https://github.com/golang-migrate/migrate) — однократные миграции отдельным контейнером;
|
||||
- образ [HAProxy 3.4.7](https://www.haproxy.org/) — балансировщик.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Стенд: i5-11400H (12 потоков), 16 GB RAM, Linux 7.1.8, podman 6.1.0 + podman-compose 1.6.0 (`evidence/env.txt`). Образы: `postgres:18.6-alpine3.24`, `redis:8.10.3-alpine3.23`, `migrate/migrate:v4.20.1`, `haproxy:3.4.7-alpine`; API из `Dockerfile` (`golang:1.27.1-alpine3.24` → `alpine:3.24.1`).
|
||||
|
||||
Движок выбирается автоматически в `Makefile` и скриптах: podman + `podman-compose`, если podman установлен, иначе docker + `docker compose`. Явно: `ENGINE=docker COMPOSE="docker compose"`. `compose.yaml` проходит `docker compose config --quiet` и `podman-compose config`.
|
||||
|
||||
```sh
|
||||
scripts/init-secrets.sh # локальные secrets в ./secrets, вне Git; повторный запуск не перезаписывает
|
||||
make up # build; postgres, redis → migrate (однократно) → api ×2; lb
|
||||
until curl -sf http://localhost:8080/health/ready; do sleep 1; done
|
||||
|
||||
make check && make test && make test-go
|
||||
make test-idempotency # один Idempotency-Key, 20 параллельных POST через LB
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
$COMPOSE start api # вернуть остановленную реплику и повторить для другой
|
||||
scripts/rolling-update.sh # rolling update (под нагрузкой: параллельно python3 tests/load.py --duration 60)
|
||||
|
||||
make down # остановка, volumes сохраняются
|
||||
$COMPOSE down -v # намеренное удаление учебных данных
|
||||
```
|
||||
|
||||
Число реплик — `API_REPLICAS` (по умолчанию 2, балансируется до 4: `server-template api 4`). Публичная точка входа — только `lb` на `:8080`. Bootstrap безопасно повторяется: `migrate` при повторном запуске отвечает `no change`, `init-secrets.sh` не трогает существующие файлы.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
client → lb (HAProxy :8080) ──edge──▶ api ×2 ──backend──▶ postgres (источник истины)
|
||||
└────────▶ redis (сессии, AOF)
|
||||
migrate (one-shot) ─backend─▶ postgres
|
||||
```
|
||||
|
||||
| Роль | Service | Образ | Health / readiness | Volume | Сеть / порт | Credentials |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| LB | `lb` | `haproxy:3.4.7-alpine` | активная проверка `GET /health/ready` каждой реплики | — | edge, `0.0.0.0:8080` | нет |
|
||||
| API | `api` ×2 | `localhost/messenger-api:lab3` | `/health/live`; `/health/ready` = PostgreSQL + Redis + не draining | — | edge + backend, порт не публикуется | secrets `database_url`, `cache_url` |
|
||||
| Миграции | `migrate` | `migrate/migrate:v4.20.1` | exit 0 | SQL read-only | backend | secret `database_url` |
|
||||
| БД | `postgres` | `postgres:18.6-alpine3.24` | `pg_isready` | `pgdata` | backend, `127.0.0.1:55432` для `make test-go` | secret `postgres_password` |
|
||||
| Сессии | `redis` | `redis:8.10.3-alpine3.23` | `redis-cli ping` | `redisdata` (AOF everysec) | backend, `127.0.0.1:56379` для `make test-go` | нет |
|
||||
|
||||
- **Перенесено из lab2:** API на Go, PostgreSQL, Bearer-сессии в Redis, Argon2id. Cursor истории не зависит от процесса, поэтому любая реплика обслуживает любой запрос без sticky sessions.
|
||||
- **X-Instance-Id:** hostname контейнера (короткий ID), выставляется middleware на все ответы API. `scripts/stop-one.sh` находит контейнер с таким hostname по labels compose и останавливает только его.
|
||||
- **Идемпотентность:** таблица `message_idempotency`, PK `(user_id, chat_id, key)`; метод и путь фиксированы для эндпоинта. В одной транзакции выполняются `INSERT ... ON CONFLICT DO NOTHING` ключа и `INSERT` сообщения. Конкурентный дубль ждёт на уникальном индексе; при совпадении `sha256(text)` возвращается то же сообщение с 201, иначе 409. При 5xx транзакция откатывается, и ключ не фиксируется. Повтор заново проверяет сессию и доступ к чату.
|
||||
- **Миграции:** выполняются отдельным контейнером `migrate` до старта API (advisory lock golang-migrate); реплики миграций не запускают. Совместимость с работающей версией: допускаются только добавляющие изменения (expand/contract); `000002` лишь добавляет таблицу. Удаление или переименование колонок потребует двух релизов. `scripts/rolling-update.sh` выполняет `migrate` до замены реплик.
|
||||
- **Rolling update** (`scripts/rolling-update.sh`):
|
||||
1. сборка нового образа с тем же тегом и новым label `BUILD_ID`;
|
||||
2. `$COMPOSE run --rm migrate`;
|
||||
3. для каждой старой реплики по очереди: `stop -t 10` (drain) → `rm` → `$COMPOSE up -d --no-deps --no-recreate api` → ожидание `healthy` новой реплики.
|
||||
- **Graceful shutdown:** по SIGTERM `/health/ready` сразу отвечает 503, keep-alive отключается, 3 с drain, затем `Shutdown` с таймаутом 5 с.
|
||||
|
||||
| Таймаут | Значение |
|
||||
| --- | --- |
|
||||
| PostgreSQL `statement_timeout` / connect | 5 s / 3 s |
|
||||
| Readiness ping зависимостей | 1 s |
|
||||
| HTTP API: ReadHeader / Read / Write / Idle | 5 / 15 / 15 / 60 s |
|
||||
| HAProxy: connect / server / client / http-request / check | 2 / 20 / 30 / 10 / 1 s; `maxconn 2000` |
|
||||
| Остановка: drain + shutdown | 3 + 5 = 8 s < `stop -t 10`, `stop_grace_period: 10s` |
|
||||
|
||||
**Обнаружение отказа.** Период проверок HAProxy: `inter 1s`, `fall 2`, `rise 2`, `timeout check 1s`; DNS `hold valid 1s`.
|
||||
- При SIGTERM реплика выводится из LB по 503 readiness за ≤ 2 s, до закрытия listener (измерено 2.0 s, `evidence/drain.txt`).
|
||||
- При аварийной остановке отказ соединения сразу уходит на другую реплику (`retries 3`, `option redispatch`; повторяется только неудавшееся соединение, отправленный POST не повторяется). Максимальное время исключения backend — `inter × fall + timeout check` = 3 s.
|
||||
|
||||
Соответствие `.env.example`:
|
||||
- `SESSION_STORE=redis`;
|
||||
- `DATABASE_URL_FILE`, `CACHE_URL_FILE` — файлы secrets;
|
||||
- `API_REPLICAS` → `scale` сервиса `api`;
|
||||
- `SESSION_TTL_SECONDS`, `APP_ENV` передаются в API;
|
||||
- `IDEMPOTENCY_TTL_SECONDS` не используется: ключи хранятся бессрочно, что покрывает требование «не менее 24 ч».
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Публичный smoke | `make test` | PASS | `evidence/smoke.txt` |
|
||||
| Стенд в compose.yaml: ≥2 API, одна точка входа, общие БД и сессии | `make up`, `ps` | 2 реплики `api`, порт публикует только `lb` | `evidence/instances.txt`, `evidence/limits.txt` |
|
||||
| Разные реплики с одной сессией, X-Instance-Id | 20 × `GET /users/me` через LB одним токеном | по 10 ответов от двух ID; ID = hostname контейнера | `evidence/instances.txt` |
|
||||
| Отказ любой одной реплики: ≤ 10 s, подтверждённые сообщения доступны | `make test-failover` для `api_1` и `api_2` | PASS, 0 ошибок, первая запись после hook за 3.3–3.4 s | `evidence/failover-1.txt`, `evidence/failover-2.txt` |
|
||||
| Повтор с тем же Idempotency-Key без дубля, в т. ч. конкурентный и через разные реплики | `make test`, `make test-idempotency` | 20/20 ответов 201 с одним сообщением, обслужили обе реплики | `evidence/smoke.txt`, `evidence/idempotency-race.txt` |
|
||||
| persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS; перезапущены lb, api, redis, postgres с теми же ID; volumes сохранены | `evidence/persistence.txt` |
|
||||
| Миграции отдельно, без гонки реплик | `make up` | `migrate` exit 0, в логах API миграций нет, версия схемы 2 | `evidence/migrate.txt` |
|
||||
| Собственные Go-тесты | `make test-go` | 13 PASS | `evidence/test-go.txt` |
|
||||
| 4: readiness, timeouts, SIGTERM, исключение backend; период и время обнаружения | `stop` реплики | ready 503 → LB DOWN за 2.0 s → listener закрыт через 3 s | `evidence/drain.txt`, разделы выше |
|
||||
| 4: поочерёдная остановка каждой реплики, RPS / ошибки / восстановление | `make test-failover` под фоновым `tests/load.py` | см. таблицу ниже | `evidence/failover-{1,2}.txt`, `evidence/failover-load-{1,2}.json` |
|
||||
| 4: общая идемпотентность параллельными запросами с одним ключом | `make test-idempotency` | одно сообщение на 20 параллельных запросов | `evidence/idempotency-race.txt` |
|
||||
| 4: CPU/RAM-лимиты, API без портов, секреты и хранилища только где нужно, нет container_name | `inspect`, `ls /run/secrets`, `getent` из lb | лимиты у всех сервисов; lb не видит postgres и redis; секреты по ролям | `evidence/limits.txt` |
|
||||
| 4: rolling update под нагрузкой; миграции однократны и совместимы | `scripts/rolling-update.sh` под фоновым `tests/load.py --duration 60` | обе реплики заменены новым образом за 21 s, 0 ошибок | `evidence/rolling.txt`, `evidence/rolling-load.json` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
- **Профиль:** публичный `tests/load.py`, closed-loop POST сообщений, concurrency 4, 30 s (rolling — 60 s), без автоматических повторов. Отказ запускается через `make test-failover` примерно на 4-й секунде нагрузки; тест сам повторяет неопределённый POST с тем же ключом и проверяет сохранность и отсутствие дублей. Прогрев отдельно не выделялся; один прогон на сценарий.
|
||||
- **Лимиты:** api 1 CPU / 256 MiB на реплику, postgres 1 CPU / 512 MiB, redis 0.5 CPU / 128 MiB, lb 0.5 CPU / 64 MiB, migrate 0.5 CPU / 64 MiB.
|
||||
- **Потребление во время нагрузки** (`stats --no-stream`): api 4–5 % CPU и 28–92 MiB, postgres 12 % CPU и 135 MiB, lb 3–5 % CPU и 28–32 MiB, redis < 1 % CPU и 7 MiB.
|
||||
- **Набор данных после всех прогонов:** 294 274 сообщения, 292 пользователя, 84 чата, БД 167 MB (`evidence/dataset.txt`).
|
||||
|
||||
| Прогон | Успешные RPS (`load.py`) | Ошибки `load.py` / теста | p50 / p95 / p99, ms | Восстановление записи (тест) | Записей теста за 15 s |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| stop `api_1` | 290.3 | 0 / 0 | 13.1 / 17.6 / 23.9 | 3.34 s от старта hook (hook ≈ 3.2 s, drain) | 131 |
|
||||
| stop `api_2` | 316.8 | 0 / 0 | 12.1 / 16.1 / 22.4 | 3.37 s от старта hook | 132 |
|
||||
| rolling update | 288.5 | 0 | 13.2 / 17.0 / 20.1 | замена 2 реплик за 21 s | — |
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| `stop` реплики (SIGTERM) | вывод из LB до закрытия listener, без ошибок | DOWN по 503 за 2.0 s, 0 ошибок под нагрузкой | запись не прерывалась / потерь и дублей нет |
|
||||
| Rolling update | поочерёдная замена без простоя | 0 ошибок за 60 s, новый image и revision у обеих реплик | — / потерь нет |
|
||||
| Restart всего стенда | данные и токен сохраняются | PASS persistence | в пределах бюджета теста 90 s / потерь нет |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Потеря host, LB или PostgreSQL не переживается, это SPOF. Отказоустойчивость показана только для процесса API.
|
||||
- Порты PostgreSQL и Redis опубликованы только на `127.0.0.1` для `make test-go`. Redis без пароля доступен только с локальной машины.
|
||||
- `server-template api 4` при `API_REPLICAS` > 4 лишние реплики в балансировку не попадут.
|
||||
- Нагрузка closed-loop с одного клиента ограничена клиентом, есть coordinated omission, один прогон на сценарий. Это не оценка предельной пропускной способности.
|
||||
- Ключи идемпотентности не удаляются, таблица растёт. Для production понадобится фоновая очистка ключей старше 24 ч.
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"messenger/internal/config"
|
||||
"messenger/internal/handler"
|
||||
"messenger/internal/repository/postgres"
|
||||
"messenger/internal/repository/redis"
|
||||
"messenger/internal/router"
|
||||
"messenger/internal/service"
|
||||
)
|
||||
|
||||
const (
|
||||
drainDelay = 3 * time.Second
|
||||
shutdownTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
if err := run(log); err != nil {
|
||||
log.Error("server failed", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(log *slog.Logger) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
instanceID, err := os.Hostname()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
store := postgres.New(pool)
|
||||
|
||||
redisClient, err := redis.NewClient(cfg.CacheURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer redisClient.Close()
|
||||
sessions := redis.NewSessionStore(redisClient)
|
||||
|
||||
users := service.NewUserService(store)
|
||||
auth := service.NewAuthService(store, sessions, cfg.SessionTTL)
|
||||
chats := service.NewChatService(store)
|
||||
messages := service.NewMessageService(chats, store)
|
||||
deps := []handler.Pinger{store.Ping, sessions.Ping}
|
||||
|
||||
h := handler.New(users, auth, chats, messages, deps, log)
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: router.New(h, instanceID),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
|
||||
defer stop()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
log.Info("starting server", "addr", srv.Addr, "instance_id", instanceID, "env", cfg.Env, "session_ttl", cfg.SessionTTL.String())
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errCh <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
}
|
||||
log.Info("shutdown signal received, draining", "drain", drainDelay.String(), "timeout", shutdownTimeout.String())
|
||||
h.StartDraining()
|
||||
srv.SetKeepAlivesEnabled(false)
|
||||
time.Sleep(drainDelay)
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info("server stopped")
|
||||
return nil
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
name: messenger-lab3
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: docker.io/library/postgres:18.6-alpine3.24
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets:
|
||||
- postgres_password
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql
|
||||
networks:
|
||||
- backend
|
||||
ports:
|
||||
- "127.0.0.1:55432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 512M
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: docker.io/library/redis:8.10.3-alpine3.23
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
networks:
|
||||
- backend
|
||||
ports:
|
||||
- "127.0.0.1:56379:6379"
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 128M
|
||||
restart: unless-stopped
|
||||
|
||||
migrate:
|
||||
image: docker.io/migrate/migrate:v4.20.1
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command: ['migrate -path /migrations -database "$$(cat /run/secrets/database_url)" up']
|
||||
secrets:
|
||||
- database_url
|
||||
volumes:
|
||||
- ./internal/repository/postgres/migrations:/migrations:ro
|
||||
networks:
|
||||
- backend
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 64M
|
||||
restart: "no"
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: localhost/messenger-api:lab3
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
secrets:
|
||||
- database_url
|
||||
- cache_url
|
||||
networks:
|
||||
- edge
|
||||
- backend
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"]
|
||||
interval: 5s
|
||||
timeout: 2s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
stop_grace_period: 10s
|
||||
scale: ${API_REPLICAS:-2}
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 256M
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
lb:
|
||||
image: docker.io/library/haproxy:3.4.7-alpine
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
networks:
|
||||
- edge
|
||||
ports:
|
||||
- "8080:8080"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 64M
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
edge:
|
||||
backend:
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
redisdata:
|
||||
@@ -0,0 +1,8 @@
|
||||
$ row counts after all runs (date 2026-11-06T02:07:36Z)
|
||||
chats 84
|
||||
users 292
|
||||
messages 294274
|
||||
message_idempotency 294274
|
||||
|
||||
$ database size
|
||||
167 MB
|
||||
@@ -0,0 +1,13 @@
|
||||
$ date -u; podman stop -t 10 messenger-lab3_api_1; date -u
|
||||
02:07:18.261
|
||||
02:07:21.454
|
||||
|
||||
$ podman logs messenger-lab3_api_1 (shutdown sequence, UTC)
|
||||
02:07:18.345 shutdown signal received, draining 3s 5s
|
||||
02:07:21.345 server stopped
|
||||
|
||||
$ TZ=UTC podman logs -t messenger-lab3_lb_1 (backend state, UTC)
|
||||
02:07:20.346 Server api/api2 is DOWN, reason: Layer7 wrong status, code: 503, info: "Service Unavailable", check duration: 0ms. 1 active and 0 backup
|
||||
|
||||
SIGTERM 02:07:18.345 -> LB marks DOWN by 503 readiness 02:07:20.346 (2.0 s, <= inter 1s x fall 2) -> listener closed 02:07:21.345 (drain 3 s); hook returned in 3.2 s.
|
||||
HAProxy slot names (api1..api4 from server-template) are assigned by DNS order and do not match container numbers.
|
||||
@@ -0,0 +1,12 @@
|
||||
date: 2026-11-06T01:54:08Z
|
||||
host: i5-11400H, 12 threads, 15Gi RAM, Linux 7.1.8-arch1-3
|
||||
podman version 6.1.0
|
||||
podman-compose version 1.6.0
|
||||
go version go1.27.1 linux/amd64
|
||||
images:
|
||||
image: docker.io/library/postgres:18.6-alpine3.24
|
||||
image: docker.io/library/redis:8.10.3-alpine3.23
|
||||
image: docker.io/migrate/migrate:v4.20.1
|
||||
image: localhost/messenger-api:lab3
|
||||
image: docker.io/library/haproxy:3.4.7-alpine
|
||||
limits: see evidence/limits.txt
|
||||
@@ -0,0 +1,47 @@
|
||||
$ api replicas before
|
||||
messenger-lab3_api_2 hostname=5a9ffe83734a Up About a minute (healthy)
|
||||
messenger-lab3_api_1 hostname=ab01920585fe Up About a minute (healthy)
|
||||
|
||||
$ python3 tests/load.py --duration 30 --concurrency 4 --output evidence/failover-load-1.json & (background load during the test)
|
||||
$ podman stats --no-stream (during load, before failure)
|
||||
messenger-lab3_api_1 cpu=3.87% mem=88.06MB / 268.4MB
|
||||
messenger-lab3_api_2 cpu=4.17% mem=92.08MB / 268.4MB
|
||||
messenger-lab3_lb_1 cpu=2.81% mem=28.44MB / 67.11MB
|
||||
messenger-lab3_postgres_1 cpu=12.21% mem=135.6MB / 536.9MB
|
||||
messenger-lab3_redis_1 cpu=0.58% mem=6.857MB / 134.2MB
|
||||
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 3.339}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
|
||||
$ podman stats --no-stream (during load, one replica stopped)
|
||||
messenger-lab3_api_2 cpu=5.01% mem=27.76MB / 268.4MB
|
||||
messenger-lab3_lb_1 cpu=3.77% mem=29.78MB / 67.11MB
|
||||
messenger-lab3_postgres_1 cpu=12.32% mem=133.1MB / 536.9MB
|
||||
messenger-lab3_redis_1 cpu=0.59% mem=7.111MB / 134.2MB
|
||||
|
||||
$ background tests/load.py result
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.008,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 8712,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 290.322,
|
||||
"successful_latency_ms": {
|
||||
"p50": 13.117,
|
||||
"p95": 17.627,
|
||||
"p99": 23.947
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
|
||||
$ api replicas after (stopped one = TARGET_INSTANCE_ID)
|
||||
messenger-lab3_api_2 hostname=5a9ffe83734a Up 2 minutes (healthy)
|
||||
messenger-lab3_api_1 hostname=ab01920585fe Exited (0) 22 seconds ago (healthy)
|
||||
@@ -0,0 +1,47 @@
|
||||
$ api replicas before
|
||||
messenger-lab3_api_2 hostname=5a9ffe83734a Up 2 minutes (healthy)
|
||||
messenger-lab3_api_1 hostname=ab01920585fe Up 4 seconds (healthy)
|
||||
|
||||
$ python3 tests/load.py --duration 30 --concurrency 4 --output evidence/failover-load-2.json & (background load during the test)
|
||||
$ podman stats --no-stream (during load, before failure)
|
||||
messenger-lab3_api_1 cpu=4.21% mem=47.89MB / 268.4MB
|
||||
messenger-lab3_api_2 cpu=5.90% mem=92.86MB / 268.4MB
|
||||
messenger-lab3_lb_1 cpu=4.60% mem=31.47MB / 67.11MB
|
||||
messenger-lab3_postgres_1 cpu=12.45% mem=148.5MB / 536.9MB
|
||||
messenger-lab3_redis_1 cpu=0.59% mem=6.611MB / 134.2MB
|
||||
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 132, "failed_attempts": 0, "first_recovery_seconds": 3.37}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
|
||||
$ podman stats --no-stream (during load, one replica stopped)
|
||||
messenger-lab3_api_1 cpu=7.73% mem=33.08MB / 268.4MB
|
||||
messenger-lab3_lb_1 cpu=4.84% mem=32.26MB / 67.11MB
|
||||
messenger-lab3_postgres_1 cpu=12.54% mem=146.1MB / 536.9MB
|
||||
messenger-lab3_redis_1 cpu=0.59% mem=7.373MB / 134.2MB
|
||||
|
||||
$ background tests/load.py result
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.013,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 9508,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 316.791,
|
||||
"successful_latency_ms": {
|
||||
"p50": 12.105,
|
||||
"p95": 16.14,
|
||||
"p99": 22.351
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
|
||||
$ api replicas after (stopped one = TARGET_INSTANCE_ID)
|
||||
messenger-lab3_api_2 hostname=5a9ffe83734a Exited (0) 22 seconds ago (healthy)
|
||||
messenger-lab3_api_1 hostname=ab01920585fe Up 35 seconds (healthy)
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.008,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 8712,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 290.322,
|
||||
"successful_latency_ms": {
|
||||
"p50": 13.117,
|
||||
"p95": 17.627,
|
||||
"p99": 23.947
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.013,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 9508,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 316.791,
|
||||
"successful_latency_ms": {
|
||||
"p50": 12.105,
|
||||
"p95": 16.14,
|
||||
"p99": 22.351
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
BASE_URL="http://localhost:8080" python3 scripts/idempotency-race.py
|
||||
parallel requests with one key: 20
|
||||
successful responses (201): 20
|
||||
failed requests: 0 []
|
||||
distinct message ids in responses: 1
|
||||
messages stored in history: 1
|
||||
instances that served requests: ['56e8d4ca6c28', 'd63350b561c6']
|
||||
OK: exactly one message created
|
||||
@@ -0,0 +1,16 @@
|
||||
20 GET /api/v1/users/me through LB (localhost:8080) with ONE bearer session, no re-login
|
||||
X-Instance-Id 56e8d4ca6c28 responses 10
|
||||
X-Instance-Id d63350b561c6 responses 10
|
||||
|
||||
$ podman ps (api replicas: name, container ID = hostname = X-Instance-Id)
|
||||
messenger-lab3_api_1 d63350b561c6 Up 41 seconds (healthy)
|
||||
messenger-lab3_api_2 56e8d4ca6c28 Up About a minute (healthy)
|
||||
messenger-lab3_api_1 hostname=d63350b561c6
|
||||
messenger-lab3_api_2 hostname=56e8d4ca6c28
|
||||
|
||||
$ podman ps (published ports: only lb exposes 8080)
|
||||
messenger-lab3_api_1 8080/tcp
|
||||
messenger-lab3_api_2 8080/tcp
|
||||
messenger-lab3_lb_1 0.0.0.0:8080->8080/tcp
|
||||
messenger-lab3_postgres_1 127.0.0.1:55432->5432/tcp
|
||||
messenger-lab3_redis_1 127.0.0.1:56379->6379/tcp
|
||||
@@ -0,0 +1,23 @@
|
||||
$ podman inspect: limits, networks, published ports
|
||||
messenger-lab3_api_1 cpus=1000000000 memory=268435456 networks=messenger-lab3_backend messenger-lab3_edge ports=
|
||||
messenger-lab3_api_2 cpus=1000000000 memory=268435456 networks=messenger-lab3_backend messenger-lab3_edge ports=
|
||||
messenger-lab3_lb_1 cpus=500000000 memory=67108864 networks=messenger-lab3_edge ports=8080/tcp->0.0.0.0:8080
|
||||
messenger-lab3_migrate_1 cpus=500000000 memory=67108864 networks=messenger-lab3_backend ports=
|
||||
messenger-lab3_postgres_1 cpus=1000000000 memory=536870912 networks=messenger-lab3_backend ports=5432/tcp->127.0.0.1:55432
|
||||
messenger-lab3_redis_1 cpus=500000000 memory=134217728 networks=messenger-lab3_backend ports=6379/tcp->127.0.0.1:56379
|
||||
|
||||
$ ls /run/secrets in each running container
|
||||
messenger-lab3_api_1: cache_url database_url
|
||||
messenger-lab3_api_2: cache_url database_url
|
||||
messenger-lab3_lb_1:
|
||||
messenger-lab3_postgres_1: postgres_password
|
||||
messenger-lab3_redis_1:
|
||||
migrate (one-shot): /run/secrets/database_url
|
||||
|
||||
$ lb sees only the edge network
|
||||
postgres: not resolvable from lb
|
||||
redis: not resolvable from lb
|
||||
10.89.4.28 api.dns.podman api.dns.podman api
|
||||
|
||||
$ grep -c container_name compose.yaml
|
||||
0
|
||||
@@ -0,0 +1,22 @@
|
||||
$ podman ps -a (migrate is one-shot, exited 0; api replicas started after it)
|
||||
messenger-lab3_migrate_1 Exited (0) About a minute ago
|
||||
|
||||
$ podman logs migrate (schema already at version 2 in the kept volume; repeated run is safe)
|
||||
no change
|
||||
no change
|
||||
no change
|
||||
|
||||
$ API replicas run no migrations (count of "migrat" in logs)
|
||||
api_1: 0
|
||||
api_2: 0
|
||||
|
||||
$ SELECT version, dirty FROM schema_migrations
|
||||
2|f
|
||||
|
||||
$ \dt
|
||||
chat_members
|
||||
chats
|
||||
message_idempotency
|
||||
messages
|
||||
schema_migrations
|
||||
users
|
||||
@@ -0,0 +1,25 @@
|
||||
$ containers before
|
||||
messenger-lab3_api_1 d63350b561c6 Up 42 seconds (healthy)
|
||||
messenger-lab3_api_2 56e8d4ca6c28 Up About a minute (healthy)
|
||||
messenger-lab3_lb_1 d0ec4e5311dd Up 4 minutes
|
||||
messenger-lab3_migrate_1 82c01bec10d9 Exited (0) 14 minutes ago
|
||||
messenger-lab3_postgres_1 0d8a6c71fcaf Up 13 minutes (healthy)
|
||||
messenger-lab3_redis_1 37f40fddaa42 Up 13 minutes (healthy)
|
||||
|
||||
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
|
||||
$ containers after (same IDs, restarted, volumes kept)
|
||||
messenger-lab3_api_1 d63350b561c6 Up 2 seconds (healthy)
|
||||
messenger-lab3_api_2 56e8d4ca6c28 Up 1 second (healthy)
|
||||
messenger-lab3_lb_1 d0ec4e5311dd Up 2 seconds
|
||||
messenger-lab3_migrate_1 82c01bec10d9 Exited (0) 14 minutes ago
|
||||
messenger-lab3_postgres_1 0d8a6c71fcaf Up 2 seconds (healthy)
|
||||
messenger-lab3_redis_1 37f40fddaa42 Up 1 second (healthy)
|
||||
|
||||
$ podman volume ls
|
||||
messenger-lab3_pgdata
|
||||
messenger-lab3_redisdata
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.013,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 17311,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 288.453,
|
||||
"successful_latency_ms": {
|
||||
"p50": 13.202,
|
||||
"p95": 17.032,
|
||||
"p99": 20.075
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
$ api replicas before
|
||||
messenger-lab3_api_1 container=ab01920585fe image=3fcba3e82597 revision=1793930539 health=healthy
|
||||
messenger-lab3_api_2 container=5a9ffe83734a image=3fcba3e82597 revision=1793930539 health=healthy
|
||||
|
||||
$ python3 tests/load.py --duration 60 --concurrency 4 --output evidence/rolling-load.json & (background load)
|
||||
$ podman stats --no-stream (during load, before update)
|
||||
messenger-lab3_api_1 cpu=5.87% mem=106.7MB / 268.4MB
|
||||
messenger-lab3_api_2 cpu=2.47% mem=47.7MB / 268.4MB
|
||||
messenger-lab3_lb_1 cpu=4.56% mem=31.62MB / 67.11MB
|
||||
messenger-lab3_postgres_1 cpu=12.33% mem=156.8MB / 536.9MB
|
||||
messenger-lab3_redis_1 cpu=0.59% mem=7.361MB / 134.2MB
|
||||
|
||||
$ scripts/rolling-update.sh (build new image -> migrate once -> replace replicas one by one)
|
||||
exit=0 duration=21s
|
||||
migrate: no change
|
||||
|
||||
$ podman stats --no-stream (during load, after update)
|
||||
messenger-lab3_api_1 cpu=4.77% mem=12.05MB / 268.4MB
|
||||
messenger-lab3_api_2 cpu=7.42% mem=11.21MB / 268.4MB
|
||||
messenger-lab3_lb_1 cpu=4.78% mem=31.83MB / 67.11MB
|
||||
messenger-lab3_postgres_1 cpu=12.49% mem=159.6MB / 536.9MB
|
||||
messenger-lab3_redis_1 cpu=0.59% mem=7.119MB / 134.2MB
|
||||
|
||||
$ background tests/load.py result
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 60.0,
|
||||
"elapsed_seconds": 60.013,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 17311,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 288.453,
|
||||
"successful_latency_ms": {
|
||||
"p50": 13.202,
|
||||
"p95": 17.032,
|
||||
"p99": 20.075
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
|
||||
$ api replicas after (new containers, new image and revision)
|
||||
messenger-lab3_api_1 container=d63350b561c6 image=3ab3deda3163 revision=1793930771 health=healthy
|
||||
messenger-lab3_api_2 container=56e8d4ca6c28 image=3ab3deda3163 revision=1793930771 health=healthy
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,43 @@
|
||||
? messenger/cmd/server [no test files]
|
||||
? messenger/internal/config [no test files]
|
||||
? messenger/internal/domain [no test files]
|
||||
=== RUN TestSessionExpiry
|
||||
--- PASS: TestSessionExpiry (3.11s)
|
||||
=== RUN TestLogout
|
||||
--- PASS: TestLogout (0.13s)
|
||||
=== RUN TestWrongPassword
|
||||
--- PASS: TestWrongPassword (0.11s)
|
||||
=== RUN TestRedisUnavailable
|
||||
redis: 2026/11/06 05:07:57 pool.go:770: redis: connection pool: failed to dial after 5 attempts: dial tcp 127.0.0.1:1: connect: connection refused
|
||||
redis: 2026/11/06 05:07:57 pool.go:770: redis: connection pool: failed to dial after 5 attempts: dial tcp 127.0.0.1:1: connect: connection refused
|
||||
redis: 2026/11/06 05:07:58 pool.go:770: redis: connection pool: failed to dial after 5 attempts: dial tcp 127.0.0.1:1: connect: connection refused
|
||||
redis: 2026/11/06 05:07:58 pool.go:770: redis: connection pool: failed to dial after 5 attempts: dial tcp 127.0.0.1:1: connect: connection refused
|
||||
redis: 2026/11/06 05:07:59 pool.go:770: redis: connection pool: failed to dial after 5 attempts: dial tcp 127.0.0.1:1: connect: connection refused
|
||||
redis: 2026/11/06 05:07:59 pool.go:770: redis: connection pool: failed to dial after 5 attempts: dial tcp 127.0.0.1:1: connect: connection refused
|
||||
--- PASS: TestRedisUnavailable (2.94s)
|
||||
=== RUN TestDatabaseUnavailable
|
||||
--- PASS: TestDatabaseUnavailable (0.20s)
|
||||
=== RUN TestInvalidJSON
|
||||
--- PASS: TestInvalidJSON (0.01s)
|
||||
=== RUN TestForeignChat
|
||||
redis: 2026/11/06 05:08:00 pool.go:770: redis: connection pool: failed to dial after 5 attempts: dial tcp 127.0.0.1:1: connect: connection refused
|
||||
--- PASS: TestForeignChat (0.23s)
|
||||
=== RUN TestEmptyMessage
|
||||
--- PASS: TestEmptyMessage (0.08s)
|
||||
=== RUN TestDuplicateUsername
|
||||
--- PASS: TestDuplicateUsername (0.10s)
|
||||
=== RUN TestPaginationMultiplePages
|
||||
--- PASS: TestPaginationMultiplePages (0.09s)
|
||||
=== RUN TestConcurrentMessages
|
||||
--- PASS: TestConcurrentMessages (0.57s)
|
||||
PASS
|
||||
ok messenger/internal/handler 7.578s
|
||||
=== RUN TestRegisterUsernameRace
|
||||
--- PASS: TestRegisterUsernameRace (0.07s)
|
||||
=== RUN TestCreateChatRollback
|
||||
--- PASS: TestCreateChatRollback (0.02s)
|
||||
PASS
|
||||
ok messenger/internal/repository/postgres 0.088s
|
||||
? messenger/internal/repository/redis [no test files]
|
||||
? messenger/internal/router [no test files]
|
||||
? messenger/internal/service [no test files]
|
||||
@@ -0,0 +1,21 @@
|
||||
module messenger
|
||||
|
||||
go 1.27.1
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.3.2
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,43 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
|
||||
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
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=
|
||||
@@ -0,0 +1,30 @@
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 2000
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 20s
|
||||
timeout http-request 10s
|
||||
timeout check 1s
|
||||
retries 3
|
||||
option redispatch
|
||||
|
||||
resolvers dns
|
||||
parse-resolv-conf
|
||||
hold valid 1s
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
default-server check inter 1s fall 2 rise 2 resolvers dns init-addr none
|
||||
server-template api 4 api:8080
|
||||
@@ -0,0 +1,60 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
Env string
|
||||
SessionTTL time.Duration
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
ttl, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
if err != nil || ttl <= 0 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer")
|
||||
}
|
||||
databaseURL, err := readSecret("DATABASE_URL_FILE", "/run/secrets/database_url")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cacheURL, err := readSecret("CACHE_URL_FILE", "/run/secrets/cache_url")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
return Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Port: getenv("APP_PORT", "8080"),
|
||||
Env: getenv("APP_ENV", "lab"),
|
||||
SessionTTL: time.Duration(ttl) * time.Second,
|
||||
DatabaseURL: databaseURL,
|
||||
CacheURL: cacheURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) }
|
||||
|
||||
func readSecret(key, def string) (string, error) {
|
||||
path := getenv(key, def)
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s: cannot read %s", key, path)
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
"uuid"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (c Chat) HasMember(userID uuid.UUID) bool {
|
||||
for _, id := range c.MemberIDs {
|
||||
if id == userID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User User
|
||||
}
|
||||
|
||||
type Cursor struct {
|
||||
Scope uuid.UUID
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func CompareKey(aTime time.Time, aID uuid.UUID, bTime time.Time, bID uuid.UUID) int {
|
||||
if c := aTime.Compare(bTime); c != 0 {
|
||||
return c
|
||||
}
|
||||
return aID.Compare(bID)
|
||||
}
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
Next *Cursor
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package domain
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnavailable = errors.New("dependency unavailable")
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, ok := basicCredentials(r)
|
||||
if !ok {
|
||||
h.failLogin(w, r, domain.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
session, err := h.auth.Login(r.Context(), username, password)
|
||||
if err != nil {
|
||||
h.failLogin(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, toSessionResponse(session))
|
||||
}
|
||||
|
||||
func (h *Handler) failLogin(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, domain.ErrUnauthorized) {
|
||||
w.Header().Set(headerWWWAuthenticate, basicChallenge)
|
||||
}
|
||||
h.fail(w, r, err)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.auth.Logout(r.Context(), current(r).token); err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func basicCredentials(r *http.Request) (string, string, bool) {
|
||||
encoded, ok := authCredentials(r, "Basic")
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil || !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
username, password, ok := strings.Cut(string(raw), ":")
|
||||
return username, password, ok
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package handler_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
deadDatabaseURL = "postgres://messenger:x@127.0.0.1:1/messenger?sslmode=disable"
|
||||
deadRedisURL = "redis://127.0.0.1:1/0"
|
||||
)
|
||||
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
dbURL, redisURL := testURLs(t)
|
||||
srv := newStack(t, dbURL, redisURL, 2*time.Second)
|
||||
alice := createUser(t, srv, "alice")
|
||||
|
||||
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusOK {
|
||||
t.Fatalf("fresh session: got %d, want 200", status)
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
resp := request(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, "")
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expired session: got %d, want 401", resp.StatusCode)
|
||||
}
|
||||
if got := resp.Header.Get("WWW-Authenticate"); !strings.HasPrefix(got, "Bearer") {
|
||||
t.Errorf("WWW-Authenticate = %q, want Bearer challenge", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogout(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
alice := createUser(t, srv, "alice")
|
||||
|
||||
resp := request(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, "")
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("logout: got %d, want 204", resp.StatusCode)
|
||||
}
|
||||
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusUnauthorized {
|
||||
t.Errorf("revoked token on /users/me: got %d, want 401", status)
|
||||
}
|
||||
if status, _ := do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, ""); status != http.StatusUnauthorized {
|
||||
t.Errorf("repeated logout: got %d, want 401", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrongPassword(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
alice := createUser(t, srv, "alice")
|
||||
|
||||
for name, password := range map[string]string{"wrong password": "Wrong-password-123", "unknown user": alice.Password} {
|
||||
username := alice.Username
|
||||
if name == "unknown user" {
|
||||
username = "nobody_" + alice.Username[:10]
|
||||
}
|
||||
resp := login(t, srv, username, password)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("%s: got %d, want 401", name, resp.StatusCode)
|
||||
}
|
||||
if got := resp.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Errorf("%s: WWW-Authenticate = %q", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisUnavailable(t *testing.T) {
|
||||
dbURL, _ := testURLs(t)
|
||||
srv := newStack(t, dbURL, deadRedisURL, time.Hour)
|
||||
|
||||
if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", "some-token-from-before-the-outage", ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" {
|
||||
t.Errorf("bearer request: got %d %q, want 503 unavailable", status, errorCode(body))
|
||||
}
|
||||
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", "", ""); status != http.StatusUnauthorized {
|
||||
t.Errorf("anonymous request: got %d, want 401", status)
|
||||
}
|
||||
if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable {
|
||||
t.Errorf("ready: got %d, want 503", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatabaseUnavailable(t *testing.T) {
|
||||
dbURL, redisURL := testURLs(t)
|
||||
healthy := newStack(t, dbURL, redisURL, time.Hour)
|
||||
alice := createUser(t, healthy, "alice")
|
||||
|
||||
srv := newStack(t, deadDatabaseURL, redisURL, time.Hour)
|
||||
if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" {
|
||||
t.Errorf("valid session: got %d %q, want 503 unavailable", status, errorCode(body))
|
||||
}
|
||||
if status, _ := do(t, srv, http.MethodPost, "/api/v1/users", "",
|
||||
`{"username":"db_down_user","display_name":"X","password":"long-enough-pass"}`); status != http.StatusServiceUnavailable {
|
||||
t.Errorf("register: got %d, want 503", status)
|
||||
}
|
||||
if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable {
|
||||
t.Errorf("ready: got %d, want 503", status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"uuid"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"messenger/internal/domain"
|
||||
"messenger/internal/service"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
var req createChatRequest
|
||||
if err := decodeJSON(w, r, &req); err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
if req.Title == nil || req.MemberIDs == nil {
|
||||
h.fail(w, r, badRequest("title and member_ids are required"))
|
||||
return
|
||||
}
|
||||
memberIDs := make([]uuid.UUID, len(*req.MemberIDs))
|
||||
for i, s := range *req.MemberIDs {
|
||||
id, ok := parseUUID(s)
|
||||
if !ok {
|
||||
h.fail(w, r, badRequest("member_ids must contain UUIDs"))
|
||||
return
|
||||
}
|
||||
memberIDs[i] = id
|
||||
}
|
||||
chat, err := h.chats.Create(r.Context(), actor(r), *req.Title, memberIDs)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
limit, cursor, err := pageParams(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
page, err := h.chats.List(r.Context(), actor(r), cursor, limit)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toPageResponse(page, toChatResponse))
|
||||
}
|
||||
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := chatIDParam(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
chat, err := h.chats.Get(r.Context(), actor(r), chatID)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func chatIDParam(r *http.Request) (uuid.UUID, error) {
|
||||
id, ok := parseUUID(chi.URLParam(r, "chat_id"))
|
||||
if !ok {
|
||||
return uuid.UUID{}, badRequest("chat_id must be a UUID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func parseUUID(s string) (uuid.UUID, bool) {
|
||||
if len(s) != 36 {
|
||||
return uuid.UUID{}, false
|
||||
}
|
||||
id, err := uuid.Parse(s)
|
||||
return id, err == nil
|
||||
}
|
||||
|
||||
func pageParams(r *http.Request) (int, *domain.Cursor, error) {
|
||||
q := r.URL.Query()
|
||||
limit := service.DefaultLimit
|
||||
if q.Has("limit") {
|
||||
n, err := strconv.Atoi(q.Get("limit"))
|
||||
if err != nil {
|
||||
return 0, nil, badRequest("limit must be an integer")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cursor *domain.Cursor
|
||||
if q.Has("cursor") {
|
||||
c, ok := decodeCursor(q.Get("cursor"))
|
||||
if !ok {
|
||||
return 0, nil, badRequest("invalid cursor")
|
||||
}
|
||||
cursor = &c
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
func encodeCursor(c domain.Cursor) string {
|
||||
raw := c.Scope.String() + "." + strconv.FormatInt(c.CreatedAt.UnixMicro(), 10) + "." + c.ID.String()
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(s string) (domain.Cursor, bool) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return domain.Cursor{}, false
|
||||
}
|
||||
parts := strings.Split(string(raw), ".")
|
||||
if len(parts) != 3 {
|
||||
return domain.Cursor{}, false
|
||||
}
|
||||
scope, err1 := uuid.Parse(parts[0])
|
||||
micros, err2 := strconv.ParseInt(parts[1], 10, 64)
|
||||
id, err3 := uuid.Parse(parts[2])
|
||||
if err1 != nil || err2 != nil || err3 != nil {
|
||||
return domain.Cursor{}, false
|
||||
}
|
||||
return domain.Cursor{Scope: scope, CreatedAt: time.UnixMicro(micros).UTC(), ID: id}, true
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
type createUserRequest struct {
|
||||
Username *string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
|
||||
type createChatRequest struct {
|
||||
Title *string `json:"title"`
|
||||
MemberIDs *[]string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text *string `json:"text"`
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type pageResponse[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User userResponse `json:"user"`
|
||||
}
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type errorBody struct {
|
||||
Error errorDetails `json:"error"`
|
||||
}
|
||||
|
||||
type errorDetails struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
const timeLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
func formatTime(t time.Time) string { return t.UTC().Format(timeLayout) }
|
||||
|
||||
func toUserResponse(u domain.User) userResponse {
|
||||
return userResponse{
|
||||
ID: u.ID.String(),
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: formatTime(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toSessionResponse(s domain.Session) sessionResponse {
|
||||
return sessionResponse{
|
||||
Token: s.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: formatTime(s.ExpiresAt),
|
||||
User: toUserResponse(s.User),
|
||||
}
|
||||
}
|
||||
|
||||
func toChatResponse(c domain.Chat) chatResponse {
|
||||
members := make([]string, len(c.MemberIDs))
|
||||
for i, id := range c.MemberIDs {
|
||||
members[i] = id.String()
|
||||
}
|
||||
return chatResponse{
|
||||
ID: c.ID.String(),
|
||||
Title: c.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: formatTime(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toMessageResponse(m domain.Message) messageResponse {
|
||||
return messageResponse{
|
||||
ID: m.ID.String(),
|
||||
ChatID: m.ChatID.String(),
|
||||
SenderID: m.SenderID.String(),
|
||||
Text: m.Text,
|
||||
CreatedAt: formatTime(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toPageResponse[D, R any](p domain.Page[D], conv func(D) R) pageResponse[R] {
|
||||
items := make([]R, len(p.Items))
|
||||
for i, it := range p.Items {
|
||||
items[i] = conv(it)
|
||||
}
|
||||
resp := pageResponse[R]{Items: items}
|
||||
if p.Next != nil {
|
||||
s := encodeCursor(*p.Next)
|
||||
resp.NextCursor = &s
|
||||
}
|
||||
return resp
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
type apiError struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.message }
|
||||
|
||||
func badRequest(msg string) *apiError {
|
||||
return &apiError{http.StatusBadRequest, "invalid_request", msg}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, code, message string) {
|
||||
writeJSON(w, status, errorBody{Error: errorDetails{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: w.Header().Get(headerRequestID),
|
||||
}})
|
||||
}
|
||||
|
||||
func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) {
|
||||
var ae *apiError
|
||||
switch {
|
||||
case errors.As(err, &ae):
|
||||
writeError(w, ae.status, ae.code, ae.message)
|
||||
case errors.Is(err, domain.ErrInvalidInput):
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
if w.Header().Get(headerWWWAuthenticate) == "" {
|
||||
w.Header().Set(headerWWWAuthenticate, bearerChallenge)
|
||||
}
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "valid authentication is required")
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
writeError(w, http.StatusNotFound, "not_found", "resource not found")
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
writeError(w, http.StatusConflict, "conflict", err.Error())
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID),
|
||||
"method", r.Method, "path", r.URL.Path, "err", err)
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "service temporarily unavailable")
|
||||
default:
|
||||
h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID),
|
||||
"method", r.Method, "path", r.URL.Path, "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "internal server error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"messenger/internal/service"
|
||||
)
|
||||
|
||||
type Pinger func(ctx context.Context) error
|
||||
|
||||
type Handler struct {
|
||||
users *service.UserService
|
||||
auth *service.AuthService
|
||||
chats *service.ChatService
|
||||
messages *service.MessageService
|
||||
deps []Pinger
|
||||
log *slog.Logger
|
||||
draining atomic.Bool
|
||||
}
|
||||
|
||||
func New(users *service.UserService, auth *service.AuthService, chats *service.ChatService,
|
||||
messages *service.MessageService, deps []Pinger, log *slog.Logger) *Handler {
|
||||
return &Handler{users: users, auth: auth, chats: chats, messages: messages, deps: deps, log: log}
|
||||
}
|
||||
|
||||
func (h *Handler) StartDraining() {
|
||||
h.draining.Store(true)
|
||||
}
|
||||
|
||||
func (h *Handler) NotFound(w http.ResponseWriter, _ *http.Request) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "resource not found")
|
||||
}
|
||||
|
||||
func (h *Handler) MethodNotAllowed(w http.ResponseWriter, _ *http.Request) {
|
||||
writeError(w, http.StatusMethodNotAllowed, "invalid_request", "method not allowed")
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
package handler_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/handler"
|
||||
"messenger/internal/repository/postgres"
|
||||
"messenger/internal/repository/redis"
|
||||
"messenger/internal/router"
|
||||
"messenger/internal/service"
|
||||
)
|
||||
|
||||
func testURLs(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
dbURL, redisURL := os.Getenv("TEST_DATABASE_URL"), os.Getenv("TEST_REDIS_URL")
|
||||
if dbURL == "" || redisURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL and TEST_REDIS_URL are required")
|
||||
}
|
||||
return dbURL, redisURL
|
||||
}
|
||||
|
||||
func newServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
dbURL, redisURL := testURLs(t)
|
||||
return newStack(t, dbURL, redisURL, time.Hour)
|
||||
}
|
||||
|
||||
func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest.Server {
|
||||
t.Helper()
|
||||
pool, err := postgres.NewPool(context.Background(), dbURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
store := postgres.New(pool)
|
||||
client, err := redis.NewClient(redisURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { client.Close() })
|
||||
sessions := redis.NewSessionStore(client)
|
||||
|
||||
users := service.NewUserService(store)
|
||||
auth := service.NewAuthService(store, sessions, ttl)
|
||||
chats := service.NewChatService(store)
|
||||
messages := service.NewMessageService(chats, store)
|
||||
h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
|
||||
srv := httptest.NewServer(router.New(h, "test"))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
type testUser struct {
|
||||
ID string
|
||||
Username string
|
||||
Password string
|
||||
Token string
|
||||
}
|
||||
|
||||
func request(t *testing.T, srv *httptest.Server, method, path, token, body string) *http.Response {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
|
||||
req.Header.Set("Idempotency-Key", uuid.New().String())
|
||||
}
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func do(t *testing.T, srv *httptest.Server, method, path, token, body string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
resp := request(t, srv, method, path, token, body)
|
||||
defer resp.Body.Close()
|
||||
var out map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
t.Fatalf("%s %s: invalid JSON response: %v", method, path, err)
|
||||
}
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
func errorCode(body map[string]any) string {
|
||||
e, _ := body["error"].(map[string]any)
|
||||
code, _ := e["code"].(string)
|
||||
return code
|
||||
}
|
||||
|
||||
func basic(username, password string) string {
|
||||
return "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))
|
||||
}
|
||||
|
||||
func login(t *testing.T, srv *httptest.Server, username, password string) *http.Response {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", basic(username, password))
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func createUser(t *testing.T, srv *httptest.Server, label string) testUser {
|
||||
t.Helper()
|
||||
u := testUser{
|
||||
Username: label + "_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:12],
|
||||
Password: "Test-password-" + label,
|
||||
}
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", "",
|
||||
fmt.Sprintf(`{"username":%q,"display_name":"Test","password":%q}`, u.Username, u.Password))
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("create user %s: status %d", u.Username, status)
|
||||
}
|
||||
u.ID = body["id"].(string)
|
||||
|
||||
resp := login(t, srv, u.Username, u.Password)
|
||||
defer resp.Body.Close()
|
||||
var session map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil || resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("login %s: status %d", u.Username, resp.StatusCode)
|
||||
}
|
||||
u.Token = session["token"].(string)
|
||||
return u
|
||||
}
|
||||
|
||||
func createChat(t *testing.T, srv *httptest.Server, owner testUser, members ...testUser) string {
|
||||
t.Helper()
|
||||
ids := make([]string, len(members))
|
||||
for i, m := range members {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
raw, _ := json.Marshal(ids)
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner.Token,
|
||||
fmt.Sprintf(`{"title":"Test","member_ids":%s}`, raw))
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("create chat: status %d", status)
|
||||
}
|
||||
return body["id"].(string)
|
||||
}
|
||||
|
||||
func TestInvalidJSON(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x","password":"long-enough-pass"}`} {
|
||||
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body)
|
||||
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
|
||||
t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestForeignChat(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
alice := createUser(t, srv, "alice")
|
||||
bob := createUser(t, srv, "bob")
|
||||
eve := createUser(t, srv, "eve")
|
||||
chat := createChat(t, srv, alice, alice, bob)
|
||||
|
||||
cases := []struct{ method, path, body string }{
|
||||
{http.MethodGet, "/api/v1/chats/" + chat, ""},
|
||||
{http.MethodGet, "/api/v1/chats/" + chat + "/messages", ""},
|
||||
{http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
status, resp := do(t, srv, c.method, c.path, eve.Token, c.body)
|
||||
if status != http.StatusNotFound || errorCode(resp) != "not_found" {
|
||||
t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status)
|
||||
}
|
||||
}
|
||||
|
||||
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve.Token, "")
|
||||
if status != http.StatusOK || len(resp["items"].([]any)) != 0 {
|
||||
t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyMessage(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
alice := createUser(t, srv, "alice")
|
||||
chat := createChat(t, srv, alice, alice)
|
||||
|
||||
for _, text := range []string{"", " ", "\n\t"} {
|
||||
body, _ := json.Marshal(map[string]string{"text": text})
|
||||
status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, string(body))
|
||||
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
|
||||
t.Errorf("text %q: got %d, want 400", text, status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateUsername(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
alice := createUser(t, srv, "alice")
|
||||
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "",
|
||||
fmt.Sprintf(`{"username":%q,"display_name":"Other","password":"another-password"}`, alice.Username))
|
||||
if status != http.StatusConflict || errorCode(resp) != "conflict" {
|
||||
t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaginationMultiplePages(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
alice := createUser(t, srv, "alice")
|
||||
chat := createChat(t, srv, alice, alice)
|
||||
|
||||
const total, limit = 7, 3
|
||||
for i := range total {
|
||||
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, fmt.Sprintf(`{"text":"msg %d"}`, i))
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("send message %d: status %d", i, status)
|
||||
}
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
pages := 0
|
||||
prevCreatedAt := ""
|
||||
cursor := ""
|
||||
for {
|
||||
path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chat, limit)
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + cursor
|
||||
}
|
||||
status, resp := do(t, srv, http.MethodGet, path, alice.Token, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("page %d: status %d", pages+1, status)
|
||||
}
|
||||
pages++
|
||||
for _, it := range resp["items"].([]any) {
|
||||
m := it.(map[string]any)
|
||||
id, createdAt := m["id"].(string), m["created_at"].(string)
|
||||
if seen[id] {
|
||||
t.Errorf("message %s returned twice", id)
|
||||
}
|
||||
if createdAt < prevCreatedAt {
|
||||
t.Errorf("messages out of order: %s after %s", createdAt, prevCreatedAt)
|
||||
}
|
||||
seen[id] = true
|
||||
prevCreatedAt = createdAt
|
||||
}
|
||||
next, ok := resp["next_cursor"].(string)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
|
||||
if len(seen) != total {
|
||||
t.Errorf("got %d messages, want %d", len(seen), total)
|
||||
}
|
||||
if want := (total + limit - 1) / limit; pages != want {
|
||||
t.Errorf("got %d pages, want %d", pages, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessages(t *testing.T) {
|
||||
srv := newServer(t)
|
||||
const clients, perClient = 10, 10
|
||||
|
||||
users := make([]testUser, clients)
|
||||
for i := range users {
|
||||
users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i))
|
||||
}
|
||||
chat := createChat(t, srv, users[0], users...)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, clients*perClient)
|
||||
for c, user := range users {
|
||||
wg.Go(func() {
|
||||
for i := range perClient {
|
||||
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user.Token,
|
||||
fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i))
|
||||
if status != http.StatusCreated {
|
||||
errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0].Token, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("read history: status %d", status)
|
||||
}
|
||||
items := resp["items"].([]any)
|
||||
ids := map[string]bool{}
|
||||
for _, it := range items {
|
||||
ids[it.(map[string]any)["id"].(string)] = true
|
||||
}
|
||||
if len(items) != clients*perClient || len(ids) != clients*perClient {
|
||||
t.Errorf("got %d messages (%d unique), want %d", len(items), len(ids), clients*perClient)
|
||||
}
|
||||
if resp["next_cursor"] != nil {
|
||||
t.Errorf("next_cursor = %v, want null", resp["next_cursor"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const readyTimeout = time.Second
|
||||
|
||||
func (h *Handler) Live(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if h.draining.Load() {
|
||||
h.fail(w, r, fmt.Errorf("%w: draining", domain.ErrUnavailable))
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), readyTimeout)
|
||||
defer cancel()
|
||||
for _, dep := range h.deps {
|
||||
if err := dep(ctx); err != nil {
|
||||
h.fail(w, r, fmt.Errorf("%w: %v", domain.ErrUnavailable, err))
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxBodyBytes = 1 << 20
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
|
||||
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mt != "application/json" {
|
||||
return &apiError{http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type must be application/json"}
|
||||
}
|
||||
|
||||
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
|
||||
if err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return &apiError{http.StatusRequestEntityTooLarge, "payload_too_large", "request body is too large"}
|
||||
}
|
||||
return badRequest("failed to read request body")
|
||||
}
|
||||
if !utf8.Valid(raw) {
|
||||
return badRequest("request body must be valid UTF-8")
|
||||
}
|
||||
if err := checkKeys(raw, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return badRequest("request body must be a valid JSON object matching the schema")
|
||||
}
|
||||
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
return badRequest("request body must contain a single JSON object")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkKeys(raw []byte, dst any) error {
|
||||
allowed := jsonFields(dst)
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
if tok, err := dec.Token(); err != nil || tok != json.Delim('{') {
|
||||
return badRequest("request body must be a JSON object")
|
||||
}
|
||||
for dec.More() {
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
return badRequest("request body must be a valid JSON object matching the schema")
|
||||
}
|
||||
key, _ := tok.(string)
|
||||
if !allowed[key] {
|
||||
return badRequest("request body contains unknown field")
|
||||
}
|
||||
var value json.RawMessage
|
||||
if err := dec.Decode(&value); err != nil {
|
||||
return badRequest("request body must be a valid JSON object matching the schema")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func jsonFields(dst any) map[string]bool {
|
||||
t := reflect.TypeOf(dst).Elem()
|
||||
fields := make(map[string]bool, t.NumField())
|
||||
for i := range t.NumField() {
|
||||
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
||||
fields[name] = true
|
||||
}
|
||||
return fields
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const headerIdempotencyKey = "Idempotency-Key"
|
||||
|
||||
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := chatIDParam(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
key := r.Header.Get(headerIdempotencyKey)
|
||||
if !idempotencyKeyRe.MatchString(key) {
|
||||
h.fail(w, r, badRequest("Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}"))
|
||||
return
|
||||
}
|
||||
var req createMessageRequest
|
||||
if err := decodeJSON(w, r, &req); err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
if req.Text == nil {
|
||||
h.fail(w, r, badRequest("text is required"))
|
||||
return
|
||||
}
|
||||
msg, err := h.messages.Send(r.Context(), actor(r), chatID, key, *req.Text)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, toMessageResponse(msg))
|
||||
}
|
||||
|
||||
func (h *Handler) ListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := chatIDParam(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
limit, cursor, err := pageParams(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
page, err := h.messages.History(r.Context(), actor(r), chatID, cursor, limit)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toPageResponse(page, toMessageResponse))
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
headerRequestID = "X-Request-Id"
|
||||
headerInstanceID = "X-Instance-Id"
|
||||
headerWWWAuthenticate = "WWW-Authenticate"
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
func InstanceID(id string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(headerInstanceID, id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(headerRequestID, uuid.New().String())
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) AccessLog(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
route := r.URL.Path
|
||||
if rc := chi.RouteContext(r.Context()); rc != nil && rc.RoutePattern() != "" {
|
||||
route = rc.RoutePattern()
|
||||
}
|
||||
h.log.Info("request",
|
||||
"request_id", w.Header().Get(headerRequestID),
|
||||
"method", r.Method,
|
||||
"route", route,
|
||||
"status", ww.Status(),
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) Recoverer(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
rec := recover()
|
||||
if rec == nil {
|
||||
return
|
||||
}
|
||||
if rec == http.ErrAbortHandler {
|
||||
panic(rec)
|
||||
}
|
||||
h.log.Error("panic", "request_id", w.Header().Get(headerRequestID),
|
||||
"method", r.Method, "path", r.URL.Path, "panic", rec, "stack", string(debug.Stack()))
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "internal server error")
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
type principal struct {
|
||||
user domain.User
|
||||
token string
|
||||
}
|
||||
|
||||
func (h *Handler) Authenticate(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := authCredentials(r, "Bearer")
|
||||
if !ok || token == "" {
|
||||
h.fail(w, r, domain.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
user, err := h.auth.Authenticate(r.Context(), token)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), ctxKey{}, principal{user: user, token: token})
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func authCredentials(r *http.Request, scheme string) (string, bool) {
|
||||
gotScheme, credentials, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok || !strings.EqualFold(gotScheme, scheme) {
|
||||
return "", false
|
||||
}
|
||||
return credentials, true
|
||||
}
|
||||
|
||||
func current(r *http.Request) principal {
|
||||
p, ok := r.Context().Value(ctxKey{}).(principal)
|
||||
if !ok {
|
||||
panic(errors.New("handler: actor requested on unauthenticated route"))
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func actor(r *http.Request) domain.User {
|
||||
return current(r).user
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package handler
|
||||
|
||||
import "net/http"
|
||||
|
||||
func (h *Handler) RegisterUser(w http.ResponseWriter, r *http.Request) {
|
||||
var req createUserRequest
|
||||
if err := decodeJSON(w, r, &req); err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
if req.Username == nil || req.DisplayName == nil || req.Password == nil {
|
||||
h.fail(w, r, badRequest("username, display_name and password are required strings"))
|
||||
return
|
||||
}
|
||||
user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName, *req.Password)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, toUserResponse(user))
|
||||
}
|
||||
|
||||
func (h *Handler) CurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, toUserResponse(actor(r)))
|
||||
}
|
||||
@@ -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,32 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position int NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_id_idx ON chat_members (user_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
sender_id uuid NOT NULL REFERENCES users (id),
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE message_idempotency;
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE message_idempotency (
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
request_hash text NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, chat_id, key)
|
||||
);
|
||||
@@ -0,0 +1,103 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/domain"
|
||||
"messenger/internal/repository/postgres"
|
||||
)
|
||||
|
||||
func newStore(t *testing.T) (*postgres.Store, *pgxpool.Pool) {
|
||||
t.Helper()
|
||||
dbURL := os.Getenv("TEST_DATABASE_URL")
|
||||
if dbURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is required")
|
||||
}
|
||||
pool, err := postgres.NewPool(context.Background(), dbURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return postgres.New(pool), pool
|
||||
}
|
||||
|
||||
func newUser(username string) domain.User {
|
||||
return domain.User{ID: uuid.New(), Username: username, DisplayName: "Test", CreatedAt: time.Now().UTC()}
|
||||
}
|
||||
|
||||
func TestRegisterUsernameRace(t *testing.T) {
|
||||
store, pool := newStore(t)
|
||||
ctx := context.Background()
|
||||
username := "race_" + uuid.New().String()[:8]
|
||||
|
||||
const workers = 20
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, workers)
|
||||
start := make(chan struct{})
|
||||
for i := range workers {
|
||||
wg.Go(func() {
|
||||
<-start
|
||||
errs[i] = store.CreateUser(ctx, newUser(username), "hash")
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
created := 0
|
||||
for _, err := range errs {
|
||||
switch {
|
||||
case err == nil:
|
||||
created++
|
||||
case !errors.Is(err, domain.ErrConflict):
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
if created != 1 {
|
||||
t.Errorf("created %d users, want exactly 1", created)
|
||||
}
|
||||
var rows int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM users WHERE username = $1`, username).Scan(&rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rows != 1 {
|
||||
t.Errorf("users rows = %d, want 1", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatRollback(t *testing.T) {
|
||||
store, pool := newStore(t)
|
||||
ctx := context.Background()
|
||||
alice := newUser("rb_" + uuid.New().String()[:8])
|
||||
if err := store.CreateUser(ctx, alice, "hash"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: "rollback",
|
||||
MemberIDs: []uuid.UUID{alice.ID, uuid.New()},
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if err := store.CreateChat(ctx, chat); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Fatalf("CreateChat with unknown member: got %v, want ErrNotFound", err)
|
||||
}
|
||||
|
||||
var chats, members int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE id = $1`, chat.ID).Scan(&chats); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM chat_members WHERE chat_id = $1`, chat.ID).Scan(&members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if chats != 0 || members != 0 {
|
||||
t.Errorf("after rollback: chats=%d chat_members=%d, want 0 and 0", chats, members)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
maxConns = 10
|
||||
connectTimeout = 3 * time.Second
|
||||
statementTimeout = "5000"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.ConnConfig.ConnectTimeout = connectTimeout
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = statementTimeout
|
||||
return pgxpool.NewWithConfig(ctx, cfg)
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
return dbErr(s.pool.Ping(ctx))
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, u domain.User, passwordHash string) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, passwordHash, u.CreatedAt)
|
||||
return dbErr(err)
|
||||
}
|
||||
|
||||
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
var u domain.User
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
return u, dbErr(err)
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByUsername(ctx context.Context, username string) (domain.User, string, error) {
|
||||
var u domain.User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1`, username,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||
return u, hash, dbErr(err)
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, c domain.Chat) error {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
c.ID, c.Title, c.CreatedAt); err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
for i, userID := range c.MemberIDs {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1, $2, $3)`,
|
||||
c.ID, userID, i); err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
}
|
||||
return dbErr(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
func (s *Store) GetChat(ctx context.Context, id uuid.UUID) (domain.Chat, error) {
|
||||
var c domain.Chat
|
||||
err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, id).
|
||||
Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Chat{}, dbErr(err)
|
||||
}
|
||||
chats := []domain.Chat{c}
|
||||
if err := s.loadMembers(ctx, chats); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return chats[0], nil
|
||||
}
|
||||
|
||||
func (s *Store) ListUserChats(ctx context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2`, userID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1 AND (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, dbErr(err)
|
||||
}
|
||||
chats, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Chat, error) {
|
||||
var c domain.Chat
|
||||
err := row.Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
return c, err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, dbErr(err)
|
||||
}
|
||||
more := len(chats) > limit
|
||||
if more {
|
||||
chats = chats[:limit]
|
||||
}
|
||||
if err := s.loadMembers(ctx, chats); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return chats, more, nil
|
||||
}
|
||||
|
||||
func (s *Store) loadMembers(ctx context.Context, chats []domain.Chat) error {
|
||||
if len(chats) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]uuid.UUID, len(chats))
|
||||
index := make(map[uuid.UUID]int, len(chats))
|
||||
for i, c := range chats {
|
||||
ids[i] = c.ID
|
||||
index[c.ID] = i
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1) ORDER BY chat_id, position`, ids)
|
||||
if err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var chatID, userID uuid.UUID
|
||||
if err := rows.Scan(&chatID, &userID); err != nil {
|
||||
return dbErr(err)
|
||||
}
|
||||
i := index[chatID]
|
||||
chats[i].MemberIDs = append(chats[i].MemberIDs, userID)
|
||||
}
|
||||
return dbErr(rows.Err())
|
||||
}
|
||||
|
||||
func (s *Store) CreateMessageIdempotent(ctx context.Context, m domain.Message, key, requestHash string) (domain.Message, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency (user_id, chat_id, key, request_hash, message_id, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT DO NOTHING`,
|
||||
m.SenderID, m.ChatID, key, requestHash, m.ID, m.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
var storedHash string
|
||||
var stored domain.Message
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM message_idempotency k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`,
|
||||
m.SenderID, m.ChatID, key,
|
||||
).Scan(&storedHash, &stored.ID, &stored.ChatID, &stored.SenderID, &stored.Text, &stored.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if storedHash != requestHash {
|
||||
return domain.Message{}, domain.ErrConflict
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||
m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt); err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.Message{}, dbErr(err)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2`, chatID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, dbErr(err)
|
||||
}
|
||||
msgs, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Message, error) {
|
||||
var m domain.Message
|
||||
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
||||
return m, err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, dbErr(err)
|
||||
}
|
||||
more := len(msgs) > limit
|
||||
if more {
|
||||
msgs = msgs[:limit]
|
||||
}
|
||||
return msgs, more, nil
|
||||
}
|
||||
|
||||
func dbErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return domain.ErrConflict
|
||||
case "23503":
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
switch pgErr.Code[:2] {
|
||||
case "08", "53", "57":
|
||||
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const keyPrefix = "session:"
|
||||
|
||||
type SessionStore struct {
|
||||
client *goredis.Client
|
||||
}
|
||||
|
||||
func NewClient(url string) (*goredis.Client, error) {
|
||||
opts, err := goredis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts.PoolSize = 10
|
||||
opts.DialTimeout = 2 * time.Second
|
||||
opts.ReadTimeout = time.Second
|
||||
opts.WriteTimeout = time.Second
|
||||
opts.MaxRetries = 0
|
||||
return goredis.NewClient(opts), nil
|
||||
}
|
||||
|
||||
func NewSessionStore(client *goredis.Client) *SessionStore {
|
||||
return &SessionStore{client: client}
|
||||
}
|
||||
|
||||
func (s *SessionStore) Ping(ctx context.Context) error {
|
||||
return cacheErr(s.client.Ping(ctx).Err())
|
||||
}
|
||||
|
||||
func (s *SessionStore) Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error {
|
||||
return cacheErr(s.client.SetArgs(ctx, keyPrefix+tokenHash, userID.String(),
|
||||
goredis.SetArgs{ExpireAt: expiresAt}).Err())
|
||||
}
|
||||
|
||||
func (s *SessionStore) Get(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
||||
v, err := s.client.Get(ctx, keyPrefix+tokenHash).Result()
|
||||
if errors.Is(err, goredis.Nil) {
|
||||
return uuid.UUID{}, domain.ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.UUID{}, cacheErr(err)
|
||||
}
|
||||
id, err := uuid.Parse(v)
|
||||
if err != nil {
|
||||
return uuid.UUID{}, domain.ErrUnauthorized
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (s *SessionStore) Delete(ctx context.Context, tokenHash string) error {
|
||||
return cacheErr(s.client.Del(ctx, keyPrefix+tokenHash).Err())
|
||||
}
|
||||
|
||||
func cacheErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"messenger/internal/handler"
|
||||
)
|
||||
|
||||
func New(h *handler.Handler, instanceID string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(handler.InstanceID(instanceID), handler.RequestID, h.AccessLog, h.Recoverer)
|
||||
|
||||
r.NotFound(h.NotFound)
|
||||
r.MethodNotAllowed(h.MethodNotAllowed)
|
||||
|
||||
r.Get("/health/live", h.Live)
|
||||
r.Get("/health/ready", h.Ready)
|
||||
|
||||
r.Route("/api/v1", func(r chi.Router) {
|
||||
r.Post("/users", h.RegisterUser)
|
||||
r.Post("/auth/sessions", h.CreateSession)
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(h.Authenticate)
|
||||
r.Delete("/auth/sessions/current", h.DeleteSession)
|
||||
r.Get("/users/me", h.CurrentUser)
|
||||
r.Post("/chats", h.CreateChat)
|
||||
r.Get("/chats", h.ListChats)
|
||||
r.Get("/chats/{chat_id}", h.GetChat)
|
||||
r.Post("/chats/{chat_id}/messages", h.SendMessage)
|
||||
r.Get("/chats/{chat_id}/messages", h.ListMessages)
|
||||
})
|
||||
})
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const tokenBytes = 32
|
||||
|
||||
type AuthService struct {
|
||||
users UserRepository
|
||||
sessions SessionStore
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(users UserRepository, sessions SessionStore, ttl time.Duration) *AuthService {
|
||||
return &AuthService{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, username, password string) (domain.Session, error) {
|
||||
user, hash, err := s.users.GetUserByUsername(ctx, username)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
ok, err := verifyPassword(password, hash)
|
||||
if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
if !ok {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
|
||||
raw := make([]byte, tokenBytes)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
expiresAt := now().Add(s.ttl)
|
||||
if err := s.sessions.Create(ctx, HashToken(token), user.ID, expiresAt); err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
return domain.Session{Token: token, ExpiresAt: expiresAt, User: user}, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Authenticate(ctx context.Context, token string) (domain.User, error) {
|
||||
userID, err := s.sessions.Get(ctx, HashToken(token))
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
u, err := s.users.GetUser(ctx, userID)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return domain.User{}, domain.ErrUnauthorized
|
||||
}
|
||||
return u, err
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
return s.sessions.Delete(ctx, HashToken(token))
|
||||
}
|
||||
|
||||
func HashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
repo ChatRepository
|
||||
}
|
||||
|
||||
func NewChatService(repo ChatRepository) *ChatService {
|
||||
return &ChatService{repo: repo}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, actor domain.User, title string, memberIDs []uuid.UUID) (domain.Chat, error) {
|
||||
if err := checkText("title", title, 100); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
if len(memberIDs) < 1 || len(memberIDs) > 100 {
|
||||
return domain.Chat{}, fmt.Errorf("%w: member_ids must contain 1 to 100 users", domain.ErrInvalidInput)
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return domain.Chat{}, fmt.Errorf("%w: member_ids must not contain duplicates", domain.ErrInvalidInput)
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if _, ok := seen[actor.ID]; !ok {
|
||||
return domain.Chat{}, fmt.Errorf("%w: member_ids must include the current user", domain.ErrInvalidInput)
|
||||
}
|
||||
|
||||
c := domain.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
if err := s.repo.CreateChat(ctx, c); err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return domain.Chat{}, fmt.Errorf("%w: member_ids contains unknown user", domain.ErrInvalidInput)
|
||||
}
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, actor domain.User, chatID uuid.UUID) (domain.Chat, error) {
|
||||
c, err := s.repo.GetChat(ctx, chatID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
if !c.HasMember(actor.ID) {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, actor domain.User, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
if err := checkLimit(limit); err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
if after != nil && after.Scope != actor.ID {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("%w: cursor does not belong to this request", domain.ErrInvalidInput)
|
||||
}
|
||||
items, more, err := s.repo.ListUserChats(ctx, actor.ID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
page := domain.Page[domain.Chat]{Items: items}
|
||||
if more {
|
||||
last := items[len(items)-1]
|
||||
page.Next = &domain.Cursor{Scope: actor.ID, CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
chats *ChatService
|
||||
messages MessageRepository
|
||||
}
|
||||
|
||||
func NewMessageService(chats *ChatService, messages MessageRepository) *MessageService {
|
||||
return &MessageService{chats: chats, messages: messages}
|
||||
}
|
||||
|
||||
func (s *MessageService) Send(ctx context.Context, actor domain.User, chatID uuid.UUID, key, text string) (domain.Message, error) {
|
||||
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := checkText("text", text, 4000); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
m := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: actor.ID,
|
||||
Text: text,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
stored, err := s.messages.CreateMessageIdempotent(ctx, m, key, hex.EncodeToString(sum[:]))
|
||||
if errors.Is(err, domain.ErrConflict) {
|
||||
return domain.Message{}, fmt.Errorf("%w: Idempotency-Key was already used with a different body", domain.ErrConflict)
|
||||
}
|
||||
return stored, err
|
||||
}
|
||||
|
||||
func (s *MessageService) History(ctx context.Context, actor domain.User, chatID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error) {
|
||||
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if err := checkLimit(limit); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if after != nil && after.Scope != chatID {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("%w: cursor belongs to another chat", domain.ErrInvalidInput)
|
||||
}
|
||||
items, more, err := s.messages.ListMessages(ctx, chatID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
page := domain.Page[domain.Message]{Items: items}
|
||||
if more {
|
||||
last := items[len(items)-1]
|
||||
page.Next = &domain.Cursor{Scope: chatID, CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory = 19 * 1024
|
||||
argonTime = 2
|
||||
argonThreads = 1
|
||||
argonSaltLen = 16
|
||||
argonKeyLen = 32
|
||||
)
|
||||
|
||||
var errBadHash = errors.New("malformed password hash")
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
b64 := base64.RawStdEncoding
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
func verifyPassword(password, encoded string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, errBadHash
|
||||
}
|
||||
var version int
|
||||
var memory, time uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return false, errBadHash
|
||||
}
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil {
|
||||
return false, errBadHash
|
||||
}
|
||||
b64 := base64.RawStdEncoding
|
||||
salt, err := b64.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, errBadHash
|
||||
}
|
||||
want, err := b64.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, errBadHash
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
CreateUser(ctx context.Context, u domain.User, passwordHash string) error
|
||||
GetUser(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
|
||||
}
|
||||
|
||||
type ChatRepository interface {
|
||||
CreateChat(ctx context.Context, c domain.Chat) error
|
||||
GetChat(ctx context.Context, id uuid.UUID) (domain.Chat, error)
|
||||
ListUserChats(ctx context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
CreateMessageIdempotent(ctx context.Context, m domain.Message, key, requestHash string) (domain.Message, error)
|
||||
ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error)
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error
|
||||
Get(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
||||
Delete(ctx context.Context, tokenHash string) error
|
||||
}
|
||||
|
||||
func now() time.Time {
|
||||
return time.Now().UTC().Truncate(time.Microsecond)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"unicode/utf8"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
const (
|
||||
minPasswordLen = 12
|
||||
maxPasswordLen = 128
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
repo UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(repo UserRepository) *UserService {
|
||||
return &UserService{repo: repo}
|
||||
}
|
||||
|
||||
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (domain.User, error) {
|
||||
if !usernameRe.MatchString(username) {
|
||||
return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput)
|
||||
}
|
||||
if err := checkText("display_name", displayName, 100); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := checkText("password", password, maxPasswordLen); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if utf8.RuneCountInString(password) < minPasswordLen {
|
||||
return domain.User{}, fmt.Errorf("%w: password must be at least %d characters", domain.ErrInvalidInput, minPasswordLen)
|
||||
}
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
u := domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
if err := s.repo.CreateUser(ctx, u, hash); err != nil {
|
||||
if errors.Is(err, domain.ErrConflict) {
|
||||
return domain.User{}, fmt.Errorf("%w: username is already taken", domain.ErrConflict)
|
||||
}
|
||||
return domain.User{}, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultLimit = 50
|
||||
MaxLimit = 100
|
||||
)
|
||||
|
||||
func checkText(field, value string, maxRunes int) error {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return fmt.Errorf("%w: %s must not be empty", domain.ErrInvalidInput, field)
|
||||
}
|
||||
if n := utf8.RuneCountInString(value); n > maxRunes {
|
||||
return fmt.Errorf("%w: %s must be at most %d characters", domain.ErrInvalidInput, field, maxRunes)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkLimit(limit int) error {
|
||||
if limit < 1 || limit > MaxLimit {
|
||||
return fmt.Errorf("%w: limit must be between 1 and %d", domain.ErrInvalidInput, MaxLimit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Executable
+56
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
WORKERS = 20
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Одновременный повтор ' + key
|
||||
barrier = threading.Barrier(WORKERS)
|
||||
results, errors = [], []
|
||||
lock = threading.Lock()
|
||||
|
||||
def send():
|
||||
barrier.wait()
|
||||
try:
|
||||
r = c.message(alice, chat, text, key=key)
|
||||
with lock:
|
||||
results.append((r['json'], r['headers']['X-Instance-Id']))
|
||||
except AssertionError as exc:
|
||||
with lock:
|
||||
errors.append(str(exc))
|
||||
|
||||
threads = [threading.Thread(target=send) for _ in range(WORKERS)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', actor=alice, schema='MessagePage')['json']['items']
|
||||
stored = [m for m in history if m['text'] == text]
|
||||
instances = sorted({i for _, i in results})
|
||||
ids = {m['id'] for m, _ in results}
|
||||
print('parallel requests with one key:', WORKERS)
|
||||
print('successful responses (201):', len(results))
|
||||
print('failed requests:', len(errors), errors[:3])
|
||||
print('distinct message ids in responses:', len(ids))
|
||||
print('messages stored in history:', len(stored))
|
||||
print('instances that served requests:', instances)
|
||||
check(not errors, 'some requests failed')
|
||||
check(len(ids) == 1 and len(stored) == 1, 'duplicate message created')
|
||||
check(all(m == results[0][0] for m, _ in results), 'replayed responses differ')
|
||||
check(len(instances) >= 2, 'requests were not spread across replicas')
|
||||
print('OK: exactly one message created')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
|
||||
if [ ! -f secrets/postgres_password ]; then
|
||||
head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > secrets/postgres_password
|
||||
fi
|
||||
password=$(cat secrets/postgres_password)
|
||||
|
||||
[ -f secrets/database_url ] ||
|
||||
printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable\n' "$password" > secrets/database_url
|
||||
[ -f secrets/cache_url ] ||
|
||||
printf 'redis://redis:6379/0\n' > secrets/cache_url
|
||||
|
||||
chmod 644 secrets/postgres_password secrets/database_url secrets/cache_url
|
||||
echo "secrets ready in ./secrets"
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)}
|
||||
COMPOSE=${COMPOSE:-$([ "$ENGINE" = podman ] && echo podman-compose || echo "docker compose")}
|
||||
|
||||
$COMPOSE stop lb api redis postgres
|
||||
$COMPOSE start postgres redis api lb
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)}
|
||||
COMPOSE=${COMPOSE:-$([ "$ENGINE" = podman ] && echo podman-compose || echo "docker compose")}
|
||||
PROJECT=${PROJECT:-messenger-lab3}
|
||||
|
||||
replicas() {
|
||||
$ENGINE ps -aq --no-trunc --filter "label=com.docker.compose.project=$PROJECT" --filter "label=com.docker.compose.service=api" | sort
|
||||
}
|
||||
|
||||
wait_healthy() {
|
||||
for _ in $(seq 1 60); do
|
||||
if [ "$($ENGINE inspect -f '{{.State.Health.Status}}' "$1" 2>/dev/null)" = "healthy" ]; then
|
||||
return 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "replica $1 did not become healthy" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
$ENGINE build --build-arg "BUILD_ID=${BUILD_ID:-$(date +%s)}" -t localhost/messenger-api:lab3 .
|
||||
$COMPOSE run --rm migrate
|
||||
|
||||
for old in $(replicas); do
|
||||
before=$(replicas)
|
||||
$ENGINE stop -t 10 "$old"
|
||||
$ENGINE rm "$old"
|
||||
$COMPOSE up -d --no-deps --no-recreate api
|
||||
for id in $(replicas); do
|
||||
if ! echo "$before" | grep -q "$id"; then
|
||||
wait_healthy "$id"
|
||||
fi
|
||||
done
|
||||
sleep 2
|
||||
done
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)}
|
||||
PROJECT=${PROJECT:-messenger-lab3}
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||
|
||||
for id in $($ENGINE ps -q --filter "label=com.docker.compose.project=$PROJECT" --filter "label=com.docker.compose.service=api"); do
|
||||
if [ "$($ENGINE inspect -f '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then
|
||||
$ENGINE stop -t 10 "$id" >/dev/null
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
Reference in New Issue
Block a user