ЛР 2 — БПИ2301 — Спесивцев — на 4 #126
@@ -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,5 +7,5 @@ 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
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
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
|
||||
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,16 @@ PYTHON ?= python3
|
||||
BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
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
|
||||
.PHONY: help check validate test load test-persistence test-go
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "test-go: Go unit/integration tests against the running stand (race, rollback, expiry, logout, outages)"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -24,3 +28,6 @@ load:
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-go:
|
||||
@TEST_DATABASE_URL="$(TEST_DATABASE_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" go test -count=1 -v ./...
|
||||
|
||||
@@ -1,37 +1,118 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Спесивцев Даниил БПИ2301
|
||||
- Целевая оценка 4; выбранный трек 5, если нужен: не заявлен
|
||||
- Commit/PR: commit "df7b8fb7010de0dd96c213ba028be9d6e838976c"
|
||||
- Использованные источники, библиотеки и помощь ИИ: 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`;
|
||||
- [golang-migrate/migrate v4.20.1](https://github.com/golang-migrate/migrate) — версионируемые миграции;
|
||||
- [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 для хеширования паролей.
|
||||
|
||||
## Запуск из чистого clone
|
||||
## Запуск из clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Тестовый стенд: i5-11400H, 16 GB RAM, без лимитов на контейнеры
|
||||
|
||||
Образы: `postgres:18.6-alpine3.24`, `redis:8.10.3-alpine3.23`; API собирается из `Dockerfile` (`golang:1.27.1-alpine3.24` → `alpine:3.24.1`). `COMPOSE` по умолчанию `docker compose`, для podman: `export COMPOSE="podman compose"`.
|
||||
|
||||
```sh
|
||||
scripts/init-secrets.sh && cp .env.example .env # локальные secrets, вне Git
|
||||
$COMPOSE --env-file .env up -d --build # миграции применяет API при старте
|
||||
until curl -sf http://localhost:8080/health/ready; do sleep 1; done
|
||||
|
||||
make check && make test
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-go # Go-тесты уровня 4
|
||||
scripts/explain.sh # → evidence/explain.txt
|
||||
scripts/outage-demo.sh # отказ Redis/PostgreSQL
|
||||
|
||||
# проверка expiry на стенде (сценарий защиты): короткий TTL, затем вернуть 3600
|
||||
SESSION_TTL_SECONDS=2 $COMPOSE --env-file .env up -d --force-recreate --no-deps api
|
||||
|
||||
$COMPOSE down # остановка, данные сохраняются
|
||||
$COMPOSE down -v # удаление учебных данных
|
||||
```
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
клиент ──HTTP:8080──▶ api (Go) ──pgx pool──▶ postgres [volume pgdata]
|
||||
└─go-redis──▶ redis [volume redisdata, AOF]
|
||||
```
|
||||
|
||||
| Роль | Service | Образ | Health | Volume | Порт | Credentials |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| api | `api` | сборка из `Dockerfile` | `/health/ready` (PG + Redis) | — | `8080` | secrets `database_url`, `cache_url` |
|
||||
| postgres | `postgres` | `postgres:18.6-alpine3.24` | `pg_isready` | `pgdata` | `127.0.0.1:55432` | secret `postgres_password` |
|
||||
| redis | `redis` | `redis:8.10.3-alpine3.23` | `redis-cli ping` | `redisdata` | `127.0.0.1:56379` | без пароля |
|
||||
|
||||
Bootstrap: `scripts/init-secrets.sh` создаёт secrets, БД и пользователя создаёт образ postgres, схему — миграции при старте API. Всё безопасно повторять.
|
||||
|
||||
- **Источник истины:** PostgreSQL — пользователи, чаты, участники, сообщения. Redis — единственное хранилище сессий (COURSE.md допускает сессии в Redis/Valkey), поэтому включён AOF (`appendfsync everysec`).
|
||||
- **Сессии:**
|
||||
- токен — 32 байта из `crypto/rand`, base64url;
|
||||
- в Redis хранится `session:<sha256(token)> → user_id` командой `SET ... EXAT`. Срок абсолютный, рестарт его не продлевает;
|
||||
- logout = `DEL`;
|
||||
- после `FLUSHALL` или потери volume Redis все сессии теряются, пользователи входят заново, данные в PG не затрагиваются.
|
||||
- **Пароли:** Argon2id (m=19 MiB, t=2, p=1), формат PHC, проверка через `subtle.ConstantTimeCompare`.
|
||||
- **Транзакции:** `POST /chats` — `chats` + `chat_members` в одной транзакции, неизвестный участник (FK 23503) → rollback → 400. Уникальность username обеспечивает `UNIQUE` (23505 → 409).
|
||||
- **Миграции:** golang-migrate, SQL встроен в бинарник через `embed`, версия в `schema_migrations`, повторный запуск — no-op.
|
||||
- **Схема:**
|
||||
- `users` (`UNIQUE username`);
|
||||
- `chats`;
|
||||
- `chat_members` (PK `(chat_id,user_id)`, индекс `(user_id)`);
|
||||
- `messages` (индекс `(chat_id, created_at, id)`).
|
||||
- **БД и Redis:** запросы только параметризованные. Pool pgx `MaxConns=10`, `ConnectTimeout=3s`, `statement_timeout=5s`. Redis `PoolSize=10`, таймауты 1–2 с.
|
||||
- **Отказы:** ошибки соединения и SQLSTATE классов 08/53/57 → `503 unavailable`. Критичны PG и Redis: `/health/ready` проверяет оба. Без Redis запрос с токеном получает 503, а не анонимный доступ.
|
||||
- **Переход с lab1:**
|
||||
- `password` при регистрации;
|
||||
- Basic только на `POST /auth/sessions`, на остальных Bearer;
|
||||
- `X-User-Id` игнорируется;
|
||||
- in-memory хранилище заменено на PG и Redis.
|
||||
- **`.env.example`:**
|
||||
- `SESSION_TTL_SECONDS` → TTL сессии;
|
||||
- `DATABASE_URL_FILE`, `CACHE_URL_FILE` → файлы-secrets;
|
||||
- `SESSION_STORE=redis` только документирует выбор.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| Критерий | Команда | Результат | Файл |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Публичный smoke | `make check && make test` | PASS | `evidence/smoke.txt` |
|
||||
| 3: данные и сессии переживают рестарт | `make test-persistence` | PASS; все 3 контейнера перезапущены, volumes те же | `evidence/persistence.txt` |
|
||||
| 3: миграции повторно без дублей | рестарт стенда | `schema_migrations=1, dirty=f` до и после | `evidence/persistence.txt` |
|
||||
| 3/4: атомарность и rollback чата | `TestCreateChatRollback` | 0 строк в `chats`/`chat_members` | `evidence/test-go.txt` |
|
||||
| 3: Basic/Bearer, `X-User-Id` не даёт доступа | smoke | PASS | `evidence/smoke.txt` |
|
||||
| 4: Redis — сессии с TTL и persistence | `make test-persistence` | прежний токен работает после рестарта Redis | `evidence/persistence.txt` |
|
||||
| 4: гонка регистрации username | `TestRegisterUsernameRace` | из 20 параллельных запросов 1 успех, 19 conflict | `evidence/test-go.txt` |
|
||||
| 4: индекс + EXPLAIN на ≥10 000 | `scripts/explain.sh` | Index Scan, 4–5 буферов | `evidence/explain.txt` |
|
||||
| 4: expiry, logout, неверный пароль | `TestSessionExpiry`, `TestLogout`, `TestWrongPassword` | 401 с нужным `WWW-Authenticate` | `evidence/test-go.txt` |
|
||||
| 4: недоступность Redis/БД | `TestRedisUnavailable`, `TestDatabaseUnavailable`, `scripts/outage-demo.sh` | 503; без токена 401; после старта тот же токен 200 | `evidence/test-go.txt`, `evidence/outage.txt` |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
## EXPLAIN истории
|
||||
|
||||
Запрос API: `WHERE chat_id=$1 AND (created_at,id) > ($2,$3) ORDER BY created_at,id LIMIT 51`. Данные: 60 328 сообщений, 20 000 из них в одном чате.
|
||||
|
||||
| План | Узел | Buffers | Время |
|
||||
| --- | --- | --- | --- |
|
||||
| Первая страница | Index Scan `messages_chat_created_id_idx` | 4 | 0.024 ms |
|
||||
| Страница после 10 000 сообщений | Index Scan, cursor в `Index Cond` | 5 | 0.042 ms |
|
||||
| Та же без индекса | Seq Scan (отброшено 50 328 строк) + Sort | 819 | 3.492 ms |
|
||||
|
||||
Индекс совпадает с фильтром и порядком сортировки, поэтому страница читает ровно 51 запись при любой глубине cursor. Цена индекса — дополнительное обновление B-tree на каждую вставку.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| Воздействие | Ожидание | Наблюдение | Восстановление / потери |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| `restart.sh` (API, PG, Redis) | данные и токен сохраняются | PASS | потерь нет |
|
||||
| `stop redis` | 503, без токена 401 | совпадает | после старта токен работает (AOF) |
|
||||
| `stop postgres` | 503, ready 503 | совпадает | pool переподключается сам |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
## Ограничения
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Один host, без HA и backup. При аварийном падении Redis возможна потеря сессий за последнюю секунду (`everysec`).
|
||||
- Redis без пароля. Порты PG и Redis открыты только на `127.0.0.1`, они нужны для `make test-go`.
|
||||
- HTTP допустим только на локальном стенде, TLS будет в lab7.
|
||||
- Не реализовано, потому что не требуется контрактом: отказ на тело у `POST /auth/sessions`, выравнивание времени ответа для неизвестного username, кэш данных.
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
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 (
|
||||
shutdownTimeout = 5 * time.Second
|
||||
migrateAttempts = 60
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
if err := migrateWithRetry(log, cfg.DatabaseURL); 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}
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: router.New(handler.New(users, auth, chats, messages, deps, log)),
|
||||
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, "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", "timeout", shutdownTimeout.String())
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info("server stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateWithRetry(log *slog.Logger, databaseURL string) error {
|
||||
var err error
|
||||
for attempt := 1; attempt <= migrateAttempts; attempt++ {
|
||||
if err = postgres.Migrate(databaseURL); err == nil {
|
||||
log.Info("migrations applied")
|
||||
return nil
|
||||
}
|
||||
log.Warn("migrations failed, retrying", "attempt", attempt, "err", err)
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
name: messenger
|
||||
|
||||
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
|
||||
ports:
|
||||
- "127.0.0.1:55432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: docker.io/library/redis:8.10.3-alpine3.23
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
ports:
|
||||
- "127.0.0.1:56379:6379"
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
restart: unless-stopped
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: localhost/messenger-api:lab2
|
||||
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
|
||||
ports:
|
||||
- "8080:8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
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,53 @@
|
||||
# scripts/explain.sh; date: 2026-10-29T22:07:31Z
|
||||
messages_total | messages_in_big_chat
|
||||
----------------+----------------------
|
||||
60328 | 20000
|
||||
(1 row)
|
||||
|
||||
=== 1. First page (limit=50 -> LIMIT 51), index messages_chat_created_id_idx
|
||||
QUERY PLAN
|
||||
---------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=0.41..8.31 rows=51 width=78) (actual time=0.009..0.014 rows=51.00 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.41..3088.25 rows=19942 width=78) (actual time=0.008..0.012 rows=51.00 loops=1)
|
||||
Index Cond: (chat_id = '00000000-0000-4000-8000-00000000e001'::uuid)
|
||||
Index Searches: 1
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=10
|
||||
Planning Time: 0.077 ms
|
||||
Execution Time: 0.024 ms
|
||||
(10 rows)
|
||||
|
||||
=== 2. Page in the middle by keyset cursor (after 10 000 messages)
|
||||
QUERY PLAN
|
||||
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=0.41..27.77 rows=51 width=78) (actual time=0.008..0.014 rows=51.00 loops=1)
|
||||
Buffers: shared hit=5
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.41..1834.26 rows=3419 width=78) (actual time=0.008..0.012 rows=51.00 loops=1)
|
||||
Index Cond: ((chat_id = '00000000-0000-4000-8000-00000000e001'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 02:46:40+00'::timestamp with time zone, 'ea1e0a08-377a-4911-aa17-221192625ad3'::uuid)))
|
||||
Index Searches: 1
|
||||
Buffers: shared hit=5
|
||||
Planning Time: 0.035 ms
|
||||
Execution Time: 0.042 ms
|
||||
(8 rows)
|
||||
|
||||
=== 3. Same middle page WITHOUT the index (dropped inside a rolled-back transaction)
|
||||
QUERY PLAN
|
||||
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=1988.81..1988.93 rows=51 width=78) (actual time=3.462..3.467 rows=51.00 loops=1)
|
||||
Buffers: shared hit=819
|
||||
-> Sort (cost=1988.81..1997.35 rows=3419 width=78) (actual time=3.462..3.464 rows=51.00 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: top-N heapsort Memory: 31kB
|
||||
Buffers: shared hit=819
|
||||
-> Seq Scan on messages (cost=0.00..1874.74 rows=3419 width=78) (actual time=0.498..2.888 rows=10000.00 loops=1)
|
||||
Filter: ((chat_id = '00000000-0000-4000-8000-00000000e001'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 02:46:40+00'::timestamp with time zone, 'ea1e0a08-377a-4911-aa17-221192625ad3'::uuid)))
|
||||
Rows Removed by Filter: 50328
|
||||
Buffers: shared hit=819
|
||||
Planning:
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.052 ms
|
||||
Execution Time: 3.492 ms
|
||||
(14 rows)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# scripts/outage-demo.sh (COMPOSE="podman compose")
|
||||
# Dependency outage demo on the live stand; date: 2026-10-29T22:09:23Z. Token is kept in a shell variable, never printed.
|
||||
baseline: GET /users/me (Bearer) -> 200
|
||||
|
||||
## podman compose stop redis
|
||||
GET /health/ready -> 503
|
||||
GET /users/me (valid Bearer) -> 503
|
||||
GET /users/me (no auth) -> 401
|
||||
POST /auth/sessions (Basic) -> 503
|
||||
body: {"error":{"code":"unavailable","message":"service temporarily unavailable","request_id":"0fc08a63-dc18-4508-a95e-7274844d13c8"}}
|
||||
## podman compose start redis -> ready; same token: GET /users/me -> 200
|
||||
|
||||
## podman compose stop postgres
|
||||
GET /health/ready -> 503
|
||||
GET /users/me (valid Bearer) -> 503
|
||||
GET /chats (valid Bearer) -> 503
|
||||
body: {"error":{"code":"unavailable","message":"service temporarily unavailable","request_id":"43f47140-394e-461e-b5bc-1863a33fc6da"}}
|
||||
## podman compose start postgres -> ready; same token: GET /users/me -> 200
|
||||
@@ -0,0 +1,26 @@
|
||||
# make test-persistence ACTION_SCRIPT=scripts/restart.sh (COMPOSE="podman compose")
|
||||
# date: 2026-10-29T22:09:51Z; podman 6.1.0, podman-compose 1.6.0
|
||||
|
||||
## containers before
|
||||
messenger_api_1 id=e8951624fe7a started=2026-10-30 01:09:02.81809688 +0300 MSK
|
||||
messenger_postgres_1 id=6aab8ebe96dd started=2026-10-30 01:09:30.742003352 +0300 MSK
|
||||
messenger_redis_1 id=7af579a966dd started=2026-10-30 01:09:28.731706375 +0300 MSK
|
||||
schema_migrations (version|dirty): 1|f
|
||||
rows users|chats|messages: 111|43|60437
|
||||
|
||||
## test
|
||||
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.
|
||||
|
||||
## containers after (same IDs, new start time = real restart, volumes kept)
|
||||
messenger_api_1 id=e8951624fe7a started=2026-10-30 01:09:54.107586909 +0300 MSK
|
||||
messenger_postgres_1 id=6aab8ebe96dd started=2026-10-30 01:09:53.97943161 +0300 MSK
|
||||
messenger_redis_1 id=7af579a966dd started=2026-10-30 01:09:54.047665509 +0300 MSK
|
||||
schema_migrations (version|dirty): 1|f
|
||||
rows users|chats|messages: 114|44|60438 (test adds 3 users, 1 chat, 1 message)
|
||||
api log after restart: "msg":"migrations applied"
|
||||
|
||||
## volumes
|
||||
messenger_pgdata
|
||||
messenger_redisdata
|
||||
@@ -0,0 +1,5 @@
|
||||
# make check && make test; date: 2026-10-29T22:09:30Z
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,18 @@
|
||||
# make test-go; date: 2026-10-29T22:09:31Z; go version go1.27.1 linux/amd64
|
||||
--- PASS: TestSessionExpiry (3.10s)
|
||||
--- PASS: TestLogout (0.07s)
|
||||
--- PASS: TestWrongPassword (0.09s)
|
||||
--- PASS: TestRedisUnavailable (2.80s)
|
||||
--- PASS: TestDatabaseUnavailable (0.16s)
|
||||
--- PASS: TestInvalidJSON (0.01s)
|
||||
--- PASS: TestForeignChat (0.16s)
|
||||
--- PASS: TestEmptyMessage (0.07s)
|
||||
--- PASS: TestDuplicateUsername (0.09s)
|
||||
--- PASS: TestPaginationMultiplePages (0.08s)
|
||||
--- PASS: TestConcurrentMessages (0.50s)
|
||||
PASS
|
||||
ok messenger/internal/handler 7.128s
|
||||
--- PASS: TestRegisterUsernameRace (0.08s)
|
||||
--- PASS: TestCreateChatRollback (0.03s)
|
||||
PASS
|
||||
ok messenger/internal/repository/postgres 0.109s
|
||||
@@ -0,0 +1,23 @@
|
||||
module messenger
|
||||
|
||||
go 1.27.1
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.3.2
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1
|
||||
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/pgerrcode v0.0.0-20220416144525-469b46aa5efa // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
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,99 @@
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dhui/dktest v0.4.6 h1:+DPKyScKSEp3VLtbMDHcUq6V5Lm5zfZZVb0Sk7Ahom4=
|
||||
github.com/dhui/dktest v0.4.6/go.mod h1:JHTSYDtKkvFNFHJKqCzVzqXecyv+tKt8EzceOmQOgbU=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaftjlSWt4AFexzM=
|
||||
github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/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/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1 h1:2N/ToVTKrKl58ynBpgeVJ4In7VcLCjWTZtm4eP1LxhU=
|
||||
github.com/golang-migrate/migrate/v4 v4.20.1/go.mod h1:DDPgKVb4ovSWc4FwSPfV2Uz1160f4XBiTHTrAJtljmM=
|
||||
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw=
|
||||
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg=
|
||||
github.com/moby/moby/api v1.54.2/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
|
||||
github.com/moby/moby/client v0.4.1 h1:DMQgisVoMkmMs7fp3ROSdiBnoAu8+vo3GggFl06M/wY=
|
||||
github.com/moby/moby/client v0.4.1/go.mod h1:z52C9O2POPOsnxZAy//WtKcQ32P+jT/NGeXu/7nfjGQ=
|
||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
|
||||
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
github.com/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.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.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,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", "username is already taken")
|
||||
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,33 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"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
|
||||
}
|
||||
|
||||
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) 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,321 @@
|
||||
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))
|
||||
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)
|
||||
}
|
||||
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,25 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
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) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), readyTimeout)
|
||||
defer cancel()
|
||||
for _, dep := range h.deps {
|
||||
if err := dep(ctx); err != nil {
|
||||
h.fail(w, r, 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,45 @@
|
||||
package handler
|
||||
|
||||
import "net/http"
|
||||
|
||||
func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := chatIDParam(r)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
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, *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,112 @@
|
||||
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"
|
||||
headerWWWAuthenticate = "WWW-Authenticate"
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
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,39 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
func Migrate(databaseURL string) error {
|
||||
src, err := iofs.New(migrationsFS, "migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m, err := migrate.NewWithSourceInstance("iofs", src, migrateURL(databaseURL))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer m.Close()
|
||||
if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateURL(databaseURL string) string {
|
||||
for _, prefix := range []string{"postgresql://", "postgres://"} {
|
||||
if rest, ok := strings.CutPrefix(databaseURL, prefix); ok {
|
||||
return "pgx5://" + rest
|
||||
}
|
||||
}
|
||||
return databaseURL
|
||||
}
|
||||
@@ -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,106 @@
|
||||
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")
|
||||
}
|
||||
if err := postgres.Migrate(dbURL); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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,237 @@
|
||||
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) CreateMessage(ctx context.Context, m domain.Message) error {
|
||||
_, err := s.pool.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)
|
||||
return dbErr(err)
|
||||
}
|
||||
|
||||
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) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(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,60 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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, 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(),
|
||||
}
|
||||
if err := s.messages.CreateMessage(ctx, m); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
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 {
|
||||
CreateMessage(ctx context.Context, m 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,55 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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 {
|
||||
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
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
COMPOSE=${COMPOSE:-docker compose}
|
||||
|
||||
{
|
||||
echo "# scripts/explain.sh; date: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
$COMPOSE exec -T postgres psql -U messenger -d messenger -X -q < scripts/explain.sql
|
||||
} > evidence/explain.txt
|
||||
cat evidence/explain.txt
|
||||
@@ -0,0 +1,66 @@
|
||||
\set ON_ERROR_STOP on
|
||||
\set big_chat '''00000000-0000-4000-8000-00000000e001'''
|
||||
\set seed_user '''00000000-0000-4000-8000-00000000e000'''
|
||||
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (:seed_user, 'explain_seed', 'Explain seed', 'not-a-login', now())
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
SELECT CASE WHEN g = 0 THEN :big_chat::uuid
|
||||
ELSE ('00000000-0000-4000-8000-' || lpad(to_hex(57345 + g), 12, '0'))::uuid END,
|
||||
'explain chat ' || g, now()
|
||||
FROM generate_series(0, 20) AS g
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT id, :seed_user, 0 FROM chats WHERE title LIKE 'explain chat %'
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), c.id, :seed_user, 'synthetic message ' || n,
|
||||
timestamptz '2026-01-01' + n * interval '1 second'
|
||||
FROM chats c
|
||||
CROSS JOIN LATERAL generate_series(1, CASE WHEN c.id = :big_chat THEN 20000 ELSE 2000 END) AS n
|
||||
WHERE c.title LIKE 'explain chat %'
|
||||
AND NOT EXISTS (SELECT 1 FROM messages m WHERE m.chat_id = c.id);
|
||||
|
||||
ANALYZE users;
|
||||
ANALYZE chats;
|
||||
ANALYZE chat_members;
|
||||
ANALYZE messages;
|
||||
|
||||
SELECT count(*) AS messages_total,
|
||||
count(*) FILTER (WHERE chat_id = :big_chat) AS messages_in_big_chat
|
||||
FROM messages;
|
||||
|
||||
SELECT created_at AS cur_ts, id AS cur_id
|
||||
FROM messages WHERE chat_id = :big_chat
|
||||
ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset
|
||||
|
||||
\echo '=== 1. First page (limit=50 -> LIMIT 51), index messages_chat_created_id_idx'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :big_chat
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51;
|
||||
|
||||
\echo '=== 2. Page in the middle by keyset cursor (after 10 000 messages)'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :big_chat AND (created_at, id) > (:'cur_ts', :'cur_id')
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51;
|
||||
|
||||
\echo '=== 3. Same middle page WITHOUT the index (dropped inside a rolled-back transaction)'
|
||||
BEGIN;
|
||||
DROP INDEX messages_chat_created_id_idx;
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :big_chat AND (created_at, id) > (:'cur_ts', :'cur_id')
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51;
|
||||
ROLLBACK;
|
||||
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
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
B=http://localhost:8080
|
||||
C=${COMPOSE:-docker compose}
|
||||
u="outage_$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')"; p="Outage-demo-password"
|
||||
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
|
||||
wait_ready() { for i in $(seq 1 60); do [ "$(code $B/health/ready)" = 200 ] && return; sleep 1; done; }
|
||||
echo "# Dependency outage demo on the live stand; date: $(date -u +%Y-%m-%dT%H:%M:%SZ). Token is kept in a shell variable, never printed."
|
||||
curl -s -o /dev/null -X POST $B/api/v1/users -H 'Content-Type: application/json' -d "{\"username\":\"$u\",\"display_name\":\"Demo\",\"password\":\"$p\"}"
|
||||
T=$(curl -s -X POST $B/api/v1/auth/sessions -u "$u:$p" | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')
|
||||
echo "baseline: GET /users/me (Bearer) -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")"
|
||||
echo; echo "## $C stop redis"; $C stop redis >/dev/null 2>&1
|
||||
echo "GET /health/ready -> $(code $B/health/ready)"
|
||||
echo "GET /users/me (valid Bearer) -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")"
|
||||
echo "GET /users/me (no auth) -> $(code $B/api/v1/users/me)"
|
||||
echo "POST /auth/sessions (Basic) -> $(code -X POST $B/api/v1/auth/sessions -u "$u:$p")"
|
||||
echo "body: $(curl -s $B/api/v1/users/me -H "Authorization: Bearer $T")"
|
||||
$C start redis >/dev/null 2>&1; wait_ready
|
||||
echo "## $C start redis -> ready; same token: GET /users/me -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")"
|
||||
echo; echo "## $C stop postgres"; $C stop postgres >/dev/null 2>&1
|
||||
echo "GET /health/ready -> $(code $B/health/ready)"
|
||||
echo "GET /users/me (valid Bearer) -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")"
|
||||
echo "GET /chats (valid Bearer) -> $(code $B/api/v1/chats -H "Authorization: Bearer $T")"
|
||||
echo "body: $(curl -s $B/api/v1/chats -H "Authorization: Bearer $T")"
|
||||
$C start postgres >/dev/null 2>&1; wait_ready
|
||||
echo "## $C start postgres -> ready; same token: GET /users/me -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")"
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
COMPOSE=${COMPOSE:-docker compose}
|
||||
|
||||
$COMPOSE stop api postgres redis
|
||||
$COMPOSE start postgres redis api
|
||||
Reference in New Issue
Block a user