forked from mtusi2026/mtusi2026lab2
ЛР2 на 4: PostgreSQL, Argon2id, Redis-сессии и persistence.
Compose-стенд, student-tests (expiry/EXPLAIN), REPORT и шпаргалка DEFENSE.
This commit is contained in:
+10
-6
@@ -1,11 +1,15 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
|
||||||
APP_HOST=0.0.0.0
|
APP_HOST=0.0.0.0
|
||||||
APP_PORT=8080
|
APP_PORT=8080
|
||||||
APP_ENV=lab
|
APP_ENV=lab
|
||||||
|
APP_ACCESS_LOG=1
|
||||||
SESSION_TTL_SECONDS=3600
|
SESSION_TTL_SECONDS=3600
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
POSTGRES_USER=messenger
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
POSTGRES_PASSWORD=messenger
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
POSTGRES_DB=messenger
|
||||||
SESSION_STORE=postgres
|
# Прямые URL для локального compose (порт 5432/6379 на хосте — для make student-test):
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
DATABASE_URL=postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable
|
||||||
|
REDIS_URL=redis://127.0.0.1:6379/0
|
||||||
|
# Альтернатива для секретов вне env (Swarm/K8s):
|
||||||
|
# DATABASE_URL_FILE=/run/secrets/database_url
|
||||||
|
# CACHE_URL_FILE=/run/secrets/cache_url
|
||||||
|
|||||||
+87
@@ -0,0 +1,87 @@
|
|||||||
|
# Шпаргалка к защите ЛР2
|
||||||
|
|
||||||
|
**Автор:** Гавриленко Владислав, БПИ2303 · **Цель:** оценка 4 (без трека 5)
|
||||||
|
**Стенд:** `http://127.0.0.1:8080` · **Ветка:** `solution/bpi2303-gavrilenko`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Быстрый старт
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd lab2
|
||||||
|
cp -n .env.example .env
|
||||||
|
bash scripts/up.sh
|
||||||
|
make test
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
make student-test
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Архитектура (что говорить)
|
||||||
|
|
||||||
|
| Компонент | Роль |
|
||||||
|
|-----------|------|
|
||||||
|
| **PostgreSQL** | Источник истины: users, chats, chat_members, messages. COMMIT = подтверждённое сообщение. |
|
||||||
|
| **Redis (AOF)** | Только сессии: opaque Bearer, TTL, logout. Ключ = SHA-256 токена, не сам токен. |
|
||||||
|
| **API (Go)** | Маршруты по OpenAPI; Basic только на `POST /auth/sessions`, дальше Bearer. |
|
||||||
|
|
||||||
|
Пароли: **Argon2id** PHC-строка в `password_hash`, не plaintext и не «быстрый» SHA для пароля.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Аутентификация
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Регистрация (пароль 12–128 символов)
|
||||||
|
curl -s -X POST http://127.0.0.1:8080/api/v1/users \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"username":"alice_demo","display_name":"Алиса","password":"correct-horse-1"}'
|
||||||
|
|
||||||
|
# Вход — только Basic, без тела
|
||||||
|
curl -s -X POST http://127.0.0.1:8080/api/v1/auth/sessions \
|
||||||
|
-H 'Authorization: Basic '"$(printf '%s:%s' alice_demo correct-horse-1 | base64)"
|
||||||
|
|
||||||
|
# Бизнес-запросы — Bearer; X-User-Id не даёт доступ
|
||||||
|
export TOKEN='<token из ответа>'
|
||||||
|
curl -s http://127.0.0.1:8080/api/v1/users/me -H "Authorization: Bearer $TOKEN"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Logout:** `DELETE /api/v1/auth/sessions/current` с Bearer → 204, тот же токен дальше 401.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Типовые вопросы
|
||||||
|
|
||||||
|
1. **Что даёт COMMIT?** Сообщение и участники чата видны после commit; при rollback составного создания чата «хвоста» нет.
|
||||||
|
|
||||||
|
2. **Сессии после restart Redis?** С AOF на volume ключи переживают `docker compose restart`; TTL API не продлевает.
|
||||||
|
|
||||||
|
3. **Отличие auth от доступа к чату?** Bearer доказывает личность; членство в `chat_members` решает 404 на чужой чат (не 403).
|
||||||
|
|
||||||
|
4. **Зачем Argon2id, а не SHA?** Медленный KDF против перебора; SHA/MD5 для паролей не подходят.
|
||||||
|
|
||||||
|
5. **Индекс `messages_history_idx`?** `(chat_id, created_at, id)` под keyset-пагинацию; EXPLAIN на ≥10k сообщений — Index Scan, не Seq Scan всей таблицы.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Проверки на защите
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make check
|
||||||
|
curl -s http://127.0.0.1:8080/health/ready
|
||||||
|
make test
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Показать: гонка username (student-test), отказ Redis/PG → 503 без анонима, короткий `SESSION_TTL_SECONDS` + expiry.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Остановка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose --env-file .env down
|
||||||
|
# Полное удаление учебных данных:
|
||||||
|
docker compose --env-file .env down -v
|
||||||
|
```
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
# syntax=docker/dockerfile:1.7
|
||||||
|
FROM golang:1.23.8-bookworm AS build
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY cmd ./cmd
|
||||||
|
COPY internal ./internal
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
||||||
|
|
||||||
|
FROM gcr.io/distroless/static-debian12:nonroot
|
||||||
|
COPY --from=build /out/server /server
|
||||||
|
USER nonroot:nonroot
|
||||||
|
EXPOSE 8080
|
||||||
|
ENV APP_HOST=0.0.0.0 \
|
||||||
|
APP_PORT=8080 \
|
||||||
|
APP_ENV=lab \
|
||||||
|
SESSION_TTL_SECONDS=3600
|
||||||
|
HEALTHCHECK --interval=5s --timeout=3s --start-period=15s --retries=5 \
|
||||||
|
CMD ["/server", "-healthcheck"]
|
||||||
|
ENTRYPOINT ["/server"]
|
||||||
@@ -4,7 +4,9 @@ CA_FILE ?=
|
|||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence
|
GO ?= go
|
||||||
|
|
||||||
|
.PHONY: help check validate test load test-persistence student-test
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||||
@@ -24,3 +26,6 @@ load:
|
|||||||
test-persistence:
|
test-persistence:
|
||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
@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)
|
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
student-test:
|
||||||
|
$(GO) test ./student-tests/ -v -count=1 -timeout 300s
|
||||||
|
|||||||
@@ -1,37 +1,63 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: **Гавриленко Владислав, БПИ2303**
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка; трек 5: **4** (трек 5 не заявляется)
|
||||||
- Commit/PR: TODO после публикации
|
- Ветка: `solution/bpi2303-gavrilenko`
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Источники: Go `net/http`, `jackc/pgx/v5`, `redis/go-redis/v9`, `golang.org/x/crypto/argon2`, `google/uuid`; публичные `tests/` и `contracts/` skeleton; перенос паттернов из собственной lab1; реализация с опорой на учебную архитектуру lab2 (самостоятельный код, модуль `gavrilenko-sxdees/lab2`).
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Требования: Docker, Go 1.23+, Python 3.9+.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
bash scripts/up.sh
|
||||||
|
# или: docker compose --env-file .env up -d --build
|
||||||
|
curl -s http://127.0.0.1:8080/health/ready
|
||||||
|
make test
|
||||||
|
make student-test
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Остановка: `docker compose --env-file .env stop`.
|
||||||
|
Удаление учебных volumes: `docker compose --env-file .env down -v`.
|
||||||
|
|
||||||
|
Образы: сборка `golang:1.23.8-bookworm`, runtime `gcr.io/distroless/static-debian12:nonroot`, PostgreSQL `postgres:16.6`, Redis `redis:7.4.1` (`appendonly yes`, `appendfsync everysec`).
|
||||||
|
|
||||||
|
Переменные: в compose заданы `DATABASE_URL` и `REDIS_URL`; `config` также читает `DATABASE_URL_FILE` / `CACHE_URL_FILE` из `.env.example`. `SESSION_TTL_SECONDS` по умолчанию 3600.
|
||||||
|
|
||||||
|
Миграции вшиты в бинарник (`internal/store/migrations`), применяются при старте; повтор безопасен через `schema_migrations`.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Клиент → API → **PostgreSQL** (users, chats, chat_members, messages). **Redis** — только сессии: opaque Bearer, TTL, logout; в ключах SHA-256 токена.
|
||||||
|
|
||||||
|
Пароли: **Argon2id** (`m=19456,t=2,p=1`). Basic только на `POST /api/v1/auth/sessions` (без тела). Остальное — Bearer; `X-User-Id` не используется. Недоступность PG/Redis → **503**, не аноним.
|
||||||
|
|
||||||
|
Создание чата — одна транзакция; гонка username — `UNIQUE`. История — keyset `(created_at, id)` с индексом `messages_history_idx (chat_id, created_at, id)`.
|
||||||
|
|
||||||
|
Из lab1: те же семантики чатов/сообщений/cursor; вместо `X-User-Id` — сессии и PostgreSQL.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
Стенд: macOS, Docker Desktop, локальные порты 8080/5432/6379. Прогон: 2026-12-01.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
| Критерий | Команда | Результат | Файл |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Публичный smoke | `make test` | PASS | `evidence/smoke-pass.txt` |
|
||||||
|
| Persistence API+PG+Redis | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS | `evidence/persistence.txt` |
|
||||||
|
| Student-тесты (4) | `make student-test` | ok, 11 тестов | `evidence/student-test.txt` |
|
||||||
|
| EXPLAIN ≥10k | `TestMessagesHistoryIndexExplain` | `messages_history_idx`, Bitmap Index Scan | `evidence/student-test.txt`, `evidence/explain-history.json` |
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
| Воздействие | Ожидание | Наблюдение |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `docker compose restart` (volumes сохранены) | данные PG + сессия Redis | persistence PASS |
|
||||||
|
| Logout | 204, затем 401 | student-test |
|
||||||
|
| Redis/PG down | 503, без user JSON | student-test |
|
||||||
|
| SESSION_TTL 2s | 401 после паузы | student-test |
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
## Ограничения
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| TODO | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
`appendfsync everysec` — при `kill -9` Redis возможна потеря ~1 с новых сессий. EXPLAIN снят на одном хосте Docker, не распределённый бенчмарк. Трек 5 (кэш/consistency, backup 100k+) не выполнялся.
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// Утилита для снятия EXPLAIN (ANALYZE, BUFFERS) в evidence/ без трека 5.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
dsn := flag.String("database-url", os.Getenv("DATABASE_URL"), "PostgreSQL DSN")
|
||||||
|
out := flag.String("out", "evidence/explain-history.json", "output file")
|
||||||
|
minMessages := flag.Int("min-messages", 10000, "minimum messages in largest chat")
|
||||||
|
flag.Parse()
|
||||||
|
if *dsn == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "set DATABASE_URL or -database-url")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
pool, err := pgxpool.New(ctx, *dsn)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
var chatID uuid.UUID
|
||||||
|
var count int
|
||||||
|
err = pool.QueryRow(ctx, `
|
||||||
|
SELECT chat_id, count(*)::int FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 1`).
|
||||||
|
Scan(&chatID, &count)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "need seeded messages:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if count < *minMessages {
|
||||||
|
fmt.Fprintf(os.Stderr, "largest chat has %d messages, need %d (run student TestMessagesHistoryIndexExplain or load)\n", count, *minMessages)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
var curAt time.Time
|
||||||
|
var curID uuid.UUID
|
||||||
|
off := count / 2
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
SELECT created_at, id FROM messages
|
||||||
|
WHERE chat_id = $1 ORDER BY created_at, id OFFSET $2 LIMIT 1`, chatID, off).
|
||||||
|
Scan(&curAt, &curID); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
var plan []byte
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||||
|
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 51`, chatID, curAt, curID).Scan(&plan); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
planStr := string(plan)
|
||||||
|
if strings.Contains(strings.ToLower(planStr), "seq scan on messages") {
|
||||||
|
fmt.Fprintln(os.Stderr, "plan uses seq scan")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
report := map[string]any{
|
||||||
|
"chat_id": chatID.String(),
|
||||||
|
"message_count": count,
|
||||||
|
"cursor_offset": off,
|
||||||
|
"generated_at": time.Now().UTC().Format(time.RFC3339),
|
||||||
|
"index_expected": "messages_history_idx",
|
||||||
|
"explain_analyze": json.RawMessage(plan),
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(*out), 0o755); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
b, err := json.MarshalIndent(report, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(*out, b, 0o644); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Printf("wrote %s chat=%s messages=%d\n", *out, chatID, count)
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
// Точка входа HTTP API.
|
||||||
|
//
|
||||||
|
// Процесс поднимает пул PostgreSQL, применяет миграции, проверяет Redis и только потом слушает порт.
|
||||||
|
// SIGTERM переводит /health/ready в 503 и даёт текущим запросам до 10 секунд на завершение.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gavrilenko-sxdees/lab2/internal/api"
|
||||||
|
"gavrilenko-sxdees/lab2/internal/auth"
|
||||||
|
"gavrilenko-sxdees/lab2/internal/config"
|
||||||
|
"gavrilenko-sxdees/lab2/internal/session"
|
||||||
|
"gavrilenko-sxdees/lab2/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
healthcheck := flag.Bool("healthcheck", false, "probe local /health/ready and exit")
|
||||||
|
flag.Parse()
|
||||||
|
if *healthcheck {
|
||||||
|
os.Exit(runHealthcheck())
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("config: %v", err)
|
||||||
|
}
|
||||||
|
hasher, err := auth.NewHasher()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("password hasher: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rootCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
// docker compose restart поднимает API одновременно с Postgres.
|
||||||
|
// Процесс не выходит сразу: иначе контейнер останется мёртвым, а тест сохранности
|
||||||
|
// не дождётся /health/ready. Ждём хранилища ограниченное время.
|
||||||
|
st, err := waitPostgres(rootCtx, cfg.DatabaseURL, hasher)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("postgres: %v", err)
|
||||||
|
}
|
||||||
|
defer st.Close()
|
||||||
|
if err := st.Migrate(rootCtx); err != nil {
|
||||||
|
log.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
sessions, err := waitRedis(rootCtx, cfg.RedisURL, cfg.SessionTTL)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("redis: %v", err)
|
||||||
|
}
|
||||||
|
defer sessions.Close()
|
||||||
|
|
||||||
|
srvAPI := api.New(st, sessions)
|
||||||
|
httpServer := &http.Server{
|
||||||
|
Addr: cfg.Addr(),
|
||||||
|
Handler: srvAPI.Handler(),
|
||||||
|
ReadHeaderTimeout: 5 * time.Second,
|
||||||
|
ReadTimeout: 15 * time.Second,
|
||||||
|
WriteTimeout: 15 * time.Second,
|
||||||
|
IdleTimeout: 60 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
errCh := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
log.Printf("listening on %s env=%s session_ttl=%s", cfg.Addr(), cfg.Env, cfg.SessionTTL)
|
||||||
|
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
errCh <- err
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-errCh:
|
||||||
|
log.Fatalf("listen: %v", err)
|
||||||
|
case <-rootCtx.Done():
|
||||||
|
}
|
||||||
|
log.Printf("shutting down")
|
||||||
|
srvAPI.BeginDrain()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := httpServer.Shutdown(ctx); err != nil {
|
||||||
|
log.Printf("shutdown error: %v", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
log.Printf("shutdown complete")
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitPostgres(ctx context.Context, dsn string, hasher *auth.Hasher) (*store.Store, error) {
|
||||||
|
deadline := time.Now().Add(45 * time.Second)
|
||||||
|
var last error
|
||||||
|
for {
|
||||||
|
st, err := store.Open(ctx, dsn, hasher)
|
||||||
|
if err == nil {
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
last = err
|
||||||
|
if ctx.Err() != nil || time.Now().After(deadline) {
|
||||||
|
return nil, last
|
||||||
|
}
|
||||||
|
log.Printf("postgres not ready, retrying")
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitRedis(ctx context.Context, redisURL string, ttl time.Duration) (*session.Store, error) {
|
||||||
|
deadline := time.Now().Add(45 * time.Second)
|
||||||
|
var last error
|
||||||
|
for {
|
||||||
|
st, err := session.Open(redisURL, ttl)
|
||||||
|
if err == nil {
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
last = err
|
||||||
|
if ctx.Err() != nil || time.Now().After(deadline) {
|
||||||
|
return nil, last
|
||||||
|
}
|
||||||
|
log.Printf("redis not ready, retrying")
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runHealthcheck() int {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
host := cfg.Host
|
||||||
|
if host == "0.0.0.0" || host == "::" {
|
||||||
|
host = "127.0.0.1"
|
||||||
|
}
|
||||||
|
client := &http.Client{Timeout: 2 * time.Second}
|
||||||
|
resp, err := client.Get(fmt.Sprintf("http://%s:%d/health/ready", host, cfg.Port))
|
||||||
|
if err != nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
_, _ = io.Copy(io.Discard, resp.Body)
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# Локальный стенд lab2. Образы закреплены тегом, не latest.
|
||||||
|
# Сессии живут в Redis с AOF: рестарт контейнера не стирает ключи, volume redisdata сохраняет файл.
|
||||||
|
# PostgreSQL — источник истины для пользователей, чатов и сообщений.
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.6
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:5432:5432"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
stop_grace_period: 10s
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7.4.1
|
||||||
|
# everysec — компромисс durability: потерять можно около секунды записей при внезапном kill -9,
|
||||||
|
# обычный docker restart данные сессий сохраняет.
|
||||||
|
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
|
||||||
|
volumes:
|
||||||
|
- redisdata:/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:6379:6379"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
stop_grace_period: 10s
|
||||||
|
|
||||||
|
api:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
APP_HOST: 0.0.0.0
|
||||||
|
APP_PORT: 8080
|
||||||
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
|
APP_ACCESS_LOG: ${APP_ACCESS_LOG:-1}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:-messenger}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable
|
||||||
|
REDIS_URL: redis://redis:6379/0
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8080:8080"
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
stop_grace_period: 10s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
|
redisdata:
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
{
|
||||||
|
"chat_id": "784ecbaf-2866-46fb-a540-60de53ca7e45",
|
||||||
|
"cursor_offset": 5000,
|
||||||
|
"explain_analyze": [
|
||||||
|
{
|
||||||
|
"Plan": {
|
||||||
|
"Node Type": "Limit",
|
||||||
|
"Parallel Aware": false,
|
||||||
|
"Async Capable": false,
|
||||||
|
"Startup Cost": 43.71,
|
||||||
|
"Total Cost": 43.75,
|
||||||
|
"Plan Rows": 13,
|
||||||
|
"Plan Width": 88,
|
||||||
|
"Actual Startup Time": 0.850,
|
||||||
|
"Actual Total Time": 0.857,
|
||||||
|
"Actual Rows": 51,
|
||||||
|
"Actual Loops": 1,
|
||||||
|
"Shared Hit Blocks": 96,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0,
|
||||||
|
"Plans": [
|
||||||
|
{
|
||||||
|
"Node Type": "Sort",
|
||||||
|
"Parent Relationship": "Outer",
|
||||||
|
"Parallel Aware": false,
|
||||||
|
"Async Capable": false,
|
||||||
|
"Startup Cost": 43.71,
|
||||||
|
"Total Cost": 43.75,
|
||||||
|
"Plan Rows": 13,
|
||||||
|
"Plan Width": 88,
|
||||||
|
"Actual Startup Time": 0.849,
|
||||||
|
"Actual Total Time": 0.852,
|
||||||
|
"Actual Rows": 51,
|
||||||
|
"Actual Loops": 1,
|
||||||
|
"Sort Key": [
|
||||||
|
"created_at",
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"Sort Method": "top-N heapsort",
|
||||||
|
"Sort Space Used": 31,
|
||||||
|
"Sort Space Type": "Memory",
|
||||||
|
"Shared Hit Blocks": 96,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0,
|
||||||
|
"Plans": [
|
||||||
|
{
|
||||||
|
"Node Type": "Bitmap Heap Scan",
|
||||||
|
"Parent Relationship": "Outer",
|
||||||
|
"Parallel Aware": false,
|
||||||
|
"Async Capable": false,
|
||||||
|
"Relation Name": "messages",
|
||||||
|
"Alias": "messages",
|
||||||
|
"Startup Cost": 4.42,
|
||||||
|
"Total Cost": 43.47,
|
||||||
|
"Plan Rows": 13,
|
||||||
|
"Plan Width": 88,
|
||||||
|
"Actual Startup Time": 0.151,
|
||||||
|
"Actual Total Time": 0.533,
|
||||||
|
"Actual Rows": 5000,
|
||||||
|
"Actual Loops": 1,
|
||||||
|
"Recheck Cond": "((chat_id = '784ecbaf-2866-46fb-a540-60de53ca7e45'::uuid) AND (ROW(created_at, id) \u003e ROW('2026-12-01 18:50:30.409+00'::timestamp with time zone, 'b7df3404-b811-4c6b-abde-620eb65e01f4'::uuid)))",
|
||||||
|
"Rows Removed by Index Recheck": 0,
|
||||||
|
"Exact Heap Blocks": 58,
|
||||||
|
"Lossy Heap Blocks": 0,
|
||||||
|
"Shared Hit Blocks": 96,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0,
|
||||||
|
"Plans": [
|
||||||
|
{
|
||||||
|
"Node Type": "Bitmap Index Scan",
|
||||||
|
"Parent Relationship": "Outer",
|
||||||
|
"Parallel Aware": false,
|
||||||
|
"Async Capable": false,
|
||||||
|
"Index Name": "messages_history_idx",
|
||||||
|
"Startup Cost": 0.00,
|
||||||
|
"Total Cost": 4.41,
|
||||||
|
"Plan Rows": 13,
|
||||||
|
"Plan Width": 0,
|
||||||
|
"Actual Startup Time": 0.145,
|
||||||
|
"Actual Total Time": 0.145,
|
||||||
|
"Actual Rows": 5000,
|
||||||
|
"Actual Loops": 1,
|
||||||
|
"Index Cond": "((chat_id = '784ecbaf-2866-46fb-a540-60de53ca7e45'::uuid) AND (ROW(created_at, id) \u003e ROW('2026-12-01 18:50:30.409+00'::timestamp with time zone, 'b7df3404-b811-4c6b-abde-620eb65e01f4'::uuid)))",
|
||||||
|
"Shared Hit Blocks": 38,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"Planning": {
|
||||||
|
"Shared Hit Blocks": 0,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0
|
||||||
|
},
|
||||||
|
"Planning Time": 0.066,
|
||||||
|
"Triggers": [],
|
||||||
|
"Execution Time": 0.882
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"generated_at": "2026-12-01T18:50:28Z",
|
||||||
|
"index_expected": "messages_history_idx",
|
||||||
|
"message_count": 10001
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
wrote evidence/explain-history.json chat=784ecbaf-2866-46fb-a540-60de53ca7e45 messages=10001
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||||
|
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
go test ./student-tests/ -v -count=1 -timeout 300s
|
||||||
|
=== RUN TestMalformedJSONAndValidation
|
||||||
|
api_test.go:73: → битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=400 request_id=8c7814c1-87d3-453a-b677-b021cbf01e4b duration_ms=0
|
||||||
|
api_test.go:76: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"8c7814c1-87d3-453a-b677-b021cbf01e4b"}}
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=400 request_id=aae104b0-eec3-4a65-93c8-c0328e5ccf1b duration_ms=0
|
||||||
|
api_test.go:83: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"aae104b0-eec3-4a65-93c8-c0328e5ccf1b"}}
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=201 request_id=a1f7ae77-60d4-4076-b5e0-f6ea277a5001 duration_ms=42
|
||||||
|
api_test.go:88: создан ok_user_408ebe33 id=cca112bd-8bcb-411c-ae4e-ee602c58a1c4
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/auth/sessions status=201 request_id=67214acc-d0b9-42f0-a343-76fe09ed3a24 duration_ms=30
|
||||||
|
api_test.go:89: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/chats status=201 request_id=81523706-f3b3-41a1-a29b-d298fe95c987 duration_ms=4
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/chats/e7f1a5f5-b736-4ded-8ec0-8ecfc7bc4deb/messages status=400 request_id=bc9dfa6c-5570-45ac-98a0-9b7917efe6bb duration_ms=0
|
||||||
|
api_test.go:96: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"bc9dfa6c-5570-45ac-98a0-9b7917efe6bb"}}
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/chats/e7f1a5f5-b736-4ded-8ec0-8ecfc7bc4deb/messages status=400 request_id=10cc785c-5bf4-4285-ae8e-1c6cbc440388 duration_ms=0
|
||||||
|
api_test.go:96: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"10cc785c-5bf4-4285-ae8e-1c6cbc440388"}}
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/chats/e7f1a5f5-b736-4ded-8ec0-8ecfc7bc4deb/messages status=400 request_id=5e090a6f-5a66-40c8-877f-85d02cdbefe9 duration_ms=0
|
||||||
|
api_test.go:103: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"5e090a6f-5a66-40c8-877f-85d02cdbefe9"}}
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=201 request_id=35833ed0-66a9-44d4-969b-c5eb58e590c8 duration_ms=27
|
||||||
|
api_test.go:108: создан outsider_f22faf8d id=bc57d071-c347-4010-b991-ef2239080933
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/auth/sessions status=201 request_id=2a5aa20d-3ce8-4fab-82bb-9f8f63156b47 duration_ms=27
|
||||||
|
api_test.go:109: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/chats/e7f1a5f5-b736-4ded-8ec0-8ecfc7bc4deb/messages status=404 request_id=2c8908a8-e144-48fd-8df8-ad4c165452bb duration_ms=4
|
||||||
|
api_test.go:111: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"2c8908a8-e144-48fd-8df8-ad4c165452bb"}}
|
||||||
|
api_test.go:115: ✓ валидация JSON, хвоста, пустого текста и чужого чата
|
||||||
|
--- PASS: TestMalformedJSONAndValidation (0.14s)
|
||||||
|
=== RUN TestMessageTextPreservedAndLengthOnOriginal
|
||||||
|
api_test.go:121: → пробелы по краям сохраняются; длина считается по исходному тексту
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=201 request_id=c4576ba4-ee5e-4eff-ae73-640770374c11 duration_ms=30
|
||||||
|
api_test.go:122: создан text_user_5e70838a id=94d594c7-bec8-4975-bbba-3347ff0a53ca
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/auth/sessions status=201 request_id=7db5073a-8a46-4804-a732-2a61f21e26f2 duration_ms=27
|
||||||
|
api_test.go:123: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/chats status=201 request_id=9e3b1eb2-80f9-4792-9936-888cc3f430f8 duration_ms=4
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/chats/913d769a-0a04-4201-b8bd-002444ffd5ee/messages status=201 request_id=b37dd318-1d61-4949-970f-5bec95d7315f duration_ms=1
|
||||||
|
api_test.go:130: status=201 body={"chat_id":"913d769a-0a04-4201-b8bd-002444ffd5ee","created_at":"2026-12-01T18:50:22.234Z","id":"b46b0564-ac0b-456e-891b-8e618ec913c2","sender_id":"94d594c7-bec8-4975-bbba-3347ff0a53ca","text":" строка\nс пробелами "}
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/chats/913d769a-0a04-4201-b8bd-002444ffd5ee/messages status=400 request_id=13f3c10a-fb33-4ef8-ad43-29c1934218b6 duration_ms=0
|
||||||
|
api_test.go:142: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"13f3c10a-fb33-4ef8-ad43-29c1934218b6"}}
|
||||||
|
api_test.go:146: ✓ текст сохранён целиком, обход лимита через TrimSpace закрыт
|
||||||
|
--- PASS: TestMessageTextPreservedAndLengthOnOriginal (0.07s)
|
||||||
|
=== RUN TestSessionRejectsJSONBody
|
||||||
|
api_test.go:152: → POST /auth/sessions с телом должен быть 400 даже при верном Basic
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=201 request_id=6bcee86b-7ab8-44da-82cf-c8f303d37bbb duration_ms=29
|
||||||
|
api_test.go:153: создан body_user_5c7f5121 id=a66ffce9-7349-4e57-9a01-bed231077616
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/auth/sessions status=400 request_id=b866cf4d-d1f3-4b3b-a4da-a4b3a80fcb18 duration_ms=0
|
||||||
|
api_test.go:157: status=400 body={"error":{"code":"invalid_request","message":"session create must not have a body","request_id":"b866cf4d-d1f3-4b3b-a4da-a4b3a80fcb18"}}
|
||||||
|
api_test.go:161: ✓ вход без JSON body
|
||||||
|
--- PASS: TestSessionRejectsJSONBody (0.03s)
|
||||||
|
=== RUN TestWrongPasswordLogoutAndIgnoredUserHeader
|
||||||
|
api_test.go:167: → неверный пароль, Basic на бизнес-методе, X-User-Id, logout
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=201 request_id=197d0423-ff61-4233-b7ab-2f5d98b327bd duration_ms=30
|
||||||
|
api_test.go:168: создан auth_user_ed92896c id=fb94cd87-882f-4664-a96c-dc57e221537b
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=201 request_id=fe1e77ae-ab9a-4a1d-838e-611c13008d49 duration_ms=27
|
||||||
|
api_test.go:169: создан auth_other_df6f670c id=8fd27932-4d87-407b-9581-f2332bd4d913
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/auth/sessions status=401 request_id=380ec531-07c5-4ddb-92f4-3266d9cb9057 duration_ms=27
|
||||||
|
api_test.go:174: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"380ec531-07c5-4ddb-92f4-3266d9cb9057"}}
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/auth/sessions status=201 request_id=ef83d617-1d7c-4171-91e4-9d49d9d4ee73 duration_ms=28
|
||||||
|
api_test.go:179: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||||
|
2026/12/01 21:50:22 method=GET path=/api/v1/users/me status=401 request_id=7f5443d5-6704-4b42-ba33-b1d389a885ee duration_ms=0
|
||||||
|
api_test.go:183: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"7f5443d5-6704-4b42-ba33-b1d389a885ee"}}
|
||||||
|
2026/12/01 21:50:22 method=GET path=/api/v1/users/me status=401 request_id=fe283e43-b207-4ecb-bbf6-fe590d3a95ae duration_ms=0
|
||||||
|
api_test.go:189: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"fe283e43-b207-4ecb-bbf6-fe590d3a95ae"}}
|
||||||
|
2026/12/01 21:50:22 method=GET path=/api/v1/users/me status=200 request_id=66d1b66d-3735-432e-b4d0-eb6e79bf0beb duration_ms=1
|
||||||
|
api_test.go:198: status=200 body={"created_at":"2026-12-01T18:50:22.299Z","display_name":"Студент","id":"fb94cd87-882f-4664-a96c-dc57e221537b","username":"auth_user_ed92896c"}
|
||||||
|
2026/12/01 21:50:22 method=DELETE path=/api/v1/auth/sessions/current status=204 request_id=83c72daa-041a-4e92-bfc0-040d9686b037 duration_ms=3
|
||||||
|
api_test.go:204: logout status=204
|
||||||
|
2026/12/01 21:50:22 method=GET path=/api/v1/users/me status=401 request_id=50e56d70-6cb5-434c-8798-3846a90ed39f duration_ms=0
|
||||||
|
2026/12/01 21:50:22 method=DELETE path=/api/v1/auth/sessions/current status=401 request_id=2f8073a1-0d88-458d-a6a6-dbcba25bfd76 duration_ms=0
|
||||||
|
api_test.go:216: ✓ пароль, заголовки и отзыв сессии
|
||||||
|
--- PASS: TestWrongPasswordLogoutAndIgnoredUserHeader (0.12s)
|
||||||
|
=== RUN TestSessionExpiry
|
||||||
|
api_test.go:222: → SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/users status=201 request_id=d644280c-b318-456d-8738-15293d4cf0b7 duration_ms=27
|
||||||
|
api_test.go:223: создан ttl_user_13145d83 id=301cc0f8-ada0-4456-ad2b-251262161e63
|
||||||
|
2026/12/01 21:50:22 method=POST path=/api/v1/auth/sessions status=201 request_id=57b5eaf4-d723-4750-b5c0-9fe0e250006b duration_ms=28
|
||||||
|
api_test.go:224: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||||
|
2026/12/01 21:50:24 method=GET path=/api/v1/users/me status=401 request_id=6a35105c-933d-473c-8c42-57104f7fbd3d duration_ms=1
|
||||||
|
api_test.go:227: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"6a35105c-933d-473c-8c42-57104f7fbd3d"}}
|
||||||
|
api_test.go:231: ✓ истёкшая сессия отклонена
|
||||||
|
--- PASS: TestSessionExpiry (2.56s)
|
||||||
|
=== RUN TestDuplicateUsernameRace
|
||||||
|
api_test.go:238: → 8 параллельных регистраций username=race_807ba169
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=201 request_id=7a92fb01-bf76-46ab-9f12-3479782a07d8 duration_ms=91
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=409 request_id=02713e04-590a-4c14-8e73-3289a28b5603 duration_ms=94
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=409 request_id=12d7152f-5483-4b78-991d-ac7247c5ba8f duration_ms=97
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=409 request_id=eb441666-04e5-49ad-a81b-dfbf00339294 duration_ms=88
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=409 request_id=a18c4930-ce1a-494c-96db-649d042368a9 duration_ms=101
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=409 request_id=98bdfcd0-0450-4f80-bbfe-766f09db1a60 duration_ms=100
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=409 request_id=378f385e-ed06-4cf7-ab11-7cd4f40bc90e duration_ms=102
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=409 request_id=4e4adb18-6e97-4dcb-8c34-77a2a1891b9c duration_ms=106
|
||||||
|
api_test.go:263: created=1 conflict=7
|
||||||
|
api_test.go:267: ✓ UNIQUE username выдержал гонку
|
||||||
|
--- PASS: TestDuplicateUsernameRace (0.11s)
|
||||||
|
=== RUN TestChatCreateRollsBack
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=201 request_id=7716707a-7331-44ab-8679-c2c367f3105e duration_ms=32
|
||||||
|
api_test.go:273: создан roll_user_75e279d9 id=c709350a-58b2-42b1-8333-ba491252a445
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/auth/sessions status=201 request_id=b09ff4de-407c-4179-a9f0-ba72ce238ea6 duration_ms=33
|
||||||
|
api_test.go:274: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||||
|
api_test.go:277: → создание чата с несуществующим участником должно откатиться, title=rollback-f430e70d-c8c0-444a-a77f-f1c59b1689e9
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/chats status=400 request_id=589dc17f-f4f0-46b5-81cb-c090f4a8b48f duration_ms=4
|
||||||
|
api_test.go:280: status=400 body={"error":{"code":"invalid_request","message":"unknown member","request_id":"589dc17f-f4f0-46b5-81cb-c090f4a8b48f"}}
|
||||||
|
api_test.go:288: строк chats с этим title после ошибки: 0
|
||||||
|
api_test.go:292: ✓ транзакция создания чата откатилась
|
||||||
|
--- PASS: TestChatCreateRollsBack (0.08s)
|
||||||
|
=== RUN TestPaginationPages
|
||||||
|
api_test.go:298: → три сообщения, две страницы limit=2, затем последняя
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=201 request_id=182a861e-f996-44a7-9c17-b31187bfe227 duration_ms=35
|
||||||
|
api_test.go:299: создан page_user_906741f1 id=4ec624ed-4023-491d-8ee2-6fd1e31861c7
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/auth/sessions status=201 request_id=4e35191b-1973-4408-bcab-bfee095e5132 duration_ms=34
|
||||||
|
api_test.go:300: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/chats status=201 request_id=3321328d-432f-43ec-9e5e-9c2abb849714 duration_ms=4
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/chats/457a99ba-136b-46df-a5f6-83a5008b8370/messages status=201 request_id=45de49bf-6b39-43d1-83fa-fdc31c4f5b29 duration_ms=1
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/chats/457a99ba-136b-46df-a5f6-83a5008b8370/messages status=201 request_id=a95b3627-aa7b-4c3d-967e-30b22700afa5 duration_ms=1
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/chats/457a99ba-136b-46df-a5f6-83a5008b8370/messages status=201 request_id=f1b3140f-f4a2-4fac-b268-cf1c836f956b duration_ms=1
|
||||||
|
2026/12/01 21:50:25 method=GET path=/api/v1/chats/457a99ba-136b-46df-a5f6-83a5008b8370/messages status=200 request_id=20509bc7-eaa6-465a-bfac-db28ff6f48ef duration_ms=4
|
||||||
|
api_test.go:310: status=200 body={"items":[{"chat_id":"457a99ba-136b-46df-a5f6-83a5008b8370","created_at":"2026-12-01T18:50:25.219Z","id":"07536bba-3e33-4d66-923a-4a4ff37f9689","sender_id":"4ec624ed-4023-491d-8ee2-6fd1e31861c7","text":"раз"},{"chat_id":"457a99ba-136b-46df-a5f6-83a5008b8370","created_at":"2026-12-01T18:50:25.221Z","id":"e9cc6d68-0785-43a9-a974-9e5810e35af1","sender_id":"4ec624ed-4023-491d-8ee2-6fd1e31861c7","te...
|
||||||
|
2026/12/01 21:50:25 method=GET path=/api/v1/chats/457a99ba-136b-46df-a5f6-83a5008b8370/messages status=200 request_id=040d2cdf-e95c-42bf-8738-2a3aa4d61f1b duration_ms=2
|
||||||
|
api_test.go:318: status=200 body={"items":[{"chat_id":"457a99ba-136b-46df-a5f6-83a5008b8370","created_at":"2026-12-01T18:50:25.222Z","id":"864382d9-192e-4403-8b2a-e85223827162","sender_id":"4ec624ed-4023-491d-8ee2-6fd1e31861c7","text":"три"}],"next_cursor":null}
|
||||||
|
api_test.go:324: ✓ keyset обошёл историю без зависания cursor
|
||||||
|
--- PASS: TestPaginationPages (0.09s)
|
||||||
|
=== RUN TestRedisDownIsNotAnonymous
|
||||||
|
api_test.go:328: → закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=201 request_id=f7c39bb5-90c1-4831-90f4-44143bb3f61a duration_ms=33
|
||||||
|
api_test.go:340: создан redis_down_bbc56966 id=f1de2bbe-2e7f-4159-b284-6914f94595f7
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/auth/sessions status=503 request_id=bb0f101c-879a-4c19-b4ae-115a3c9600be duration_ms=28
|
||||||
|
api_test.go:344: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"bb0f101c-879a-4c19-b4ae-115a3c9600be"}}
|
||||||
|
2026/12/01 21:50:25 method=GET path=/api/v1/users/me status=503 request_id=b87ce6e1-de89-46f3-9cd1-a9570e4270c6 duration_ms=0
|
||||||
|
api_test.go:351: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"b87ce6e1-de89-46f3-9cd1-a9570e4270c6"}}
|
||||||
|
api_test.go:355: ✓ сбой Redis не стал анонимным доступом
|
||||||
|
--- PASS: TestRedisDownIsNotAnonymous (0.07s)
|
||||||
|
=== RUN TestPostgresDownIsNotAnonymous
|
||||||
|
api_test.go:359: → закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/users status=201 request_id=a961cc22-bfdb-4dc5-b5d9-46bc9f75fcd0 duration_ms=28
|
||||||
|
api_test.go:362: создан pg_down_41fff6fc id=d92583f4-77f1-4b80-82bf-413cf20ea48b
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/auth/sessions status=201 request_id=fa9976ca-c842-46be-9a06-e56cc04cd608 duration_ms=29
|
||||||
|
api_test.go:363: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||||
|
2026/12/01 21:50:25 method=GET path=/health/ready status=503 request_id=0ea20664-4b12-4952-90fd-4f61cf0afebf duration_ms=0
|
||||||
|
api_test.go:384: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"0ea20664-4b12-4952-90fd-4f61cf0afebf"}}
|
||||||
|
2026/12/01 21:50:25 method=GET path=/api/v1/users/me status=503 request_id=5b48d911-8a0e-4423-8205-b48b9ed0708a duration_ms=0
|
||||||
|
api_test.go:391: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"5b48d911-8a0e-4423-8205-b48b9ed0708a"}}
|
||||||
|
2026/12/01 21:50:25 method=POST path=/api/v1/auth/sessions status=503 request_id=e029c234-40fa-42cb-a436-f34c42d28634 duration_ms=0
|
||||||
|
api_test.go:398: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"e029c234-40fa-42cb-a436-f34c42d28634"}}
|
||||||
|
api_test.go:402: ✓ сбой PostgreSQL не стал анонимным доступом
|
||||||
|
--- PASS: TestPostgresDownIsNotAnonymous (0.11s)
|
||||||
|
=== RUN TestMessagesHistoryIndexExplain
|
||||||
|
explain_test.go:55: → вставка 10001 сообщений в один чат
|
||||||
|
explain_test.go:102: EXPLAIN plan: [
|
||||||
|
{
|
||||||
|
"Plan": {
|
||||||
|
"Node Type": "Limit",
|
||||||
|
"Parallel Aware": false,
|
||||||
|
"Async Capable": false,
|
||||||
|
"Startup Cost": 43.71,
|
||||||
|
"Total Cost": 43.75,
|
||||||
|
"Plan Rows": 13,
|
||||||
|
"Plan Width": 88,
|
||||||
|
"Actual Startup Time": 0.815,
|
||||||
|
"Actual Total Time": 0.821,
|
||||||
|
"Actual Rows": 51,
|
||||||
|
"Actual Loops": 1,
|
||||||
|
"Shared Hit Blocks": 96,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0,
|
||||||
|
"Plans": [
|
||||||
|
{
|
||||||
|
"Node Type": "Sort",
|
||||||
|
"Parent Relationship": "Outer",
|
||||||
|
"Parallel Aware": false,
|
||||||
|
"Async Capable": false,
|
||||||
|
"Startup Cost": 43.71,
|
||||||
|
"Total Cost": 43.75,
|
||||||
|
"Plan Rows": 13,
|
||||||
|
"Plan Width": 88,
|
||||||
|
"Actual Startup Time": 0.814,
|
||||||
|
"Actual Total Time": 0.817,
|
||||||
|
"Actual Rows": 51,
|
||||||
|
"Actual Loops": 1,
|
||||||
|
"Sort Key": ["created_at", "id"],
|
||||||
|
"Sort Method": "top-N heapsort",
|
||||||
|
"Sort Space Used": 31,
|
||||||
|
"Sort Space Type": "Memory",
|
||||||
|
"Shared Hit Blocks": 96,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0,
|
||||||
|
"Plans": [
|
||||||
|
{
|
||||||
|
"Node Type": "Bitmap Heap Scan",
|
||||||
|
"Parent Relationship": "Outer",
|
||||||
|
"Parallel Aware": false,
|
||||||
|
"Async Capable": false,
|
||||||
|
"Relation Name": "messages",
|
||||||
|
"Alias": "messages",
|
||||||
|
"Startup Cost": 4.42,
|
||||||
|
"Total Cost": 43.47,
|
||||||
|
"Plan Rows": 13,
|
||||||
|
"Plan Width": 88,
|
||||||
|
"Actual Startup Time": 0.137,
|
||||||
|
"Actual Total Time": 0.497,
|
||||||
|
"Actual Rows": 5000,
|
||||||
|
"Actual Loops": 1,
|
||||||
|
"Recheck Cond": "((chat_id = '784ecbaf-2866-46fb-a540-60de53ca7e45'::uuid) AND (ROW(created_at, id) > ROW('2026-12-01 18:50:30.409+00'::timestamp with time zone, 'b7df3404-b811-4c6b-abde-620eb65e01f4'::uuid)))",
|
||||||
|
"Rows Removed by Index Recheck": 0,
|
||||||
|
"Exact Heap Blocks": 58,
|
||||||
|
"Lossy Heap Blocks": 0,
|
||||||
|
"Shared Hit Blocks": 96,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0,
|
||||||
|
"Plans": [
|
||||||
|
{
|
||||||
|
"Node Type": "Bitmap Index Scan",
|
||||||
|
"Parent Relationship": "Outer",
|
||||||
|
"Parallel Aware": false,
|
||||||
|
"Async Capable": false,
|
||||||
|
"Index Name": "messages_history_idx",
|
||||||
|
"Startup Cost": 0.00,
|
||||||
|
"Total Cost": 4.41,
|
||||||
|
"Plan Rows": 13,
|
||||||
|
"Plan Width": 0,
|
||||||
|
"Actual Startup Time": 0.131,
|
||||||
|
"Actual Total Time": 0.131,
|
||||||
|
"Actual Rows": 5000,
|
||||||
|
"Actual Loops": 1,
|
||||||
|
"Index Cond": "((chat_id = '784ecbaf-2866-46fb-a540-60de53ca7e45'::uuid) AND (ROW(created_at, id) > ROW('2026-12-01 18:50:30.409+00'::timestamp with time zone, 'b7df3404-b811-4c6b-abde-620eb65e01f4'::uuid)))",
|
||||||
|
"Shared Hit Blocks": 38,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"Planning": {
|
||||||
|
"Shared Hit Blocks": 0,
|
||||||
|
"Shared Read Blocks": 0,
|
||||||
|
"Shared Dirtied Blocks": 0,
|
||||||
|
"Shared Written Blocks": 0,
|
||||||
|
"Local Hit Blocks": 0,
|
||||||
|
"Local Read Blocks": 0,
|
||||||
|
"Local Dirtied Blocks": 0,
|
||||||
|
"Local Written Blocks": 0,
|
||||||
|
"Temp Read Blocks": 0,
|
||||||
|
"Temp Written Blocks": 0
|
||||||
|
},
|
||||||
|
"Planning Time": 0.052,
|
||||||
|
"Triggers": [
|
||||||
|
],
|
||||||
|
"Execution Time": 0.842
|
||||||
|
}
|
||||||
|
]
|
||||||
|
explain_test.go:116: ✓ индекс истории подтверждён EXPLAIN на 10001 сообщении
|
||||||
|
--- PASS: TestMessagesHistoryIndexExplain (0.29s)
|
||||||
|
PASS
|
||||||
|
ok gavrilenko-sxdees/lab2/student-tests 3.997s
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
module gavrilenko-sxdees/lab2
|
||||||
|
|
||||||
|
go 1.23.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/jackc/pgx/v5 v5.7.4
|
||||||
|
github.com/redis/go-redis/v9 v9.7.0
|
||||||
|
golang.org/x/crypto v0.31.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
golang.org/x/sync v0.10.0 // indirect
|
||||||
|
golang.org/x/sys v0.28.0 // indirect
|
||||||
|
golang.org/x/text v0.21.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||||
|
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||||
|
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
|
||||||
|
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
|
||||||
|
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||||
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||||
|
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||||
|
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||||
|
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||||
|
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||||
|
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,650 @@
|
|||||||
|
// Package api — HTTP-слой lab2.
|
||||||
|
//
|
||||||
|
// Порядок обработки запроса:
|
||||||
|
// 1. X-Request-Id на каждый ответ, включая ошибки;
|
||||||
|
// 2. журнал method/path/status без текста сообщений и без токена;
|
||||||
|
// 3. маршрут;
|
||||||
|
// 4. для защищённых маршрутов — только Bearer. Basic и X-User-Id доступ не дают.
|
||||||
|
//
|
||||||
|
// /health/live отвечает, пока процесс жив. /health/ready ещё проверяет PostgreSQL и Redis:
|
||||||
|
// без них нельзя честно принять запись или узнать, кто делает запрос.
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"gavrilenko-sxdees/lab2/internal/session"
|
||||||
|
"gavrilenko-sxdees/lab2/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ctxKey int
|
||||||
|
|
||||||
|
const (
|
||||||
|
userKey ctxKey = iota
|
||||||
|
tokenKey
|
||||||
|
requestIDKey
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
challengeBasic = `Basic realm="messenger", charset="UTF-8"`
|
||||||
|
challengeBearer = `Bearer realm="messenger"`
|
||||||
|
)
|
||||||
|
|
||||||
|
// Server связывает HTTP с PostgreSQL и Redis.
|
||||||
|
type Server struct {
|
||||||
|
Store *store.Store
|
||||||
|
Sessions *session.Store
|
||||||
|
ready atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// New помечает процесс готовым. Реальная зависимость всё равно проверяется в /health/ready.
|
||||||
|
func New(st *store.Store, sessions *session.Store) *Server {
|
||||||
|
s := &Server{Store: st, Sessions: sessions}
|
||||||
|
s.ready.Store(true)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// BeginDrain вызывается на SIGTERM: новые клиенты видят 503 на /health/ready.
|
||||||
|
func (s *Server) BeginDrain() { s.ready.Store(false) }
|
||||||
|
|
||||||
|
// Handler собирает маршруты lab2. Идемпотентности и вложений здесь нет — это lab3+.
|
||||||
|
func (s *Server) Handler() http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /health/live", s.handleLive)
|
||||||
|
mux.HandleFunc("GET /health/ready", s.handleReady)
|
||||||
|
mux.HandleFunc("POST /api/v1/users", s.handleCreateUser)
|
||||||
|
mux.HandleFunc("POST /api/v1/auth/sessions", s.handleCreateSession)
|
||||||
|
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", s.requireUser(s.handleRevokeSession))
|
||||||
|
mux.HandleFunc("GET /api/v1/users/me", s.requireUser(s.handleMe))
|
||||||
|
mux.HandleFunc("POST /api/v1/chats", s.requireUser(s.handleCreateChat))
|
||||||
|
mux.HandleFunc("GET /api/v1/chats", s.requireUser(s.handleListChats))
|
||||||
|
mux.HandleFunc("GET /api/v1/chats/{chat_id}", s.requireUser(s.handleGetChat))
|
||||||
|
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleCreateMessage))
|
||||||
|
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleListMessages))
|
||||||
|
return s.withRequestID(s.withAccessLog(mux))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleLive(w http.ResponseWriter, r *http.Request) {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !s.ready.Load() {
|
||||||
|
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "service is shutting down")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil {
|
||||||
|
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if err := decodeStrict(r, &body); err != nil {
|
||||||
|
writeDecodeErr(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !validUsername(body.Username) {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid username")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
display := strings.TrimSpace(body.DisplayName)
|
||||||
|
if display == "" || utf8.RuneCountInString(display) > 100 {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid display_name")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n := utf8.RuneCountInString(body.Password); n < 12 || n > 128 {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid password")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, err := s.Store.CreateUser(r.Context(), body.Username, display, body.Password)
|
||||||
|
if err != nil {
|
||||||
|
s.writeStoreErr(w, r, err, http.StatusConflict, "conflict", "username already taken")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, userDTO(u))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCreateSession(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Контракт: только Basic, без JSON body. Любые байты в теле — 400, не тихий игнор.
|
||||||
|
rawBody, err := io.ReadAll(io.LimitReader(r.Body, 4096))
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(bytes.TrimSpace(rawBody)) != 0 {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "session create must not have a body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username, password, ok := parseBasic(r.Header.Get("Authorization"))
|
||||||
|
if !ok || !validUsername(username) {
|
||||||
|
writeAuthError(w, r, challengeBasic)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n := utf8.RuneCountInString(password); n < 12 || n > 128 {
|
||||||
|
writeAuthError(w, r, challengeBasic)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, err := s.Store.Authenticate(r.Context(), username, password)
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
writeAuthError(w, r, challengeBasic)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeStoreErr(w, r, err, 0, "", "")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token, exp, err := s.Sessions.Issue(r.Context(), u.ID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, map[string]any{
|
||||||
|
"token": token,
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_at": formatTime(exp),
|
||||||
|
"user": userDTO(u),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleRevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||||
|
token, _ := r.Context().Value(tokenKey).(string)
|
||||||
|
if err := s.Sessions.Revoke(r.Context(), token); err != nil {
|
||||||
|
if errors.Is(err, session.ErrUnauthorized) {
|
||||||
|
writeAuthError(w, r, challengeBearer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
|
||||||
|
u, err := s.Store.GetUser(r.Context(), userFrom(r))
|
||||||
|
if err != nil {
|
||||||
|
s.writeStoreErr(w, r, err, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, userDTO(u))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCreateChat(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
MemberIDs []string `json:"member_ids"`
|
||||||
|
}
|
||||||
|
if err := decodeStrict(r, &body); err != nil {
|
||||||
|
writeDecodeErr(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
title := strings.TrimSpace(body.Title)
|
||||||
|
if title == "" || utf8.RuneCountInString(title) > 100 {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid title")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uid := userFrom(r)
|
||||||
|
seen := make(map[uuid.UUID]struct{}, len(body.MemberIDs))
|
||||||
|
ids := make([]uuid.UUID, 0, len(body.MemberIDs))
|
||||||
|
callerPresent := false
|
||||||
|
for _, raw := range body.MemberIDs {
|
||||||
|
id, err := uuid.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, dup := seen[id]; dup {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "duplicate member id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
if id == uid {
|
||||||
|
callerPresent = true
|
||||||
|
}
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
if !callerPresent {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "caller must be a member")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chat, err := s.Store.CreateChat(r.Context(), title, ids)
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "unknown member")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeStoreErr(w, r, err, 0, "", "")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, chatDTO(chat))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleListChats(w http.ResponseWriter, r *http.Request) {
|
||||||
|
uid := userFrom(r)
|
||||||
|
limit, after, err := parsePage(r, "chats:"+uid.String())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, next, err := s.Store.ListChats(r.Context(), uid, limit, after)
|
||||||
|
if err != nil {
|
||||||
|
s.writeStoreErr(w, r, err, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := make([]any, len(items))
|
||||||
|
for i := range items {
|
||||||
|
out[i] = chatDTO(&items[i])
|
||||||
|
}
|
||||||
|
var cursor *store.PageCursor
|
||||||
|
if next != nil {
|
||||||
|
cursor = &store.PageCursor{Scope: "chats:" + uid.String(), CreatedAt: next.CreatedAt, ID: next.ID}
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, pageDTO(out, cursor))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleGetChat(w http.ResponseWriter, r *http.Request) {
|
||||||
|
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chat, err := s.Store.GetChat(r.Context(), chatID, userFrom(r))
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeStoreErr(w, r, err, 0, "", "")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, chatDTO(chat))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
if err := decodeStrict(r, &body); err != nil {
|
||||||
|
writeDecodeErr(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Непустота — по TrimSpace; длина и сохранение — по исходному тексту.
|
||||||
|
// Иначе пробелы по краям пропадают, а строка «пробел + 4000 букв» проходит как 4000.
|
||||||
|
if strings.TrimSpace(body.Text) == "" || utf8.RuneCountInString(body.Text) > 4000 {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
msg, err := s.Store.CreateMessage(r.Context(), chatID, userFrom(r), body.Text)
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeStoreErr(w, r, err, 0, "", "")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, messageDTO(msg))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleListMessages(w http.ResponseWriter, r *http.Request) {
|
||||||
|
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
scope := "chat:" + chatID.String()
|
||||||
|
limit, after, err := parsePage(r, scope)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, next, err := s.Store.ListMessages(r.Context(), chatID, userFrom(r), limit, after)
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.writeStoreErr(w, r, err, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := make([]any, len(items))
|
||||||
|
for i := range items {
|
||||||
|
out[i] = messageDTO(&items[i])
|
||||||
|
}
|
||||||
|
var cursor *store.PageCursor
|
||||||
|
if next != nil {
|
||||||
|
cursor = &store.PageCursor{Scope: scope, CreatedAt: next.CreatedAt, ID: next.ID}
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, pageDTO(out, cursor))
|
||||||
|
}
|
||||||
|
|
||||||
|
// requireUser принимает только Authorization: Bearer. X-User-Id не читается.
|
||||||
|
// Basic на бизнес-методе — тот же 401, но с Bearer-challenge, не с Basic.
|
||||||
|
func (s *Server) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
header := r.Header.Get("Authorization")
|
||||||
|
if strings.HasPrefix(strings.ToLower(header), "basic ") {
|
||||||
|
writeAuthError(w, r, challengeBearer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token, ok := parseBearer(header)
|
||||||
|
if !ok {
|
||||||
|
writeAuthError(w, r, challengeBearer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uid, err := s.Sessions.Lookup(r.Context(), token)
|
||||||
|
if errors.Is(err, session.ErrUnauthorized) {
|
||||||
|
writeAuthError(w, r, challengeBearer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx := context.WithValue(r.Context(), userKey, uid)
|
||||||
|
ctx = context.WithValue(ctx, tokenKey, token)
|
||||||
|
next(w, r.WithContext(ctx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func userFrom(r *http.Request) uuid.UUID {
|
||||||
|
id, _ := r.Context().Value(userKey).(uuid.UUID)
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) withRequestID(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rid := r.Header.Get("X-Request-Id")
|
||||||
|
if rid == "" {
|
||||||
|
rid = uuid.NewString()
|
||||||
|
}
|
||||||
|
w.Header().Set("X-Request-Id", rid)
|
||||||
|
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, rid)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type statusRecorder struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *statusRecorder) WriteHeader(code int) {
|
||||||
|
s.status = code
|
||||||
|
s.ResponseWriter.WriteHeader(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) withAccessLog(next http.Handler) http.Handler {
|
||||||
|
quiet := strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "0") || strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "false")
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
start := time.Now()
|
||||||
|
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||||
|
next.ServeHTTP(rec, r)
|
||||||
|
if quiet && rec.status < 400 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/health/") && rec.status == http.StatusOK {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||||
|
// path без query: в cursor нет секрета, но и текста сообщения в логе быть не должно.
|
||||||
|
log.Printf("method=%s path=%s status=%d request_id=%s duration_ms=%d",
|
||||||
|
r.Method, r.URL.Path, rec.status, rid, time.Since(start).Milliseconds())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePage(r *http.Request, expectedScope string) (int, *store.PageCursor, error) {
|
||||||
|
limit := 50
|
||||||
|
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||||
|
n, err := strconv.Atoi(raw)
|
||||||
|
if err != nil || n < 1 || n > 100 {
|
||||||
|
return 0, nil, fmt.Errorf("invalid limit")
|
||||||
|
}
|
||||||
|
limit = n
|
||||||
|
}
|
||||||
|
rawCursor := r.URL.Query().Get("cursor")
|
||||||
|
if rawCursor == "" {
|
||||||
|
return limit, nil, nil
|
||||||
|
}
|
||||||
|
cur, err := decodeCursor(rawCursor)
|
||||||
|
if err != nil || cur.Scope != expectedScope {
|
||||||
|
return 0, nil, fmt.Errorf("invalid cursor")
|
||||||
|
}
|
||||||
|
return limit, cur, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeCursor(c *store.PageCursor) string {
|
||||||
|
payload := fmt.Sprintf("%s|%s|%s", c.Scope, c.CreatedAt.UTC().Format(time.RFC3339Nano), c.ID.String())
|
||||||
|
return base64.RawURLEncoding.EncodeToString([]byte(payload))
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeCursor(raw string) (*store.PageCursor, error) {
|
||||||
|
b, err := base64.RawURLEncoding.DecodeString(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(string(b), "|", 3)
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return nil, fmt.Errorf("bad cursor")
|
||||||
|
}
|
||||||
|
ts, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id, err := uuid.Parse(parts[2])
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &store.PageCursor{Scope: parts[0], CreatedAt: ts.UTC(), ID: id}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validUsername(s string) bool {
|
||||||
|
if len(s) < 3 || len(s) > 32 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range s {
|
||||||
|
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeStrict(r *http.Request, dst any) error {
|
||||||
|
ct := r.Header.Get("Content-Type")
|
||||||
|
if ct != "" && !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ct)), "application/json") {
|
||||||
|
return errUnsupported
|
||||||
|
}
|
||||||
|
// Читаем тело целиком: Decoder.More() не ловит хвост вида {"text":"x"}} —
|
||||||
|
// после одного объекта More()=false, а лишняя скобка всё равно остаётся.
|
||||||
|
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||||
|
if err != nil {
|
||||||
|
return errMalformed
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
if err := dec.Decode(dst); err != nil {
|
||||||
|
return errMalformed
|
||||||
|
}
|
||||||
|
rest := bytes.TrimSpace(raw[dec.InputOffset():])
|
||||||
|
if len(rest) != 0 {
|
||||||
|
return errMalformed
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
errUnsupported = errors.New("unsupported media type")
|
||||||
|
errMalformed = errors.New("malformed json")
|
||||||
|
)
|
||||||
|
|
||||||
|
func writeDecodeErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||||
|
if errors.Is(err, errUnsupported) {
|
||||||
|
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed json")
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBasic(header string) (string, string, bool) {
|
||||||
|
const prefix = "basic "
|
||||||
|
if len(header) < len(prefix) || strings.ToLower(header[:len(prefix)]) != prefix {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(header[len(prefix):]))
|
||||||
|
if err != nil || !utf8.Valid(raw) {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
user, pass, ok := strings.Cut(string(raw), ":")
|
||||||
|
if !ok || user == "" {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
return user, pass, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBearer(header string) (string, bool) {
|
||||||
|
const prefix = "bearer "
|
||||||
|
if len(header) < len(prefix) || strings.ToLower(header[:len(prefix)]) != prefix {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
token := strings.TrimSpace(header[len(prefix):])
|
||||||
|
if token == "" || strings.Contains(token, " ") {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return token, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func userDTO(u *store.User) map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"id": u.ID.String(),
|
||||||
|
"username": u.Username,
|
||||||
|
"display_name": u.DisplayName,
|
||||||
|
"created_at": formatTime(u.CreatedAt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func chatDTO(c *store.Chat) map[string]any {
|
||||||
|
ids := make([]string, len(c.MemberIDs))
|
||||||
|
for i, id := range c.MemberIDs {
|
||||||
|
ids[i] = id.String()
|
||||||
|
}
|
||||||
|
return map[string]any{
|
||||||
|
"id": c.ID.String(),
|
||||||
|
"title": c.Title,
|
||||||
|
"member_ids": ids,
|
||||||
|
"created_at": formatTime(c.CreatedAt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func messageDTO(m *store.Message) map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"id": m.ID.String(),
|
||||||
|
"chat_id": m.ChatID.String(),
|
||||||
|
"sender_id": m.SenderID.String(),
|
||||||
|
"text": m.Text,
|
||||||
|
"created_at": formatTime(m.CreatedAt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func pageDTO(items []any, next *store.PageCursor) map[string]any {
|
||||||
|
var cursor any
|
||||||
|
if next != nil {
|
||||||
|
cursor = encodeCursor(next)
|
||||||
|
}
|
||||||
|
if items == nil {
|
||||||
|
items = []any{}
|
||||||
|
}
|
||||||
|
return map[string]any{"items": items, "next_cursor": cursor}
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatTime(t time.Time) string {
|
||||||
|
return t.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z")
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
_ = enc.Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeError(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||||
|
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||||
|
if rid == "" {
|
||||||
|
rid = w.Header().Get("X-Request-Id")
|
||||||
|
}
|
||||||
|
writeJSON(w, status, map[string]any{
|
||||||
|
"error": map[string]any{
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
"request_id": rid,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAuthError(w http.ResponseWriter, r *http.Request, challenge string) {
|
||||||
|
w.Header().Set("WWW-Authenticate", challenge)
|
||||||
|
writeError(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeStoreErr прячет текст драйвера. fallbackStatus используется для ожидаемой доменной ошибки.
|
||||||
|
func (s *Server) writeStoreErr(w http.ResponseWriter, r *http.Request, err error, fallbackStatus int, fallbackCode, fallbackMessage string) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, store.ErrUnavailable):
|
||||||
|
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||||
|
case errors.Is(err, store.ErrConflict) && fallbackStatus != 0:
|
||||||
|
writeError(w, r, fallbackStatus, fallbackCode, fallbackMessage)
|
||||||
|
case errors.Is(err, store.ErrNotFound) && fallbackStatus != 0:
|
||||||
|
if fallbackCode == "unauthorized" {
|
||||||
|
writeAuthError(w, r, challengeBearer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeError(w, r, fallbackStatus, fallbackCode, fallbackMessage)
|
||||||
|
case errors.Is(err, store.ErrInvalidCursor):
|
||||||
|
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||||
|
default:
|
||||||
|
if errors.Is(err, store.ErrConflict) {
|
||||||
|
writeError(w, r, http.StatusConflict, "conflict", "username already taken")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// В лог — только тип, без SQL и без текста, который драйвер мог вложить в ошибку.
|
||||||
|
log.Printf("request_id=%s store_error_type=%T", requestID(r), err)
|
||||||
|
writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestID(r *http.Request) string {
|
||||||
|
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||||
|
return rid
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
// Package auth хранит пароли через Argon2id.
|
||||||
|
//
|
||||||
|
// bcrypt отвергнут: библиотека молча режет пароль на 72 байта, а контракт
|
||||||
|
// разрешает до 128 Unicode code points, включая символы вне ASCII.
|
||||||
|
// Argon2id принимает пароль целиком. Параметры — интерактивные, не «серверные»
|
||||||
|
// на сотни миллисекунд: smoke создаёт несколько пользователей подряд.
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/argon2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
argonTime = 2
|
||||||
|
argonMemory = 19 * 1024 // KiB, около 19 MiB
|
||||||
|
argonThreads = 1
|
||||||
|
argonKeyLen = 32
|
||||||
|
argonSaltLen = 16
|
||||||
|
)
|
||||||
|
|
||||||
|
// Hasher умеет хешировать и проверять. dummy — хеш случайного пароля,
|
||||||
|
// чтобы отсутствующий username занимал примерно столько же CPU, сколько неверный пароль.
|
||||||
|
type Hasher struct {
|
||||||
|
dummy string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHasher готовит dummy-хеш один раз на процесс.
|
||||||
|
func NewHasher() (*Hasher, error) {
|
||||||
|
dummy, err := Hash(randomPassword())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Hasher{dummy: dummy}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash возвращает PHC-строку. Её пишем в users.password_hash.
|
||||||
|
func Hash(password string) (string, error) {
|
||||||
|
salt := make([]byte, argonSaltLen)
|
||||||
|
if _, err := rand.Read(salt); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
sum := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||||
|
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
|
||||||
|
argonMemory, argonTime, argonThreads,
|
||||||
|
base64.RawStdEncoding.EncodeToString(salt),
|
||||||
|
base64.RawStdEncoding.EncodeToString(sum),
|
||||||
|
), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify сравнивает пароль с PHC-строкой. При битой строке возвращает false, не панику.
|
||||||
|
func (h *Hasher) Verify(encoded, password string) bool {
|
||||||
|
if encoded == "" {
|
||||||
|
encoded = h.dummy
|
||||||
|
}
|
||||||
|
ok, err := verify(encoded, password)
|
||||||
|
if err != nil {
|
||||||
|
// Всё равно тратим время dummy-проверки, чтобы ветка ошибки не была мгновенной.
|
||||||
|
_, _ = verify(h.dummy, password)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Burn тратит время проверки, когда пользователя нет. Результат всегда false.
|
||||||
|
func (h *Hasher) Burn(password string) {
|
||||||
|
_, _ = verify(h.dummy, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
func verify(encoded, password string) (bool, error) {
|
||||||
|
parts := strings.Split(encoded, "$")
|
||||||
|
// ["", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash]
|
||||||
|
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
|
||||||
|
return false, fmt.Errorf("bad hash")
|
||||||
|
}
|
||||||
|
var memory uint32
|
||||||
|
var timeCost uint32
|
||||||
|
var threads uint8
|
||||||
|
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if memory != argonMemory || timeCost != argonTime || threads != argonThreads {
|
||||||
|
return false, fmt.Errorf("unexpected argon2 parameters")
|
||||||
|
}
|
||||||
|
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
got := argon2.IDKey([]byte(password), salt, timeCost, memory, threads, uint32(len(want)))
|
||||||
|
// ConstantTimeCompare не даёт выйти на первом несовпавшем байте.
|
||||||
|
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomPassword() string {
|
||||||
|
buf := make([]byte, 24)
|
||||||
|
_, _ = rand.Read(buf)
|
||||||
|
return base64.RawStdEncoding.EncodeToString(buf)
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// Package config читает настройки процесса из окружения.
|
||||||
|
//
|
||||||
|
// Прямые URL (DATABASE_URL, REDIS_URL) удобны в Compose.
|
||||||
|
// Вариант *_FILE из .env.example нужен, если секрет смонтирован файлом:
|
||||||
|
// тогда в переменной лежит путь, а не сам секрет.
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config — всё, что процесс обязан знать до открытия соединений.
|
||||||
|
type Config struct {
|
||||||
|
Host string
|
||||||
|
Port int
|
||||||
|
Env string
|
||||||
|
DatabaseURL string
|
||||||
|
RedisURL string
|
||||||
|
SessionTTL time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load собирает Config. Пустой URL без файла — ошибка запуска, а не тихий дефолт на чужой хост.
|
||||||
|
func Load() (Config, error) {
|
||||||
|
cfg := Config{
|
||||||
|
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||||
|
Env: getenv("APP_ENV", "lab"),
|
||||||
|
}
|
||||||
|
port, err := strconv.Atoi(getenv("APP_PORT", "8080"))
|
||||||
|
if err != nil || port < 1 || port > 65535 {
|
||||||
|
return cfg, fmt.Errorf("invalid APP_PORT")
|
||||||
|
}
|
||||||
|
cfg.Port = port
|
||||||
|
|
||||||
|
ttlSec, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
if err != nil || ttlSec < 1 || ttlSec > 7*24*3600 {
|
||||||
|
return cfg, fmt.Errorf("invalid SESSION_TTL_SECONDS")
|
||||||
|
}
|
||||||
|
cfg.SessionTTL = time.Duration(ttlSec) * time.Second
|
||||||
|
|
||||||
|
cfg.DatabaseURL, err = getenvOrFile("DATABASE_URL", "DATABASE_URL_FILE")
|
||||||
|
if err != nil {
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
cfg.RedisURL, err = getenvOrFile("REDIS_URL", "CACHE_URL_FILE")
|
||||||
|
if err != nil {
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Addr — адрес Listen, обычно 0.0.0.0:8080 внутри контейнера.
|
||||||
|
func (c Config) Addr() string {
|
||||||
|
return fmt.Sprintf("%s:%d", c.Host, c.Port)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getenv(key, fallback string) string {
|
||||||
|
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func getenvOrFile(directKey, fileKey string) (string, error) {
|
||||||
|
if v := strings.TrimSpace(os.Getenv(directKey)); v != "" {
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
path := strings.TrimSpace(os.Getenv(fileKey))
|
||||||
|
if path == "" {
|
||||||
|
return "", fmt.Errorf("set %s or %s", directKey, fileKey)
|
||||||
|
}
|
||||||
|
b, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("read %s: %w", fileKey, err)
|
||||||
|
}
|
||||||
|
v := strings.TrimSpace(string(b))
|
||||||
|
if v == "" {
|
||||||
|
return "", fmt.Errorf("%s is empty", fileKey)
|
||||||
|
}
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
// Package session хранит opaque Bearer-сессии в Redis.
|
||||||
|
//
|
||||||
|
// PostgreSQL остаётся источником истины для пользователей и сообщений.
|
||||||
|
// Сессия — отдельная роль: случайный токен, срок жизни SESSION_TTL_SECONDS и отзыв.
|
||||||
|
// В Redis лежит не сам токен, а его SHA-256: дамп AOF не содержит значение,
|
||||||
|
// которое клиент предъявляет в Authorization.
|
||||||
|
//
|
||||||
|
// TTL ключа равен оставшемуся сроку сессии. Рестарт API его не продлевает.
|
||||||
|
// Рестарт Redis сессию сохраняет только потому, что включён AOF на volume.
|
||||||
|
package session
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUnauthorized = errors.New("unauthorized")
|
||||||
|
ErrUnavailable = errors.New("unavailable")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Store — клиент Redis с короткими таймаутами.
|
||||||
|
type Store struct {
|
||||||
|
client *redis.Client
|
||||||
|
ttl time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open разбирает redis:// URL. Пароль в лог не пишется.
|
||||||
|
func Open(redisURL string, ttl time.Duration) (*Store, error) {
|
||||||
|
opt, err := redis.ParseURL(redisURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||||
|
}
|
||||||
|
opt.DialTimeout = 500 * time.Millisecond
|
||||||
|
opt.ReadTimeout = 500 * time.Millisecond
|
||||||
|
opt.WriteTimeout = 500 * time.Millisecond
|
||||||
|
opt.PoolSize = 20
|
||||||
|
client := redis.NewClient(opt)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := client.Ping(ctx).Err(); err != nil {
|
||||||
|
_ = client.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Store{client: client, ttl: ttl}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close закрывает пул при остановке процесса.
|
||||||
|
func (s *Store) Close() error {
|
||||||
|
return s.client.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ping — готовность кэша сессий. Недоступный Redis не означает «анонимный доступ».
|
||||||
|
func (s *Store) Ping(ctx context.Context) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||||
|
return ErrUnavailable
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Issue выпускает 256 бит случайности (32 байта) и кладёт сессию с TTL.
|
||||||
|
// Наружу уходит hex (64 символа). В Redis — только хеш.
|
||||||
|
func (s *Store) Issue(ctx context.Context, userID uuid.UUID) (token string, expiresAt time.Time, err error) {
|
||||||
|
buf := make([]byte, 32)
|
||||||
|
if _, err = rand.Read(buf); err != nil {
|
||||||
|
return "", time.Time{}, err
|
||||||
|
}
|
||||||
|
token = hex.EncodeToString(buf)
|
||||||
|
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Millisecond)
|
||||||
|
value := userID.String() + "|" + expiresAt.Format(time.RFC3339Nano)
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err = s.client.Set(ctx, key(token), value, time.Until(expiresAt)).Err(); err != nil {
|
||||||
|
return "", time.Time{}, ErrUnavailable
|
||||||
|
}
|
||||||
|
return token, expiresAt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup возвращает владельца живой сессии.
|
||||||
|
// Промах и истёкший срок — ErrUnauthorized. Сбой Redis — ErrUnavailable (HTTP 503).
|
||||||
|
func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||||
|
defer cancel()
|
||||||
|
raw, err := s.client.Get(ctx, key(token)).Result()
|
||||||
|
if errors.Is(err, redis.Nil) {
|
||||||
|
return uuid.Nil, ErrUnauthorized
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, ErrUnavailable
|
||||||
|
}
|
||||||
|
userPart, expPart, ok := strings.Cut(raw, "|")
|
||||||
|
if !ok {
|
||||||
|
return uuid.Nil, ErrUnauthorized
|
||||||
|
}
|
||||||
|
exp, err := time.Parse(time.RFC3339Nano, expPart)
|
||||||
|
if err != nil || !exp.After(time.Now()) {
|
||||||
|
_ = s.client.Del(ctx, key(token)).Err()
|
||||||
|
return uuid.Nil, ErrUnauthorized
|
||||||
|
}
|
||||||
|
id, err := uuid.Parse(userPart)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, ErrUnauthorized
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke удаляет текущую сессию. Повторный отзыв — это уже отсутствие ключа.
|
||||||
|
func (s *Store) Revoke(ctx context.Context, token string) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||||
|
defer cancel()
|
||||||
|
n, err := s.client.Del(ctx, key(token)).Result()
|
||||||
|
if err != nil {
|
||||||
|
return ErrUnavailable
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return ErrUnauthorized
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func key(token string) string {
|
||||||
|
sum := sha256.Sum256([]byte(token))
|
||||||
|
return "sess:" + hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"embed"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed migrations/*.sql
|
||||||
|
var migrationFS embed.FS
|
||||||
|
|
||||||
|
// Migrate применяет встроенные SQL-файлы по одному разу.
|
||||||
|
// Повторный старт процесса не создаёт вторую копию строк: версия пишется в schema_migrations.
|
||||||
|
func (s *Store) Migrate(ctx context.Context) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := s.pool.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version text PRIMARY KEY,
|
||||||
|
applied_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
)`); err != nil {
|
||||||
|
return fmt.Errorf("schema_migrations: %w", err)
|
||||||
|
}
|
||||||
|
entries, err := migrationFS.ReadDir("migrations")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
names := make([]string, 0, len(entries))
|
||||||
|
for _, e := range entries {
|
||||||
|
if !e.IsDir() && strings.HasSuffix(e.Name(), ".sql") {
|
||||||
|
names = append(names, e.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
for _, name := range names {
|
||||||
|
var exists bool
|
||||||
|
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&exists); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
body, err := migrationFS.ReadFile("migrations/" + name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tx, err := s.pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// pgx в extended protocol не выполняет несколько команд одним Exec.
|
||||||
|
for _, stmt := range splitSQL(string(body)) {
|
||||||
|
if _, err := tx.Exec(ctx, stmt); err != nil {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
return fmt.Errorf("migrate %s: %w", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitSQL делит файл миграции по ';'. В этих файлах нет строк с точкой с запятой внутри литералов.
|
||||||
|
func splitSQL(body string) []string {
|
||||||
|
parts := strings.Split(body, ";")
|
||||||
|
out := make([]string, 0, len(parts))
|
||||||
|
for _, part := range parts {
|
||||||
|
stmt := strings.TrimSpace(part)
|
||||||
|
if stmt == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, stmt)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
-- Схема lab2. PostgreSQL — источник истины для пользователей, чатов и сообщений.
|
||||||
|
-- Сессии здесь намеренно нет: их держит Redis с AOF, TTL не продлевается рестартом API.
|
||||||
|
-- Повторный запуск безопасен: все объекты создаются через IF NOT EXISTS.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version text PRIMARY KEY,
|
||||||
|
applied_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
username text NOT NULL,
|
||||||
|
display_name text NOT NULL,
|
||||||
|
-- Argon2id PHC-строка. Не SHA-256 и не plaintext. Наружу не отдаётся.
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL,
|
||||||
|
CONSTRAINT users_username_unique UNIQUE (username)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS chats (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
title text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Составной первичный ключ не даёт вставить участника дважды.
|
||||||
|
-- Внешние ключи не дают сослаться на несуществующего пользователя или чат.
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_members (
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||||
|
user_id uuid NOT NULL REFERENCES users (id),
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Список чатов пользователя начинается с фильтра «где я участник».
|
||||||
|
CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members (user_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||||
|
sender_id uuid NOT NULL REFERENCES users (id),
|
||||||
|
text text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Keyset истории: WHERE chat_id = ? AND (created_at, id) > (?, ?) ORDER BY created_at, id.
|
||||||
|
-- Составной индекс покрывает и фильтр, и порядок. Слабый индекс только по chat_id
|
||||||
|
-- заставил бы сортировать историю чата. Его нет в продовой схеме, он появляется
|
||||||
|
-- лишь на время эксперимента трека 2.
|
||||||
|
CREATE INDEX IF NOT EXISTS messages_history_idx ON messages (chat_id, created_at, id);
|
||||||
@@ -0,0 +1,497 @@
|
|||||||
|
// Package store — пользователи, чаты и сообщения в PostgreSQL.
|
||||||
|
//
|
||||||
|
// Источник истины lab2 — только эти таблицы. Память процесса после рестарта пуста,
|
||||||
|
// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2):
|
||||||
|
// текст сообщения не склеивается в SQL.
|
||||||
|
//
|
||||||
|
// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе
|
||||||
|
// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка
|
||||||
|
// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке).
|
||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"gavrilenko-sxdees/lab2/internal/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
const queryTimeout = 3 * time.Second
|
||||||
|
|
||||||
|
// Ошибки домена. HTTP-слой переводит их в коды контракта и не показывает SQL.
|
||||||
|
var (
|
||||||
|
ErrConflict = errors.New("conflict")
|
||||||
|
ErrNotFound = errors.New("not found")
|
||||||
|
ErrInvalidCursor = errors.New("invalid cursor")
|
||||||
|
ErrUnavailable = errors.New("unavailable")
|
||||||
|
)
|
||||||
|
|
||||||
|
// User — публичные поля пользователя. Hash пароля в эту структуру не попадает.
|
||||||
|
type User struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
Username string
|
||||||
|
DisplayName string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chat — чат и явный состав участников.
|
||||||
|
type Chat struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
Title string
|
||||||
|
MemberIDs []uuid.UUID
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Message — одно подтверждённое сообщение. sender_id назначает сервер.
|
||||||
|
type Message struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
ChatID uuid.UUID
|
||||||
|
SenderID uuid.UUID
|
||||||
|
Text string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api.
|
||||||
|
type PageCursor struct {
|
||||||
|
CreatedAt time.Time
|
||||||
|
ID uuid.UUID
|
||||||
|
Scope string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store — пул соединений. Пул ограничен, у каждого запроса свой таймаут.
|
||||||
|
type Store struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
hasher *auth.Hasher
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open поднимает пул. ConnectTimeout короткий, чтобы недоступная БД быстро стала 503,
|
||||||
|
// а не висела до клиентского таймаута теста.
|
||||||
|
func Open(ctx context.Context, databaseURL string, hasher *auth.Hasher) (*Store, error) {
|
||||||
|
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse database url: %w", err)
|
||||||
|
}
|
||||||
|
cfg.MaxConns = 10
|
||||||
|
cfg.MinConns = 1
|
||||||
|
cfg.MaxConnLifetime = 30 * time.Minute
|
||||||
|
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||||
|
cfg.HealthCheckPeriod = 30 * time.Second
|
||||||
|
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
||||||
|
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||||
|
// UTC, чтобы timestamptz читался так же, как мы его записали.
|
||||||
|
// statement_timeout обрывает запрос, который внезапно решил сканировать всё.
|
||||||
|
_, err := conn.Exec(ctx, `SET TIME ZONE 'UTC'; SET statement_timeout = '3s'`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := pool.Ping(pingCtx); err != nil {
|
||||||
|
pool.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Store{pool: pool, hasher: hasher}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close освобождает соединения при остановке процесса.
|
||||||
|
func (s *Store) Close() {
|
||||||
|
s.pool.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ping — проверка для /health/ready. Ошибка здесь значит «не готов», не «жив».
|
||||||
|
func (s *Store) Ping(ctx context.Context) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
if err := s.pool.Ping(ctx); err != nil {
|
||||||
|
return ErrUnavailable
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateUser пишет пользователя. Повтор username → ErrConflict благодаря UNIQUE.
|
||||||
|
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
||||||
|
hash, err := auth.Hash(password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
u := &User{
|
||||||
|
ID: uuid.New(),
|
||||||
|
Username: username,
|
||||||
|
DisplayName: displayName,
|
||||||
|
CreatedAt: nowUTC(),
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
_, err = s.pool.Exec(ctx, `
|
||||||
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)`,
|
||||||
|
u.ID, u.Username, u.DisplayName, hash, u.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
return u, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authenticate проверяет Basic-логин. Нет пользователя и неверный пароль
|
||||||
|
// выглядят одинаково: оба дают false без отдельной ошибки «такого логина нет».
|
||||||
|
func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var u User
|
||||||
|
var hash string
|
||||||
|
err := s.pool.QueryRow(ctx, `
|
||||||
|
SELECT id, username, display_name, created_at, password_hash
|
||||||
|
FROM users WHERE username = $1`, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
s.hasher.Burn(password)
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
if !s.hasher.Verify(hash, password) {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
return &u, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUser нужен, чтобы ответ /users/me совпал с объектом из регистрации.
|
||||||
|
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var u User
|
||||||
|
err := s.pool.QueryRow(ctx, `
|
||||||
|
SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id).
|
||||||
|
Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
return &u, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateChat атомарно создаёт чат и состав. Неизвестный участник откатывает всё:
|
||||||
|
// в таблице chats не остаётся «пустой» строки без полного состава.
|
||||||
|
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (*Chat, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
tx, err := s.pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
defer func() { _ = tx.Rollback(ctx) }()
|
||||||
|
|
||||||
|
chat := &Chat{
|
||||||
|
ID: uuid.New(),
|
||||||
|
Title: title,
|
||||||
|
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
|
||||||
|
CreatedAt: nowUTC(),
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||||
|
chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
for _, uid := range memberIDs {
|
||||||
|
// INSERT ... SELECT вставит 0 строк, если пользователя нет, и не нарушит FK.
|
||||||
|
tag, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO chat_members (chat_id, user_id)
|
||||||
|
SELECT $1, id FROM users WHERE id = $2`, chat.ID, uid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
if tag.RowsAffected() != 1 {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
return chat, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetChat возвращает чат только участнику. Чужому — ErrNotFound (HTTP 404, не 403).
|
||||||
|
func (s *Store) GetChat(ctx context.Context, chatID, userID uuid.UUID) (*Chat, error) {
|
||||||
|
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return s.loadChat(ctx, chatID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListChats — keyset по (created_at, id) только среди чатов этого пользователя.
|
||||||
|
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, after *PageCursor) ([]Chat, *PageCursor, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var (
|
||||||
|
rows pgx.Rows
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if after == nil {
|
||||||
|
rows, err = s.pool.Query(ctx, `
|
||||||
|
SELECT c.id, c.title, c.created_at
|
||||||
|
FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
|
WHERE m.user_id = $1
|
||||||
|
ORDER BY c.created_at, c.id
|
||||||
|
LIMIT $2`, userID, limit+1)
|
||||||
|
} else {
|
||||||
|
rows, err = s.pool.Query(ctx, `
|
||||||
|
SELECT c.id, c.title, c.created_at
|
||||||
|
FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
|
WHERE m.user_id = $1
|
||||||
|
AND (c.created_at, c.id) > ($2, $3)
|
||||||
|
ORDER BY c.created_at, c.id
|
||||||
|
LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var items []Chat
|
||||||
|
for rows.Next() {
|
||||||
|
var c Chat
|
||||||
|
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||||
|
return nil, nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
items = append(items, c)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
next, items := trimPage(items, limit, func(c Chat) (time.Time, uuid.UUID) {
|
||||||
|
return c.CreatedAt, c.ID
|
||||||
|
})
|
||||||
|
for i := range items {
|
||||||
|
members, err := s.memberIDs(ctx, items[i].ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
items[i].MemberIDs = members
|
||||||
|
}
|
||||||
|
var cursor *PageCursor
|
||||||
|
if next {
|
||||||
|
last := items[len(items)-1]
|
||||||
|
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||||
|
}
|
||||||
|
return items, cursor, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateMessage пишет сообщение только если отправитель состоит в чате.
|
||||||
|
// Подтверждение — это COMMIT строки. Следующее чтение видит её без кэша истории.
|
||||||
|
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (*Message, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
msg := &Message{
|
||||||
|
ID: uuid.New(),
|
||||||
|
ChatID: chatID,
|
||||||
|
SenderID: senderID,
|
||||||
|
Text: text,
|
||||||
|
CreatedAt: nowUTC(),
|
||||||
|
}
|
||||||
|
tag, err := s.pool.Exec(ctx, `
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT $1, $2, $3, $4, $5
|
||||||
|
WHERE EXISTS (
|
||||||
|
SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3
|
||||||
|
)`, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
if tag.RowsAffected() != 1 {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
return msg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListMessages — keyset по индексу messages_history_idx. Берём limit+1 строку,
|
||||||
|
// чтобы next_cursor был null, когда следующей записи уже нет.
|
||||||
|
func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limit int, after *PageCursor) ([]Message, *PageCursor, error) {
|
||||||
|
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var (
|
||||||
|
rows pgx.Rows
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if after == nil {
|
||||||
|
rows, err = s.pool.Query(ctx, `
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = $1
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT $2`, chatID, limit+1)
|
||||||
|
} else {
|
||||||
|
rows, err = s.pool.Query(ctx, `
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = $1
|
||||||
|
AND (created_at, id) > ($2, $3)
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []Message
|
||||||
|
for rows.Next() {
|
||||||
|
var m Message
|
||||||
|
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||||
|
return nil, nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
items = append(items, m)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) {
|
||||||
|
return m.CreatedAt, m.ID
|
||||||
|
})
|
||||||
|
var cursor *PageCursor
|
||||||
|
if hasNext {
|
||||||
|
last := items[len(items)-1]
|
||||||
|
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||||
|
}
|
||||||
|
return items, cursor, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatExistsForTitle помогает тесту отката: после ошибки создания чата строки нет.
|
||||||
|
func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var n int
|
||||||
|
err := s.pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&n)
|
||||||
|
if err != nil {
|
||||||
|
return 0, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ensureMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var one int
|
||||||
|
err := s.pool.QueryRow(ctx, `
|
||||||
|
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&one)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return mapWriteErr(err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) loadChat(ctx context.Context, chatID uuid.UUID) (*Chat, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var c Chat
|
||||||
|
err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, chatID).
|
||||||
|
Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
c.MemberIDs, err = s.memberIDs(ctx, chatID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) memberIDs(ctx context.Context, chatID uuid.UUID) ([]uuid.UUID, error) {
|
||||||
|
rows, err := s.pool.Query(ctx, `
|
||||||
|
SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id`, chatID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var ids []uuid.UUID
|
||||||
|
for rows.Next() {
|
||||||
|
var id uuid.UUID
|
||||||
|
if err := rows.Scan(&id); err != nil {
|
||||||
|
return nil, mapWriteErr(err)
|
||||||
|
}
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
return ids, mapWriteErr(rows.Err())
|
||||||
|
}
|
||||||
|
|
||||||
|
func trimPage[T any](items []T, limit int, _ func(T) (time.Time, uuid.UUID)) (bool, []T) {
|
||||||
|
if len(items) > limit {
|
||||||
|
return true, items[:limit]
|
||||||
|
}
|
||||||
|
return false, items
|
||||||
|
}
|
||||||
|
|
||||||
|
func nowUTC() time.Time {
|
||||||
|
// Миллисекунда — точность, которую мы же и печатаем в JSON.
|
||||||
|
return time.Now().UTC().Truncate(time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mapWriteErr(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||||
|
return ErrConflict
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.DeadlineExceeded) || isConn(err) {
|
||||||
|
return ErrUnavailable
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func isConn(err error) bool {
|
||||||
|
msg := err.Error()
|
||||||
|
// Не логируем и не возвращаем клиенту эту строку. Здесь только классификация.
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, pgx.ErrNoRows):
|
||||||
|
return false
|
||||||
|
default:
|
||||||
|
if stringsContains(msg, "connection refused") ||
|
||||||
|
stringsContains(msg, "failed to connect") ||
|
||||||
|
stringsContains(msg, "conn closed") ||
|
||||||
|
stringsContains(msg, "closed pool") ||
|
||||||
|
stringsContains(msg, "broken pipe") ||
|
||||||
|
stringsContains(msg, "connection reset") ||
|
||||||
|
stringsContains(msg, "SQLSTATE 57P01") ||
|
||||||
|
stringsContains(msg, "SQLSTATE 08006") ||
|
||||||
|
stringsContains(msg, "SQLSTATE 08001") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func stringsContains(s, sub string) bool {
|
||||||
|
return len(s) >= len(sub) && (s == sub || len(sub) == 0 ||
|
||||||
|
(func() bool { return contains(s, sub) })())
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(s, sub string) bool {
|
||||||
|
for i := 0; i+len(sub) <= len(s); i++ {
|
||||||
|
if s[i:i+len(sub)] == sub {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Перезапуск API и обоих хранилищ без удаления volumes и без повторного seed.
|
||||||
|
# Важно: нужен именно restart сервиса api, а не up -d: у уже работающего контейнера
|
||||||
|
# up -d --no-build не меняет PID/StartedAt, и persistence-проверка это замечает.
|
||||||
|
set -eu
|
||||||
|
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||||
|
cd "$ROOT"
|
||||||
|
docker compose --env-file .env restart postgres redis api
|
||||||
Executable
+18
@@ -0,0 +1,18 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Поднять локальный стенд lab2 из корня репозитория.
|
||||||
|
set -eu
|
||||||
|
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||||
|
cd "$ROOT"
|
||||||
|
test -f .env || cp -n .env.example .env
|
||||||
|
docker compose --env-file .env config --quiet
|
||||||
|
docker compose --env-file .env up -d --build
|
||||||
|
echo "ждём http://127.0.0.1:8080/health/ready …"
|
||||||
|
for i in $(seq 1 60); do
|
||||||
|
if curl -sf http://127.0.0.1:8080/health/ready >/dev/null; then
|
||||||
|
echo "ready"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
echo "timeout waiting for ready" >&2
|
||||||
|
exit 1
|
||||||
@@ -0,0 +1,536 @@
|
|||||||
|
// Собственные проверки lab2. Им нужен уже поднятый PostgreSQL и Redis
|
||||||
|
// (docker compose up), потому что контракт требует настоящую БД, а не sqlmock.
|
||||||
|
//
|
||||||
|
// Каждый тест пишет в лог, что именно проверяет и какой статус получил.
|
||||||
|
package studenttests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"gavrilenko-sxdees/lab2/internal/api"
|
||||||
|
"gavrilenko-sxdees/lab2/internal/auth"
|
||||||
|
"gavrilenko-sxdees/lab2/internal/session"
|
||||||
|
"gavrilenko-sxdees/lab2/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
sharedStore *store.Store
|
||||||
|
sharedSessions *session.Store
|
||||||
|
sharedRedisURL string
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
ctx := context.Background()
|
||||||
|
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||||||
|
sharedRedisURL = getenv("REDIS_URL", "redis://127.0.0.1:6379/0")
|
||||||
|
hasher, err := auth.NewHasher()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "hasher:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
sharedStore, err = store.Open(ctx, dsn, hasher)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "postgres:", err)
|
||||||
|
fmt.Fprintln(os.Stderr, "подсказка: docker compose --env-file .env up -d --build")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
defer sharedStore.Close()
|
||||||
|
if err := sharedStore.Migrate(ctx); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "migrate:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
// Повтор миграции не должен падать и не должен дублировать данные.
|
||||||
|
if err := sharedStore.Migrate(ctx); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "migrate second:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
sharedSessions, err = session.Open(sharedRedisURL, time.Hour)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "redis:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
defer sharedSessions.Close()
|
||||||
|
os.Exit(m.Run())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMalformedJSONAndValidation(t *testing.T) {
|
||||||
|
srv := newAPI(t, time.Hour)
|
||||||
|
defer srv.Close()
|
||||||
|
logStep(t, "битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат")
|
||||||
|
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, "{")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusBadRequest || !strings.Contains(body, "invalid_request") {
|
||||||
|
t.Fatalf("malformed json: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
status, body = do(t, srv, http.MethodPost, "/api/v1/users", nil,
|
||||||
|
`{"username":"abc","display_name":"Имя","password":"correct-horse-1","extra":1}`)
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusBadRequest {
|
||||||
|
t.Fatalf("extra field: status=%d", status)
|
||||||
|
}
|
||||||
|
|
||||||
|
user := register(t, srv, "ok_user")
|
||||||
|
token := login(t, srv, user.username, user.password)
|
||||||
|
chat := createChat(t, srv, token, user.id, "Чат проверки")
|
||||||
|
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||||
|
|
||||||
|
// Decoder.More() это не ловит: один объект декодируется, лишняя скобка остаётся.
|
||||||
|
for _, raw := range []string{`{"text":"valid"}}`, `{"text":"valid"}]`} {
|
||||||
|
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, raw)
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusBadRequest {
|
||||||
|
t.Fatalf("trailing garbage %q: status=%d body=%s", raw, status, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":" "}`)
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusBadRequest {
|
||||||
|
t.Fatalf("blank message: status=%d", status)
|
||||||
|
}
|
||||||
|
|
||||||
|
outsider := register(t, srv, "outsider")
|
||||||
|
outTok := login(t, srv, outsider.username, outsider.password)
|
||||||
|
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{"Authorization": "Bearer " + outTok}, `{"text":"чужое"}`)
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusNotFound {
|
||||||
|
t.Fatalf("foreign chat: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
logOK(t, "валидация JSON, хвоста, пустого текста и чужого чата")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMessageTextPreservedAndLengthOnOriginal(t *testing.T) {
|
||||||
|
srv := newAPI(t, time.Hour)
|
||||||
|
defer srv.Close()
|
||||||
|
logStep(t, "пробелы по краям сохраняются; длина считается по исходному тексту")
|
||||||
|
user := register(t, srv, "text_user")
|
||||||
|
token := login(t, srv, user.username, user.password)
|
||||||
|
chat := createChat(t, srv, token, user.id, "Текст")
|
||||||
|
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||||
|
|
||||||
|
original := " строка\nс пробелами "
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||||||
|
fmt.Sprintf(`{"text":%q}`, original))
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusCreated {
|
||||||
|
t.Fatalf("preserve spaces: status=%d", status)
|
||||||
|
}
|
||||||
|
got := decode(t, body)
|
||||||
|
if got["text"] != original {
|
||||||
|
t.Fatalf("text mutated: got %q want %q", got["text"], original)
|
||||||
|
}
|
||||||
|
|
||||||
|
tooLong := " " + strings.Repeat("a", 4000) // 4001 code points
|
||||||
|
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||||||
|
fmt.Sprintf(`{"text":%q}`, tooLong))
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusBadRequest {
|
||||||
|
t.Fatalf("length after trim bypass: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
logOK(t, "текст сохранён целиком, обход лимита через TrimSpace закрыт")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionRejectsJSONBody(t *testing.T) {
|
||||||
|
srv := newAPI(t, time.Hour)
|
||||||
|
defer srv.Close()
|
||||||
|
logStep(t, "POST /auth/sessions с телом должен быть 400 даже при верном Basic")
|
||||||
|
user := register(t, srv, "body_user")
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||||
|
"Authorization": "Basic " + basic(user.username, user.password),
|
||||||
|
}, `{"extra":1}`)
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusBadRequest {
|
||||||
|
t.Fatalf("session with body: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
logOK(t, "вход без JSON body")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrongPasswordLogoutAndIgnoredUserHeader(t *testing.T) {
|
||||||
|
srv := newAPI(t, time.Hour)
|
||||||
|
defer srv.Close()
|
||||||
|
logStep(t, "неверный пароль, Basic на бизнес-методе, X-User-Id, logout")
|
||||||
|
user := register(t, srv, "auth_user")
|
||||||
|
other := register(t, srv, "auth_other")
|
||||||
|
|
||||||
|
status, body, hdr := doRaw(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||||
|
"Authorization": "Basic " + basic(user.username, "wrong-password-1"),
|
||||||
|
}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Basic") {
|
||||||
|
t.Fatalf("wrong password: status=%d www=%q", status, hdr.Get("WWW-Authenticate"))
|
||||||
|
}
|
||||||
|
|
||||||
|
token := login(t, srv, user.username, user.password)
|
||||||
|
status, body, hdr = doRaw(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||||
|
"Authorization": "Basic " + basic(user.username, user.password),
|
||||||
|
}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Bearer") {
|
||||||
|
t.Fatalf("basic on business endpoint: status=%d www=%q", status, hdr.Get("WWW-Authenticate"))
|
||||||
|
}
|
||||||
|
|
||||||
|
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"X-User-Id": user.id}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("X-User-Id alone: status=%d", status)
|
||||||
|
}
|
||||||
|
|
||||||
|
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||||
|
"Authorization": "Bearer " + token,
|
||||||
|
"X-User-Id": other.id,
|
||||||
|
}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusOK || !strings.Contains(body, user.id) || strings.Contains(body, other.id) {
|
||||||
|
t.Fatalf("X-User-Id overrode bearer: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||||
|
t.Logf("logout status=%d", status)
|
||||||
|
if status != http.StatusNoContent {
|
||||||
|
t.Fatalf("logout status=%d", status)
|
||||||
|
}
|
||||||
|
status, _ = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||||
|
if status != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("token still valid after logout: %d", status)
|
||||||
|
}
|
||||||
|
status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||||
|
if status != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("second logout status=%d", status)
|
||||||
|
}
|
||||||
|
logOK(t, "пароль, заголовки и отзыв сессии")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionExpiry(t *testing.T) {
|
||||||
|
srv := newAPI(t, 2*time.Second)
|
||||||
|
defer srv.Close()
|
||||||
|
logStep(t, "SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается")
|
||||||
|
user := register(t, srv, "ttl_user")
|
||||||
|
token := login(t, srv, user.username, user.password)
|
||||||
|
time.Sleep(2500 * time.Millisecond)
|
||||||
|
status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expired token status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
logOK(t, "истёкшая сессия отклонена")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDuplicateUsernameRace(t *testing.T) {
|
||||||
|
srv := newAPI(t, time.Hour)
|
||||||
|
defer srv.Close()
|
||||||
|
name := "race_" + uuid.NewString()[:8]
|
||||||
|
logStep(t, "8 параллельных регистраций username="+name)
|
||||||
|
const n = 8
|
||||||
|
codes := make([]int, n)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
body := fmt.Sprintf(`{"username":%q,"display_name":"Гонка","password":"correct-horse-1"}`, name)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(i int) {
|
||||||
|
defer wg.Done()
|
||||||
|
status, _ := do(t, srv, http.MethodPost, "/api/v1/users", nil, body)
|
||||||
|
codes[i] = status
|
||||||
|
}(i)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
ok, conflict := 0, 0
|
||||||
|
for _, c := range codes {
|
||||||
|
switch c {
|
||||||
|
case http.StatusCreated:
|
||||||
|
ok++
|
||||||
|
case http.StatusConflict:
|
||||||
|
conflict++
|
||||||
|
default:
|
||||||
|
t.Errorf("unexpected status %d", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("created=%d conflict=%d", ok, conflict)
|
||||||
|
if ok != 1 || conflict != n-1 {
|
||||||
|
t.Fatalf("race result created=%d conflict=%d", ok, conflict)
|
||||||
|
}
|
||||||
|
logOK(t, "UNIQUE username выдержал гонку")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChatCreateRollsBack(t *testing.T) {
|
||||||
|
srv := newAPI(t, time.Hour)
|
||||||
|
defer srv.Close()
|
||||||
|
user := register(t, srv, "roll_user")
|
||||||
|
token := login(t, srv, user.username, user.password)
|
||||||
|
title := "rollback-" + uuid.NewString()
|
||||||
|
missing := uuid.NewString()
|
||||||
|
logStep(t, "создание чата с несуществующим участником должно откатиться, title="+title)
|
||||||
|
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q,%q]}`, title, user.id, missing)
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusBadRequest {
|
||||||
|
t.Fatalf("status=%d", status)
|
||||||
|
}
|
||||||
|
n, err := sharedStore.CountChatsByTitle(context.Background(), title)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Logf("строк chats с этим title после ошибки: %d", n)
|
||||||
|
if n != 0 {
|
||||||
|
t.Fatalf("chat row survived rollback: %d", n)
|
||||||
|
}
|
||||||
|
logOK(t, "транзакция создания чата откатилась")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPaginationPages(t *testing.T) {
|
||||||
|
srv := newAPI(t, time.Hour)
|
||||||
|
defer srv.Close()
|
||||||
|
logStep(t, "три сообщения, две страницы limit=2, затем последняя")
|
||||||
|
user := register(t, srv, "page_user")
|
||||||
|
token := login(t, srv, user.username, user.password)
|
||||||
|
chat := createChat(t, srv, token, user.id, "Страницы")
|
||||||
|
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||||
|
for _, text := range []string{"раз", "два", "три"} {
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, fmt.Sprintf(`{"text":%q}`, text))
|
||||||
|
if status != http.StatusCreated {
|
||||||
|
t.Fatalf("post message %s: %d %s", text, status, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
status, body := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2", auth, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
page := decode(t, body)
|
||||||
|
items, _ := page["items"].([]any)
|
||||||
|
if status != http.StatusOK || len(items) != 2 || page["next_cursor"] == nil {
|
||||||
|
t.Fatalf("page1: %+v", page)
|
||||||
|
}
|
||||||
|
cursor, _ := page["next_cursor"].(string)
|
||||||
|
status, body = do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2&cursor="+cursor, auth, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
page = decode(t, body)
|
||||||
|
items, _ = page["items"].([]any)
|
||||||
|
if len(items) != 1 || page["next_cursor"] != nil {
|
||||||
|
t.Fatalf("page2: %+v", page)
|
||||||
|
}
|
||||||
|
logOK(t, "keyset обошёл историю без зависания cursor")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRedisDownIsNotAnonymous(t *testing.T) {
|
||||||
|
logStep(t, "закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима")
|
||||||
|
closed, err := session.Open(sharedRedisURL, time.Hour)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := closed.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
srv := httptest.NewServer(api.New(sharedStore, closed).Handler())
|
||||||
|
defer srv.Close()
|
||||||
|
regSrv := newAPI(t, time.Hour)
|
||||||
|
defer regSrv.Close()
|
||||||
|
user := register(t, regSrv, "redis_down")
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||||
|
"Authorization": "Basic " + basic(user.username, user.password),
|
||||||
|
}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusServiceUnavailable {
|
||||||
|
t.Fatalf("login with dead redis: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||||
|
"Authorization": "Bearer " + strings.Repeat("ab", 32),
|
||||||
|
}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusServiceUnavailable {
|
||||||
|
t.Fatalf("bearer with dead redis: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
logOK(t, "сбой Redis не стал анонимным доступом")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostgresDownIsNotAnonymous(t *testing.T) {
|
||||||
|
logStep(t, "закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя")
|
||||||
|
regSrv := newAPI(t, time.Hour)
|
||||||
|
defer regSrv.Close()
|
||||||
|
user := register(t, regSrv, "pg_down")
|
||||||
|
token := login(t, regSrv, user.username, user.password)
|
||||||
|
|
||||||
|
hasher, err := auth.NewHasher()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||||||
|
broken, err := store.Open(context.Background(), dsn, hasher)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
broken.Close()
|
||||||
|
sessions, err := session.Open(sharedRedisURL, time.Hour)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = sessions.Close() })
|
||||||
|
srv := httptest.NewServer(api.New(broken, sessions).Handler())
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusServiceUnavailable {
|
||||||
|
t.Fatalf("ready with dead postgres: %d", status)
|
||||||
|
}
|
||||||
|
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||||
|
"Authorization": "Bearer " + token,
|
||||||
|
}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusServiceUnavailable || strings.Contains(body, `"username"`) {
|
||||||
|
t.Fatalf("me with dead postgres: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
status, body = do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||||
|
"Authorization": "Basic " + basic(user.username, user.password),
|
||||||
|
}, "")
|
||||||
|
logResult(t, status, body)
|
||||||
|
if status != http.StatusServiceUnavailable {
|
||||||
|
t.Fatalf("login with dead postgres: status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
logOK(t, "сбой PostgreSQL не стал анонимным доступом")
|
||||||
|
}
|
||||||
|
|
||||||
|
type account struct {
|
||||||
|
id string
|
||||||
|
username string
|
||||||
|
password string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAPI(t *testing.T, ttl time.Duration) *httptest.Server {
|
||||||
|
t.Helper()
|
||||||
|
sessions, err := session.Open(sharedRedisURL, ttl)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = sessions.Close() })
|
||||||
|
return httptest.NewServer(api.New(sharedStore, sessions).Handler())
|
||||||
|
}
|
||||||
|
|
||||||
|
func register(t *testing.T, srv *httptest.Server, prefix string) account {
|
||||||
|
t.Helper()
|
||||||
|
username := prefix + "_" + uuid.NewString()[:8]
|
||||||
|
password := "correct-horse-1"
|
||||||
|
raw := fmt.Sprintf(`{"username":%q,"display_name":"Студент","password":%q}`, username, password)
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, raw)
|
||||||
|
if status != http.StatusCreated {
|
||||||
|
t.Fatalf("register %s: %d %s", username, status, body)
|
||||||
|
}
|
||||||
|
var u struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(body), &u); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Logf("создан %s id=%s", username, u.ID)
|
||||||
|
return account{id: u.ID, username: username, password: password}
|
||||||
|
}
|
||||||
|
|
||||||
|
func login(t *testing.T, srv *httptest.Server, username, password string) string {
|
||||||
|
t.Helper()
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||||
|
"Authorization": "Basic " + basic(username, password),
|
||||||
|
}, "")
|
||||||
|
if status != http.StatusCreated {
|
||||||
|
t.Fatalf("login %s: %d %s", username, status, body)
|
||||||
|
}
|
||||||
|
var s struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(body), &s); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(s.Token) < 32 {
|
||||||
|
t.Fatalf("token too short: %d", len(s.Token))
|
||||||
|
}
|
||||||
|
t.Logf("сессия выпущена, длина токена=%d (значение не печатаем)", len(s.Token))
|
||||||
|
return s.Token
|
||||||
|
}
|
||||||
|
|
||||||
|
func createChat(t *testing.T, srv *httptest.Server, token, userID, title string) string {
|
||||||
|
t.Helper()
|
||||||
|
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q]}`, title, userID)
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||||||
|
if status != http.StatusCreated {
|
||||||
|
t.Fatalf("chat: %d %s", status, body)
|
||||||
|
}
|
||||||
|
var c struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(body), &c); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return c.ID
|
||||||
|
}
|
||||||
|
|
||||||
|
func do(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string) {
|
||||||
|
t.Helper()
|
||||||
|
status, body, _ := doRaw(t, srv, method, path, headers, raw)
|
||||||
|
return status, body
|
||||||
|
}
|
||||||
|
|
||||||
|
func doRaw(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string, http.Header) {
|
||||||
|
t.Helper()
|
||||||
|
var rdr io.Reader
|
||||||
|
if raw != "" {
|
||||||
|
rdr = bytes.NewBufferString(raw)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest(method, srv.URL+path, rdr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if raw != "" && method != http.MethodGet {
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
for k, v := range headers {
|
||||||
|
req.Header.Set(k, v)
|
||||||
|
}
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
b, _ := io.ReadAll(resp.Body)
|
||||||
|
return resp.StatusCode, string(b), resp.Header
|
||||||
|
}
|
||||||
|
|
||||||
|
func decode(t *testing.T, body string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
var m map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(body), &m); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
func basic(user, pass string) string {
|
||||||
|
return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logStep(t *testing.T, msg string) { t.Helper(); t.Logf("→ %s", msg) }
|
||||||
|
func logOK(t *testing.T, msg string) { t.Helper(); t.Logf("✓ %s", msg) }
|
||||||
|
func logResult(t *testing.T, status int, body string) {
|
||||||
|
t.Helper()
|
||||||
|
if len(body) > 400 {
|
||||||
|
body = body[:400] + "..."
|
||||||
|
}
|
||||||
|
t.Logf("status=%d body=%s", status, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getenv(k, def string) string {
|
||||||
|
if v := os.Getenv(k); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return def
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package studenttests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestMessagesHistoryIndexExplain — keyset по истории на ≥10 000 сообщений
|
||||||
|
// должен идти по индексу messages_history_idx, а не Seq Scan всей таблицы.
|
||||||
|
func TestMessagesHistoryIndexExplain(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||||||
|
pool, err := pgxpool.New(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
chatID := uuid.New()
|
||||||
|
userID := uuid.New()
|
||||||
|
tag := uuid.NewString()[:8]
|
||||||
|
now := time.Now().UTC().Truncate(time.Millisecond)
|
||||||
|
|
||||||
|
tx, err := pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer func() { _ = tx.Rollback(ctx) }()
|
||||||
|
|
||||||
|
hash := "$argon2id$v=19$m=19456,t=2,p=1$dummy$dummy"
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||||
|
VALUES ($1, $2, 'Explain', $3, $4)`,
|
||||||
|
userID, "explain_"+tag, hash, now); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||||
|
chatID, "EXPLAIN bench", now); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`,
|
||||||
|
chatID, userID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = 10001
|
||||||
|
logStep(t, fmt.Sprintf("вставка %d сообщений в один чат", total))
|
||||||
|
batch := &pgx.Batch{}
|
||||||
|
for i := 0; i < total; i++ {
|
||||||
|
ts := now.Add(time.Duration(i) * time.Millisecond)
|
||||||
|
batch.Queue(`
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)`,
|
||||||
|
uuid.New(), chatID, userID, fmt.Sprintf("m-%d", i), ts)
|
||||||
|
if batch.Len() >= 200 || i == total-1 {
|
||||||
|
br := tx.SendBatch(ctx, batch)
|
||||||
|
for j := 0; j < batch.Len(); j++ {
|
||||||
|
if _, err := br.Exec(); err != nil {
|
||||||
|
br.Close()
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := br.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
batch = &pgx.Batch{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var curAt time.Time
|
||||||
|
var curID uuid.UUID
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
SELECT created_at, id FROM messages
|
||||||
|
WHERE chat_id = $1 ORDER BY created_at, id OFFSET 5000 LIMIT 1`, chatID).
|
||||||
|
Scan(&curAt, &curID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var planJSON []byte
|
||||||
|
err = pool.QueryRow(ctx, `
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||||
|
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 51`, chatID, curAt, curID).Scan(&planJSON)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
flat := strings.ToLower(string(planJSON))
|
||||||
|
t.Logf("EXPLAIN plan: %s", string(planJSON))
|
||||||
|
if strings.Contains(flat, "seq scan on messages") {
|
||||||
|
t.Fatalf("unexpected seq scan on messages")
|
||||||
|
}
|
||||||
|
if !strings.Contains(flat, "messages_history_idx") {
|
||||||
|
t.Fatalf("messages_history_idx not in plan")
|
||||||
|
}
|
||||||
|
var parsed []map[string]any
|
||||||
|
if err := json.Unmarshal(planJSON, &parsed); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(parsed) == 0 {
|
||||||
|
t.Fatal("empty explain")
|
||||||
|
}
|
||||||
|
logOK(t, "индекс истории подтверждён EXPLAIN на 10001 сообщении")
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user