Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe52c2a99f | ||
|
|
9fabf8dff3 | ||
|
|
09b4b1d49d | ||
|
|
158fed100c | ||
|
|
10b5842be3 | ||
|
|
4455850c6a |
+32
-5
@@ -1,11 +1,38 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# Compose uses these values for interpolation in compose.yaml.
|
||||
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_DB=messenger
|
||||
|
||||
# Used only by the optional recovery profile during Track 2 verification.
|
||||
POSTGRES_RESTORE_DB=messenger_restore_admin
|
||||
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
|
||||
# File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
|
||||
DB_MAX_CONNS=10
|
||||
DB_MIN_CONNS=2
|
||||
DB_MAX_CONN_LIFETIME=30m
|
||||
DB_MAX_CONN_IDLE_TIME=5m
|
||||
DB_HEALTH_CHECK_PERIOD=30s
|
||||
DB_CONNECT_TIMEOUT=5s
|
||||
DB_QUERY_TIMEOUT=3s
|
||||
|
||||
READINESS_TIMEOUT=2s
|
||||
SHUTDOWN_TIMEOUT=10s
|
||||
|
||||
# Redis stores a disposable cache; PostgreSQL remains the source of truth.
|
||||
CACHE_URL=redis://redis:6379/0
|
||||
CACHE_TTL=5m
|
||||
CACHE_OPERATION_TIMEOUT=250ms
|
||||
CACHE_POOL_SIZE=10
|
||||
|
||||
# Optional Redis Insight profile binds its UI only to localhost.
|
||||
REDIS_INSIGHT_PORT=5540
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS builder
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
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="-w -s" -o /build/server ./cmd/server/main.go
|
||||
|
||||
FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
|
||||
|
||||
RUN addgroup -g 1000 appgroup && \
|
||||
adduser -u 1000 -G appgroup -s /bin/sh -D appuser
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /build/server /app/server
|
||||
|
||||
RUN chown -R appuser:appgroup /app
|
||||
|
||||
USER appuser:appgroup
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=10 \
|
||||
CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1
|
||||
|
||||
|
||||
ENTRYPOINT ["/app/server"]
|
||||
@@ -1,13 +1,109 @@
|
||||
GO ?= go
|
||||
PYTHON ?= python3
|
||||
COMPOSE ?= docker compose
|
||||
|
||||
ENV_FILE ?= .env
|
||||
BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
COMPOSE_CMD = $(COMPOSE) --env-file "$(ENV_FILE)"
|
||||
|
||||
.PHONY: \
|
||||
help \
|
||||
init-env \
|
||||
fmt \
|
||||
fmt-check \
|
||||
build \
|
||||
go-test \
|
||||
go-race \
|
||||
go-vet \
|
||||
go-check \
|
||||
check \
|
||||
validate \
|
||||
test \
|
||||
load \
|
||||
test-persistence \
|
||||
test-level4-transactions \
|
||||
test-session-security \
|
||||
test-cache-fallback \
|
||||
test-database-failure \
|
||||
explain-history \
|
||||
test-level4 \
|
||||
test-track2 \
|
||||
test-level5 \
|
||||
compose-config \
|
||||
compose-build \
|
||||
compose-up \
|
||||
compose-tools-up \
|
||||
compose-down \
|
||||
compose-ps \
|
||||
compose-logs
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "init-env: create local .env from .env.example if missing"
|
||||
@echo "fmt: format Go source files"
|
||||
@echo "fmt-check: report unformatted Go source files"
|
||||
@echo "build: compile the API"
|
||||
@echo "go-test: run Go tests"
|
||||
@echo "go-race: run Go tests with race detector"
|
||||
@echo "go-vet: run static Go analysis"
|
||||
@echo "go-check: run formatting, tests, race detector and vet"
|
||||
@echo "check: run offline skeleton checks"
|
||||
@echo "validate: validate the OpenAPI contract"
|
||||
@echo "test: run public smoke test against a running API"
|
||||
@echo "load: run synthetic load against a running API"
|
||||
@echo "test-persistence: run persistence test with ACTION_SCRIPT"
|
||||
@echo "test-level4-transactions: verify username race and chat rollback"
|
||||
@echo "test-session-security: verify short TTL, wrong password and logout"
|
||||
@echo "test-cache-fallback: verify API fallback while Redis is stopped"
|
||||
@echo "test-database-failure: verify bounded errors while PostgreSQL is stopped"
|
||||
@echo "explain-history: run EXPLAIN on a rolled-back 10000-message fixture"
|
||||
@echo "test-level4: run the complete cumulative level 4 verification"
|
||||
@echo "test-track2: benchmark 100000 messages and verify backup/restore"
|
||||
@echo "test-level5: run cumulative level 4 checks and Track 2"
|
||||
@echo "compose-config: validate resolved Compose configuration"
|
||||
@echo "compose-build: build application images"
|
||||
@echo "compose-up: start the stack"
|
||||
@echo "compose-tools-up: start optional Redis Insight"
|
||||
@echo "compose-down: stop the stack without deleting volumes"
|
||||
@echo "compose-ps: show stack containers"
|
||||
@echo "compose-logs: follow stack logs"
|
||||
|
||||
init-env:
|
||||
@if [ -f "$(ENV_FILE)" ]; then \
|
||||
echo "$(ENV_FILE) already exists; leaving it unchanged"; \
|
||||
else \
|
||||
cp .env.example "$(ENV_FILE)"; \
|
||||
echo "Created $(ENV_FILE) from .env.example"; \
|
||||
fi
|
||||
|
||||
fmt:
|
||||
$(GO) fmt ./...
|
||||
|
||||
fmt-check:
|
||||
@files="$$(find cmd internal student_tests -type f -name '*.go' -print)"; \
|
||||
unformatted="$$(gofmt -l $$files)"; \
|
||||
if [ -n "$$unformatted" ]; then \
|
||||
echo "Unformatted Go files:"; \
|
||||
echo "$$unformatted"; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
build:
|
||||
$(GO) build ./cmd/server
|
||||
|
||||
go-test:
|
||||
$(GO) test ./...
|
||||
|
||||
go-race:
|
||||
$(GO) test -race ./...
|
||||
|
||||
go-vet:
|
||||
$(GO) vet ./...
|
||||
|
||||
go-check: fmt-check go-test go-race go-vet
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -22,5 +118,80 @@ load:
|
||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
@test -n "$(ACTION_SCRIPT)" || \
|
||||
(echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py \
|
||||
--mode persistence \
|
||||
--action-script "$(ACTION_SCRIPT)" \
|
||||
--base-url "$(BASE_URL)" \
|
||||
$(TLS_ARGS)
|
||||
|
||||
test-level4-transactions:
|
||||
$(PYTHON) tests/level4_transactions.py \
|
||||
--base-url "$(BASE_URL)" \
|
||||
$(TLS_ARGS)
|
||||
|
||||
test-session-security:
|
||||
$(PYTHON) tests/session_security.py \
|
||||
--action-script "scripts/session_ttl.sh" \
|
||||
--ttl-seconds 2 \
|
||||
--base-url "$(BASE_URL)" \
|
||||
$(TLS_ARGS)
|
||||
|
||||
test-cache-fallback:
|
||||
$(PYTHON) tests/cache_resilience.py \
|
||||
--action-script "scripts/redis_outage.sh" \
|
||||
--base-url "$(BASE_URL)" \
|
||||
$(TLS_ARGS)
|
||||
|
||||
test-database-failure:
|
||||
$(PYTHON) tests/database_resilience.py \
|
||||
--action-script "scripts/postgres_outage.sh" \
|
||||
--base-url "$(BASE_URL)" \
|
||||
$(TLS_ARGS)
|
||||
|
||||
explain-history:
|
||||
scripts/explain_history.sh
|
||||
|
||||
test-level4:
|
||||
$(MAKE) go-check
|
||||
$(MAKE) check
|
||||
$(MAKE) validate
|
||||
$(MAKE) compose-config
|
||||
$(MAKE) test
|
||||
$(MAKE) test-level4-transactions
|
||||
$(MAKE) test-session-security
|
||||
$(MAKE) test-cache-fallback
|
||||
$(MAKE) test-database-failure
|
||||
$(MAKE) test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
$(MAKE) explain-history
|
||||
|
||||
test-track2:
|
||||
scripts/run_track2.sh
|
||||
|
||||
test-level5:
|
||||
$(MAKE) test-level4
|
||||
$(MAKE) test-track2
|
||||
|
||||
compose-config:
|
||||
@test -f "$(ENV_FILE)" || \
|
||||
(echo "$(ENV_FILE) is missing; run: make init-env"; exit 2)
|
||||
$(COMPOSE_CMD) config --quiet
|
||||
|
||||
compose-build:
|
||||
$(COMPOSE_CMD) build
|
||||
|
||||
compose-up:
|
||||
$(COMPOSE_CMD) up -d --build
|
||||
|
||||
compose-tools-up:
|
||||
$(COMPOSE_CMD) --profile tools up -d redis-insight
|
||||
|
||||
compose-down:
|
||||
$(COMPOSE_CMD) down
|
||||
|
||||
compose-ps:
|
||||
$(COMPOSE_CMD) ps
|
||||
|
||||
compose-logs:
|
||||
$(COMPOSE_CMD) logs --follow
|
||||
|
||||
@@ -1,37 +1,289 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Чурилин, БВТ2301
|
||||
- Целевая оценка: 5; выбран Track 2 «План запроса и восстановление»
|
||||
- Commit/PR: уровень 3 — commit `158fed1`; уровень 4 — commit `09b4b1d`; Track 2 уровня 5 — ветка `solution/bvt2301-churilin`, итоговые ссылки указываются в MR
|
||||
- Использованные библиотеки: `pgx/v5`, `go-redis/v9`, `google/uuid`, `x/crypto/argon2`, `golang-migrate`
|
||||
- Использованные источники: документация PostgreSQL, Go, Docker Compose и Redis; при проектировании, реализации и проверке использовался ИИ-ассистент
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Проверенное окружение: Ubuntu 26.04 в WSL2, Go 1.27.1, Python 3.14.4,
|
||||
Docker Engine 29.7.2, Docker Compose 5.5.0, PostgreSQL 16.15,
|
||||
Redis 8.10.2 и Redis Insight 3.8.0.
|
||||
|
||||
Измерения уровня 4 выполнены в WSL2 на Intel Core i5-1135G7: Docker видел
|
||||
8 логических CPU и 3.724 GiB RAM. Отдельные CPU/RAM quotas для API и PostgreSQL
|
||||
в Compose не задавались, поэтому они использовали лимиты Docker Desktop/WSL;
|
||||
Redis дополнительно ограничен `maxmemory=64mb`. Перед проверками стенд ожидался
|
||||
до состояния `healthy`, отдельный искусственный прогрев для SQL-плана не
|
||||
использовался.
|
||||
|
||||
Создать локальную конфигурацию и секреты с синтетическими значениями:
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
umask 077
|
||||
|
||||
LAB_DB_PASSWORD="$(openssl rand -hex 24)"
|
||||
printf '%s\n' "$LAB_DB_PASSWORD" > secrets/postgres_password.txt
|
||||
printf 'postgresql://messenger:%s@postgres:5432/messenger?sslmode=disable\n' \
|
||||
"$LAB_DB_PASSWORD" > secrets/database_url.txt
|
||||
unset LAB_DB_PASSWORD
|
||||
|
||||
chmod 600 secrets/postgres_password.txt secrets/database_url.txt
|
||||
```
|
||||
|
||||
`.env`, `.venv/` и `secrets/` исключены из Git. PostgreSQL не публикует порт на
|
||||
host; API доступен на `http://localhost:8080`.
|
||||
|
||||
Проверить конфигурацию и запустить стенд:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build
|
||||
docker compose --env-file .env ps
|
||||
```
|
||||
|
||||
Выполнить проверки:
|
||||
|
||||
```sh
|
||||
make go-check
|
||||
make check
|
||||
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||
make validate PYTHON=.venv/bin/python
|
||||
|
||||
# Полная накопительная проверка уровня 4:
|
||||
make test-level4 PYTHON=.venv/bin/python
|
||||
|
||||
# Только исследование Track 2:
|
||||
make test-track2
|
||||
|
||||
# Полная накопительная проверка уровней 4 и 5:
|
||||
make test-level5 PYTHON=.venv/bin/python
|
||||
|
||||
# Отдельная повторная проверка идемпотентности миграций:
|
||||
docker compose run --rm migrate
|
||||
|
||||
# Необязательный web-интерфейс Redis Insight:
|
||||
make compose-tools-up
|
||||
# Открыть http://localhost:5540 и добавить redis:6379, database 0.
|
||||
```
|
||||
|
||||
Безопасная остановка сохраняет named volume:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down
|
||||
```
|
||||
|
||||
Команда ниже намеренно и необратимо удаляет локальные учебные данные; она не
|
||||
используется в persistence-сценарии:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down --volumes
|
||||
```
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```text
|
||||
HTTP client
|
||||
-> request ID / logger / recovery
|
||||
-> Basic login или Bearer authentication
|
||||
-> HTTP handler
|
||||
-> CachedRepository
|
||||
|-> Redis: необязательная копия карточки чата
|
||||
`-> PostgreSQL: источник истины и все остальные операции
|
||||
```
|
||||
|
||||
PostgreSQL является источником истины для пользователей, password hashes,
|
||||
чатов, участников, сообщений и действующих сессий. Redis содержит только
|
||||
восстанавливаемую копию карточек чатов. `MemoryStore` сохранён только для
|
||||
быстрых unit/regression-тестов и не используется production-сервером.
|
||||
|
||||
Стенд по умолчанию состоит из четырёх Compose-сервисов:
|
||||
|
||||
- `postgres` — PostgreSQL 16.15 с named volume `postgres_data`;
|
||||
- `redis` — Redis 8.10.2 без host-порта и persistence;
|
||||
- `migrate` — одноразовое применение версионированных миграций;
|
||||
- `api` — собранное из исходников Go-приложение без постоянного локального состояния.
|
||||
|
||||
Опциональный профиль `tools` запускает Redis Insight 3.8.0. Только его UI
|
||||
доступен на `127.0.0.1:5540`; сам Redis остаётся внутри Compose-сети.
|
||||
|
||||
Опциональный профиль `recovery` запускается только сценарием Track 2. Он
|
||||
поднимает второй PostgreSQL без host-порта на отдельном named volume
|
||||
`postgres_restore_data`, чтобы восстановление не могло смешаться с рабочей БД.
|
||||
|
||||
Образы закреплены одновременно версией и digest. Dockerfile использует
|
||||
multi-stage build, а runtime-процесс запускается от непривилегированного
|
||||
пользователя.
|
||||
|
||||
### Схема и транзакционные границы
|
||||
|
||||
Миграция создаёт `users`, `chats`, `chat_members`, `messages` и `sessions`.
|
||||
Ограничения PostgreSQL окончательно обеспечивают уникальность username,
|
||||
валидные длины строк, максимум 100 участников, внешние ключи и членство
|
||||
отправителя в чате.
|
||||
|
||||
Создание чата и всех строк членства выполняется одной транзакцией. После вставки
|
||||
чата участники добавляются через `INSERT ... SELECT FROM users`; отсутствие
|
||||
пользователя даёт `RowsAffected() == 0` и выход до `COMMIT`. Deferred rollback
|
||||
удаляет уже вставленный чат и предыдущие строки членства. Сообщение вставляется через
|
||||
`INSERT ... SELECT ... WHERE EXISTS`, поэтому проверка членства и вставка не
|
||||
разделены окном гонки.
|
||||
|
||||
Чаты и сообщения упорядочены по `(created_at, id)`. Keyset cursor содержит
|
||||
версию, timestamp, UUID объекта и UUID владельца запроса/чата. Запрос читает
|
||||
`limit + 1`, чтобы определить `next_cursor` без отдельного `COUNT(*)`.
|
||||
|
||||
`make explain-history` внутри откатываемой транзакции создаёт 10 000
|
||||
синтетических сообщений, выполняет `ANALYZE` и два
|
||||
`EXPLAIN (ANALYZE, BUFFERS)`. Первая страница и страница после курсора используют
|
||||
`messages_chat_created_at_id_idx`, читают из индекса только требуемые 101 строку,
|
||||
а не всю историю. Наблюдаемые времена одного запуска: 0.068 и 0.111 мс.
|
||||
|
||||
### Аутентификация и сессии
|
||||
|
||||
Регистрация требует пароль длиной 12–128 Unicode code points. Пароль хранится
|
||||
как PHC-строка Argon2id с индивидуальной случайной солью. Неизвестный username
|
||||
при login проходит фиктивную Argon2id-проверку, чтобы убрать очевидную разницу
|
||||
во времени между неизвестным пользователем и неправильным паролем.
|
||||
|
||||
`POST /api/v1/auth/sessions` принимает Basic Auth и возвращает непрозрачный
|
||||
Bearer-токен с 256 битами случайности. В PostgreSQL хранится только SHA-256
|
||||
digest токена. Сессия имеет абсолютный `expires_at`, не продлевается при
|
||||
использовании и физически удаляется при logout.
|
||||
|
||||
Остальные бизнес-endpoint принимают только Bearer. Заголовок `X-User-Id`
|
||||
игнорируется. Неизвестный или чужой чат возвращает одинаковый 404, чтобы не
|
||||
раскрывать существование объекта.
|
||||
|
||||
### Redis cache-aside
|
||||
|
||||
Ключ имеет вид `chat:v1:<chat_uuid>`, а значением является JSON с `id`,
|
||||
`title`, упорядоченным `member_ids` и `created_at`. Версия в префиксе
|
||||
позволяет сменить формат без неоднозначного чтения старых значений.
|
||||
|
||||
`POST /chats` сначала подтверждает транзакцию PostgreSQL, затем best-effort
|
||||
записывает созданный чат в Redis. `GET /chats/{id}` сначала читает Redis:
|
||||
при hit проверяет членство вызывающего пользователя по `member_ids`; при miss
|
||||
читает PostgreSQL и заполняет Redis. При сетевой ошибке Redis выполняется
|
||||
fallback в PostgreSQL без второй попытки заполнения в том же запросе.
|
||||
|
||||
Карточка и состав участников в контракте неизменяемы, поэтому отдельных
|
||||
update/delete-инвалидаций сейчас нет. TTL равен 5 минутам и ограничивает время
|
||||
жизни производной копии. Повреждённое или несовместимое значение удаляется и
|
||||
считается ошибкой кеша. Неизвестные чаты не кешируются.
|
||||
|
||||
Redis настроен с лимитом 64 MiB и `allkeys-lru`. RDB/AOF и volume намеренно
|
||||
отключены: потеря кеша допустима, а после рестарта он лениво восстанавливается
|
||||
из PostgreSQL. Сессии остаются в PostgreSQL, поэтому очистка Redis их не
|
||||
отзывает. Пул Redis ограничен 10 соединениями, timeout операции — 250 мс.
|
||||
|
||||
### Надёжность и конфигурация
|
||||
|
||||
`pgxpool` ограничен параметрами `DB_MIN_CONNS`/`DB_MAX_CONNS`; запросы,
|
||||
подключение, readiness и graceful shutdown имеют отдельные timeout. Startup
|
||||
выполняет PostgreSQL `Ping` и завершается с ошибкой, если обязательная БД
|
||||
недоступна.
|
||||
|
||||
`/health/live` проверяет жизнь HTTP-процесса. `/health/ready` проверяет
|
||||
PostgreSQL. Request ID присутствует в успешных ответах и ошибках, а logger не
|
||||
записывает body, пароль, Bearer-токен или заголовок Authorization.
|
||||
|
||||
Автоматические action hooks останавливают ровно одну зависимость и всегда
|
||||
восстанавливают её в `finally`. При отказе Redis API использует PostgreSQL. При
|
||||
отказе обязательной PostgreSQL liveness остаётся 200, readiness и запросы к БД
|
||||
возвращают ограниченный 503 `unavailable`, а запрос без Bearer отклоняется 401
|
||||
до обращения к БД. Отдельный сценарий пересоздаёт API с
|
||||
`SESSION_TTL_SECONDS=2`, проверяет expiry, неверный пароль и logout, затем
|
||||
возвращает обычное значение из `.env` (в проверенном стенде — 3600 секунд).
|
||||
|
||||
`scripts/restart.sh` перезапускает PostgreSQL и Redis, ждёт оба healthcheck и
|
||||
затем перезапускает API. PostgreSQL volume сохраняется, а Redis начинает с
|
||||
пустого кеша. Миграции при этом не выполняются заново и данные не seed-ятся.
|
||||
|
||||
### Track 2: план запроса и восстановление
|
||||
|
||||
`make test-track2` применяет настоящую миграцию к временной БД и создаёт ровно
|
||||
100 000 сообщений с распределением по трём чатам 90 000 / 9 000 / 1 000.
|
||||
Рабочая БД приложения не изменяется. Сравниваются keyset и `OFFSET 50000` на
|
||||
индексе `(chat_id, created_at, id)`, а также keyset на покрывающем индексе с
|
||||
`INCLUDE (sender_id, text)`.
|
||||
|
||||
В финальном из трёх запусков keyset на обычном индексе вернул 101 строку при 6
|
||||
buffer hits за 0.112 ms. `OFFSET` просмотрел 50 101 строку и 1 383 buffer pages
|
||||
за 6.703 ms. Покрывающий индекс дал `Index Only Scan`, 0 heap fetches, 6 buffer
|
||||
hits и 0.073 ms. При этом он вырос с 5 914 624 до 16 842 752 bytes и при
|
||||
загрузке сгенерировал 49 573 476 вместо 38 560 620 WAL bytes. Поэтому миграция
|
||||
сохраняет узкий индекс: keyset уже ограничивает работу размером страницы, а
|
||||
дополнительная write/storage cost покрытия доказана лучше, чем выигрыш одного
|
||||
локального измерения.
|
||||
|
||||
Затем custom-format backup размером 3 000 682 bytes восстановлен в новый volume
|
||||
уникального Compose-проекта. Backup занял 731 ms, весь локальный recovery вместе
|
||||
со стартом контейнера, healthcheck, restore и сверкой — 8 269 ms. Канонические
|
||||
fingerprint источника и восстановления совпали: количества всех таблиц,
|
||||
распределение сообщений, список индексов и первое/50 000-е/100 000-е сообщения.
|
||||
|
||||
Для включённого snapshot потерь не наблюдалось. Без WAL archiving/PITR коммиты
|
||||
после последнего dump теряются, поэтому операционный RPO ограничен частотой
|
||||
backup и границей snapshot. Измеренное время не является production RTO: в нём
|
||||
нет обнаружения аварии, доставки удалённого backup и переключения трафика.
|
||||
Полная методика и ограничения находятся в `docs/track2.md`.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Компиляция, unit/regression и race | `make go-check` | PASS: tests, race detector и vet | `evidence/level3.md` |
|
||||
| Структура skeleton | `make check` | PASS | `evidence/level3.md` |
|
||||
| OpenAPI 3.1 и JSON Schema | `make validate PYTHON=.venv/bin/python` | PASS | `evidence/level3.md` |
|
||||
| Compose-конфигурация | `make compose-config` | PASS | `evidence/level3.md` |
|
||||
| Публичный API smoke | `make test` | PASS: lab2 public API scenario | `evidence/level3.md` |
|
||||
| Повторный запуск миграций | `docker compose run --rm migrate` | `no change`, версия 1, `dirty=false` | `evidence/level3.md` |
|
||||
| Persistence данных и сессии | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS с прежним Bearer-токеном | `evidence/level3.md` |
|
||||
| Схема PostgreSQL | запросы к `pg_catalog` | 5 прикладных таблиц, 12 индексов, 23 ограничения | `evidence/level3.md` |
|
||||
| Защита локальных секретов | `git check-ignore` и `git ls-files` | `.env`, `.venv/`, `secrets/` игнорируются и не отслеживаются | `evidence/level3.md` |
|
||||
| Redis cache-aside и TTL | `redis-cli`, повторный GET | Ключ `chat:v1:*`, JSON-карточка, TTL около 300 с | `evidence/level4.md` |
|
||||
| Отказ Redis | `make test-cache-fallback` | PASS: readiness, Bearer-сессия, чтение и запись работают через PostgreSQL | `evidence/level4.md` |
|
||||
| Конкурентная регистрация и rollback | `make test-level4-transactions` | PASS: один 201, три 409; неуспешный чат не оставил данных | `evidence/level4.md` |
|
||||
| Короткий TTL, неверный пароль, logout | `make test-session-security` | PASS при `SESSION_TTL_SECONDS=2`; обычная конфигурация восстановлена | `evidence/level4.md` |
|
||||
| Отказ PostgreSQL | `make test-database-failure` | PASS: live=200, ready/DB=503, anonymous=401, восстановление старой сессии | `evidence/level4.md` |
|
||||
| Индекс истории | `make explain-history` | 10 000 строк; Index Scan, 101 строка, 0.068/0.111 мс | `evidence/level4.md` |
|
||||
| Redis Insight | `make compose-tools-up` и `/api/health/` | `{"status":"up"}`, UI только на localhost | `evidence/level4.md` |
|
||||
| 100 000 неравномерных сообщений | `make test-track2` | 90 000 / 9 000 / 1 000 в трёх чатах | `evidence/level5-track2.md` |
|
||||
| Сравнение запросов и индексов | `make test-track2` | keyset: 101 строка/6 buffers; OFFSET: 50 101 строка/1 383 buffers; covering: Index Only Scan | `evidence/level5-track2.md` |
|
||||
| Стоимость записи | `make test-track2` | covering: 2.85x размер индекса и +28.6% WAL | `evidence/level5-track2.md` |
|
||||
| Backup и восстановление | `make test-track2` | новый PostgreSQL volume, 100 000 сообщений, fingerprints совпали, recovery 8.269 с | `evidence/level5-track2.md` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Повторное применение мигратора | Схема и данные не дублируются | `no change`, migration version 1, `dirty=false` | Без простоя API; потерь нет |
|
||||
| Restart API, PostgreSQL и Redis | Сохранить пользователей, чат, сообщение и действующую сессию; пустой кеш восстановить | Persistence test завершился PASS с прежним токеном; последующее чтение снова создало ключ | В пределах 90-секундного бюджета; потерь подтверждённых данных нет |
|
||||
| Stop Redis | Не менять readiness и не отдавать 5xx для доступных из PostgreSQL операций | Автотест подтвердил чтение старого чата, создание нового, сохранение Bearer-auth и 401 для неверного токена | Fallback GET около 254 мс при timeout 250 мс; потерь нет |
|
||||
| Stop PostgreSQL | Оставить liveness, снять readiness и не раскрывать внутренние ошибки | Автотест получил live 200, ready 503, DB-запросы 503 и anonymous 401; после start прежняя сессия снова работает | Ответы ограничены DB/readiness timeout; подтверждённые данные не потеряны |
|
||||
| API с TTL сессии 2 с | Быстро отозвать токен по времени и сохранить logout | Автотест получил 401 после 3.25 с, затем подтвердил новый login и немедленный отзыв logout | API автоматически возвращён к TTL 3600 с |
|
||||
| Логический backup → отдельное хранилище | Получить согласованный snapshot и доказать восстановление без доступа к source volume | Fingerprint всех counts, распределения, индексов и трёх выбранных сообщений совпал | Backup 731 ms; recovery 8 269 ms; snapshot без потерь, но без WAL/PITR теряются более новые коммиты |
|
||||
|
||||
Проверка выполнялась только на синтетических данных. Зафиксированные количества
|
||||
уровня 3 приведены в `evidence/level3.md`; последующие Redis-тесты добавляли
|
||||
новые синтетические строки, поэтому эти значения не выдаются за актуальный
|
||||
production-снимок.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Все обязательные критерии уровня 4 и Track 2 уровня 5 реализованы и имеют
|
||||
автоматические или воспроизводимые проверки. Это не доказывает промышленную
|
||||
отказоустойчивость, корректность при произвольных network partition или
|
||||
максимальную пропускную способность.
|
||||
- Track 2 выполнен тремя последовательными прогонами на синтетических данных.
|
||||
Он не моделирует конкурентную production-нагрузку, холодный disk cache,
|
||||
autovacuum/bloat, удалённое backup-хранилище или WAL/PITR.
|
||||
- Стенд учебный и одноузловой: он не обеспечивает HA PostgreSQL или API.
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
applicationCache "mtusi2026lab2/internal/cache"
|
||||
"mtusi2026lab2/internal/config"
|
||||
"mtusi2026lab2/internal/database"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/handlers"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("[FATAL] Invalid configuration: %v", err)
|
||||
}
|
||||
|
||||
startupContext, startupCancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
cfg.DatabaseConnectTimeout,
|
||||
)
|
||||
|
||||
databasePool, err := database.Open(startupContext, cfg)
|
||||
startupCancel()
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
|
||||
}
|
||||
defer databasePool.Close()
|
||||
|
||||
postgresStore := store.NewPostgreSQLStore(
|
||||
databasePool,
|
||||
cfg.DatabaseQueryTimeout,
|
||||
)
|
||||
|
||||
var applicationStore store.Repository = postgresStore
|
||||
|
||||
if cfg.RedisURL != "" {
|
||||
redisChatCache, cacheError := applicationCache.NewRedisChatCache(
|
||||
cfg.RedisURL,
|
||||
cfg.RedisCacheTTL,
|
||||
cfg.RedisOperationTimeout,
|
||||
cfg.RedisPoolSize,
|
||||
)
|
||||
if cacheError != nil {
|
||||
log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError)
|
||||
}
|
||||
defer func() {
|
||||
if closeError := redisChatCache.Close(); closeError != nil {
|
||||
log.Printf("[WARN] Redis client close failed: %v", closeError)
|
||||
}
|
||||
}()
|
||||
|
||||
cacheContext, cacheCancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
cfg.RedisOperationTimeout,
|
||||
)
|
||||
if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil {
|
||||
log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError)
|
||||
} else {
|
||||
log.Println("[INFO] Redis chat cache is available")
|
||||
}
|
||||
cacheCancel()
|
||||
|
||||
applicationStore = store.NewCachedRepository(
|
||||
postgresStore,
|
||||
redisChatCache,
|
||||
log.Default(),
|
||||
)
|
||||
}
|
||||
|
||||
handler := handlers.NewHandler(
|
||||
applicationStore,
|
||||
handlers.WithReadiness(
|
||||
databasePool,
|
||||
cfg.ReadinessTimeout,
|
||||
),
|
||||
handlers.WithSessionTTL(cfg.SessionTTL),
|
||||
)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("GET /health/live", handler.HealthLive)
|
||||
mux.HandleFunc("GET /health/ready", handler.HealthReady)
|
||||
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/auth/sessions",
|
||||
handler.CreateSession,
|
||||
)
|
||||
|
||||
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||
|
||||
requireAuth := func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return middleware.RequireAuth(postgresStore, next)
|
||||
}
|
||||
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/users/me",
|
||||
requireAuth(handler.GetMe),
|
||||
)
|
||||
|
||||
mux.HandleFunc(
|
||||
"DELETE /api/v1/auth/sessions/current",
|
||||
requireAuth(handler.DeleteCurrentSession),
|
||||
)
|
||||
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats",
|
||||
requireAuth(handler.CreateChat),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats",
|
||||
requireAuth(handler.ListChats),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats/{chat_id}",
|
||||
requireAuth(handler.GetChat),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats/{chat_id}/messages",
|
||||
requireAuth(handler.CreateMessage),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats/{chat_id}/messages",
|
||||
requireAuth(handler.GetMessages),
|
||||
)
|
||||
|
||||
var rootHandler http.Handler = mux
|
||||
rootHandler = middleware.Recovery(rootHandler)
|
||||
rootHandler = middleware.Logger(rootHandler)
|
||||
rootHandler = middleware.RequestID(rootHandler)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: cfg.HTTPAddress(),
|
||||
Handler: rootHandler,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
serverErrors := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Printf("[INFO] Server starting on %s", server.Addr)
|
||||
serverErrors <- server.ListenAndServe()
|
||||
}()
|
||||
|
||||
shutdownSignals := make(chan os.Signal, 1)
|
||||
signal.Notify(
|
||||
shutdownSignals,
|
||||
os.Interrupt,
|
||||
syscall.SIGTERM,
|
||||
)
|
||||
defer signal.Stop(shutdownSignals)
|
||||
|
||||
select {
|
||||
case serverError := <-serverErrors:
|
||||
if !errors.Is(serverError, http.ErrServerClosed) {
|
||||
log.Fatalf("[FATAL] Server crashed: %v", serverError)
|
||||
}
|
||||
|
||||
case signalValue := <-shutdownSignals:
|
||||
log.Printf(
|
||||
"[INFO] Signal %v received. Starting graceful shutdown...",
|
||||
signalValue,
|
||||
)
|
||||
|
||||
shutdownContext, shutdownCancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
cfg.ShutdownTimeout,
|
||||
)
|
||||
defer shutdownCancel()
|
||||
|
||||
if err := server.Shutdown(shutdownContext); err != nil {
|
||||
log.Printf(
|
||||
"[WARN] Graceful shutdown failed: %v. Forcing close.",
|
||||
err,
|
||||
)
|
||||
_ = server.Close()
|
||||
}
|
||||
|
||||
log.Println("[INFO] Server stopped gracefully.")
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets:
|
||||
- postgres_password
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD-SHELL",
|
||||
"pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}",
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0
|
||||
command:
|
||||
[
|
||||
"redis-server",
|
||||
"--save",
|
||||
"",
|
||||
"--appendonly",
|
||||
"no",
|
||||
"--maxmemory",
|
||||
"64mb",
|
||||
"--maxmemory-policy",
|
||||
"allkeys-lru",
|
||||
]
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 3s
|
||||
stop_grace_period: 10s
|
||||
restart: unless-stopped
|
||||
|
||||
migrate:
|
||||
image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7
|
||||
entrypoint: ["/bin/sh", "-ec"]
|
||||
command:
|
||||
- >
|
||||
exec migrate
|
||||
-path=/migrations
|
||||
-database="$$(cat /run/secrets/database_url)"
|
||||
up
|
||||
secrets:
|
||||
- database_url
|
||||
volumes:
|
||||
- ./migrations:/migrations:ro
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||
APP_PORT: ${APP_PORT:-8080}
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
SESSION_STORE: ${SESSION_STORE:-postgres}
|
||||
|
||||
CACHE_URL: ${CACHE_URL:-redis://redis:6379/0}
|
||||
CACHE_TTL: ${CACHE_TTL:-5m}
|
||||
CACHE_OPERATION_TIMEOUT: ${CACHE_OPERATION_TIMEOUT:-250ms}
|
||||
CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-10}
|
||||
|
||||
DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url}
|
||||
|
||||
DB_MAX_CONNS: ${DB_MAX_CONNS:-10}
|
||||
DB_MIN_CONNS: ${DB_MIN_CONNS:-2}
|
||||
DB_MAX_CONN_LIFETIME: ${DB_MAX_CONN_LIFETIME:-30m}
|
||||
DB_MAX_CONN_IDLE_TIME: ${DB_MAX_CONN_IDLE_TIME:-5m}
|
||||
DB_HEALTH_CHECK_PERIOD: ${DB_HEALTH_CHECK_PERIOD:-30s}
|
||||
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s}
|
||||
DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s}
|
||||
|
||||
READINESS_TIMEOUT: ${READINESS_TIMEOUT:-2s}
|
||||
SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10s}
|
||||
secrets:
|
||||
- database_url
|
||||
ports:
|
||||
- "${APP_PORT:-8080}:${APP_PORT:-8080}"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD-SHELL",
|
||||
"wget -qO- http://127.0.0.1:$${APP_PORT:-8080}/health/ready || exit 1",
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
stop_grace_period: 15s
|
||||
restart: unless-stopped
|
||||
|
||||
redis-insight:
|
||||
image: redis/redisinsight:3.8.0@sha256:b5e19ee240abef6edb435871b90ff8a210995422e8e018ab61c0339d318a1f84
|
||||
profiles: ["tools"]
|
||||
ports:
|
||||
- "127.0.0.1:${REDIS_INSIGHT_PORT:-5540}:5540"
|
||||
volumes:
|
||||
- redis_insight_data:/data
|
||||
depends_on:
|
||||
redis:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
postgres-restore:
|
||||
image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
|
||||
profiles: ["recovery"]
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_DB: ${POSTGRES_RESTORE_DB:-messenger_restore_admin}
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets:
|
||||
- postgres_password
|
||||
volumes:
|
||||
- postgres_restore_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD-SHELL",
|
||||
"pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_RESTORE_DB:-messenger_restore_admin}",
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
restart: "no"
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_insight_data:
|
||||
postgres_restore_data:
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password.txt
|
||||
database_url:
|
||||
file: ./secrets/database_url.txt
|
||||
@@ -0,0 +1,301 @@
|
||||
# Проект хранения данных
|
||||
|
||||
## Источники истины
|
||||
|
||||
PostgreSQL является источником истины для пользователей, чатов, участников,
|
||||
сообщений и сессий.
|
||||
|
||||
Redis используется как cache-aside кэш неизменяемых карточек чатов, но не как
|
||||
источник истины. Потеря Redis не приводит к потере данных или сессий.
|
||||
|
||||
## Redis cache-aside
|
||||
|
||||
Ключ:
|
||||
|
||||
```text
|
||||
chat:v1:<chat_uuid>
|
||||
```
|
||||
|
||||
Значение — JSON-представление `domain.Chat`: идентификатор, заголовок,
|
||||
упорядоченный список участников и время создания. TTL по умолчанию — 5 минут.
|
||||
Префикс `v1` версионирует внутренний формат независимо от HTTP API.
|
||||
|
||||
Алгоритм чтения:
|
||||
|
||||
1. Прочитать и проверить значение Redis.
|
||||
2. При hit проверить, что вызывающий пользователь есть в `member_ids`.
|
||||
3. При miss прочитать PostgreSQL и best-effort заполнить Redis.
|
||||
4. При timeout/ошибке Redis прочитать PostgreSQL и не повторять cache write в
|
||||
том же запросе.
|
||||
|
||||
Создание чата сначала полностью фиксируется транзакцией PostgreSQL, после чего
|
||||
выполняется best-effort запись в Redis. Контракт не содержит изменения
|
||||
заголовка или состава участников и удаления чата, поэтому write-инвалидация
|
||||
сейчас не требуется. TTL удаляет забытые копии, а повреждённое значение
|
||||
удаляется при чтении.
|
||||
|
||||
Redis работает без RDB/AOF и volume, с лимитом 64 MiB и `allkeys-lru`.
|
||||
Это намеренная политика для производного кэша. Readiness зависит только от
|
||||
PostgreSQL; при очистке или restart Redis данные лениво восстанавливаются.
|
||||
|
||||
## Общие решения
|
||||
|
||||
- Идентификаторы создаются приложением как UUID.
|
||||
- Время назначается PostgreSQL и хранится как `TIMESTAMPTZ`.
|
||||
- API возвращает время в UTC в формате RFC 3339.
|
||||
- Чаты и сообщения упорядочиваются по `(created_at, id)`.
|
||||
- Используется уровень изоляции `READ COMMITTED`.
|
||||
- Все SQL-запросы параметризованы и выполняются с timeout.
|
||||
- Snapshot между несколькими HTTP-запросами не гарантируется.
|
||||
|
||||
## Таблицы
|
||||
|
||||
### `users`
|
||||
|
||||
```text
|
||||
id UUID PRIMARY KEY
|
||||
username VARCHAR(32) NOT NULL UNIQUE
|
||||
display_name TEXT NOT NULL
|
||||
password_hash TEXT NOT NULL
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
```
|
||||
|
||||
Ограничения:
|
||||
|
||||
- `username` соответствует `^[a-z0-9_]{3,32}$`;
|
||||
- `display_name` содержит 1–100 символов и не состоит только из пробелов;
|
||||
- `password_hash` содержит PHC-строку Argon2id;
|
||||
- исходный пароль не хранится и не записывается в логи.
|
||||
|
||||
Уникальность `username` окончательно обеспечивает PostgreSQL. При конкурентной
|
||||
регистрации нарушение уникальности преобразуется в HTTP 409.
|
||||
|
||||
### `chats`
|
||||
|
||||
```text
|
||||
id UUID PRIMARY KEY
|
||||
title TEXT NOT NULL
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
```
|
||||
|
||||
Ограничения:
|
||||
|
||||
- `title` содержит 1–100 символов;
|
||||
- `title` не состоит только из пробелов.
|
||||
|
||||
Индекс порядка:
|
||||
|
||||
```text
|
||||
(created_at, id)
|
||||
```
|
||||
|
||||
### `chat_members`
|
||||
|
||||
```text
|
||||
chat_id UUID NOT NULL REFERENCES chats(id)
|
||||
user_id UUID NOT NULL REFERENCES users(id)
|
||||
position SMALLINT NOT NULL
|
||||
```
|
||||
|
||||
Ограничения:
|
||||
|
||||
```text
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
UNIQUE (chat_id, position)
|
||||
CHECK (position BETWEEN 0 AND 99)
|
||||
```
|
||||
|
||||
`position` сохраняет порядок `member_ids` и ограничивает число участников
|
||||
чата сотней.
|
||||
|
||||
Индекс для поиска чатов пользователя:
|
||||
|
||||
```text
|
||||
(user_id, chat_id)
|
||||
```
|
||||
|
||||
### `messages`
|
||||
|
||||
```text
|
||||
id UUID PRIMARY KEY
|
||||
chat_id UUID NOT NULL
|
||||
sender_id UUID NOT NULL
|
||||
text TEXT NOT NULL
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
```
|
||||
|
||||
Ограничения:
|
||||
|
||||
- `text` содержит 1–4000 символов;
|
||||
- `text` не состоит только из пробелов;
|
||||
- `(chat_id, sender_id)` ссылается на
|
||||
`chat_members(chat_id, user_id)`.
|
||||
|
||||
Составной внешний ключ гарантирует, что отправитель является участником чата.
|
||||
|
||||
Индекс истории:
|
||||
|
||||
```text
|
||||
(chat_id, created_at, id)
|
||||
```
|
||||
|
||||
### `sessions`
|
||||
|
||||
```text
|
||||
token_hash BYTEA PRIMARY KEY
|
||||
user_id UUID NOT NULL REFERENCES users(id)
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
```
|
||||
|
||||
Ограничения:
|
||||
|
||||
```text
|
||||
CHECK (octet_length(token_hash) = 32)
|
||||
CHECK (expires_at > created_at)
|
||||
```
|
||||
|
||||
Клиент получает непрозрачный токен с энтропией не менее 256 бит. В PostgreSQL
|
||||
хранится только его SHA-256 digest.
|
||||
|
||||
Сессия действительна, пока строка существует и `expires_at` больше текущего
|
||||
времени. Logout физически удаляет строку сессии.
|
||||
|
||||
Индекс для очистки истёкших сессий:
|
||||
|
||||
```text
|
||||
(expires_at)
|
||||
```
|
||||
|
||||
## Транзакционные границы
|
||||
|
||||
### Регистрация
|
||||
|
||||
Хеш Argon2id вычисляется до обращения к БД. Пользователь создаётся одним
|
||||
`INSERT`. Уникальное ограничение защищает от конкурентной регистрации
|
||||
одинакового `username`.
|
||||
|
||||
### Создание чата
|
||||
|
||||
Одна транзакция:
|
||||
|
||||
1. Вставить чат.
|
||||
2. Для каждого участника выполнить параметризованный
|
||||
`INSERT ... SELECT FROM users WHERE id = $2`.
|
||||
3. Проверить, что каждая команда вставила ровно одну строку.
|
||||
4. Выполнить COMMIT.
|
||||
|
||||
Если пользователя нет, `RowsAffected() == 0`: функция возвращает
|
||||
`ErrNotFound`, а deferred `ROLLBACK` удаляет уже вставленный чат и предыдущие
|
||||
membership-строки. Автотест отправляет существующего вызывающего и
|
||||
несуществующий UUID, проверяет отсутствие частичного чата, затем успешно
|
||||
создаёт другой чат через то же приложение.
|
||||
|
||||
### Отправка сообщения
|
||||
|
||||
Проверка членства и вставка сообщения выполняются согласованно. Предпочтительно
|
||||
использовать один `INSERT ... SELECT ... WHERE EXISTS`.
|
||||
|
||||
Отсутствующий и чужой чат возвращают одинаковый HTTP 404.
|
||||
|
||||
### Сессии
|
||||
|
||||
При входе приложение проверяет Argon2id, создаёт случайный токен и сохраняет
|
||||
его digest с абсолютным `expires_at`.
|
||||
|
||||
Аутентификация ищет digest токена и проверяет срок действия. Logout удаляет
|
||||
текущую сессию. После COMMIT новый запрос с этим токеном получает HTTP 401.
|
||||
|
||||
## Курсорная пагинация
|
||||
|
||||
### Сообщения
|
||||
|
||||
Курсор содержит:
|
||||
|
||||
```text
|
||||
version, created_at, message_id, chat_id
|
||||
```
|
||||
|
||||
SQL-граница:
|
||||
|
||||
```sql
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
```
|
||||
|
||||
### Чаты
|
||||
|
||||
Курсор содержит:
|
||||
|
||||
```text
|
||||
version, created_at, chat_id, user_id
|
||||
```
|
||||
|
||||
SQL-граница:
|
||||
|
||||
```sql
|
||||
WHERE member.user_id = $1
|
||||
AND (chat.created_at, chat.id) > ($2, $3)
|
||||
ORDER BY chat.created_at, chat.id
|
||||
LIMIT $4
|
||||
```
|
||||
|
||||
В обоих запросах передаётся `limit + 1`. Дополнительная строка определяет,
|
||||
нужно ли возвращать `next_cursor`, без отдельного `COUNT(*)`.
|
||||
|
||||
## План истории на 10 000 сообщений
|
||||
|
||||
Команда `make explain-history` открывает транзакцию, добавляет отдельные
|
||||
синтетические user/chat и ровно 10 000 сообщений, выполняет `ANALYZE`, печатает
|
||||
два `EXPLAIN (ANALYZE, BUFFERS)` и завершает всё `ROLLBACK`. Поэтому измерение
|
||||
повторяемо и не оставляет нагрузочные строки в постоянной БД.
|
||||
|
||||
Для первой страницы наблюдался план:
|
||||
|
||||
```text
|
||||
Limit (actual rows=101)
|
||||
-> Index Scan using messages_chat_created_at_id_idx
|
||||
Index Cond: (chat_id = ...)
|
||||
Buffers: shared hit=5
|
||||
Execution Time: 0.068 ms
|
||||
```
|
||||
|
||||
Для страницы после 5000-го сообщения:
|
||||
|
||||
```text
|
||||
Limit (actual rows=101)
|
||||
-> Index Scan using messages_chat_created_at_id_idx
|
||||
Index Cond: chat_id = ... AND ROW(created_at, id) > ROW(...)
|
||||
Buffers: shared hit=6
|
||||
Execution Time: 0.111 ms
|
||||
```
|
||||
|
||||
Составной индекс `(chat_id, created_at, id)` одновременно соответствует
|
||||
фильтру одного чата, tuple-границе keyset cursor и порядку выдачи. Поэтому
|
||||
PostgreSQL не делает `Seq Scan` и не сортирует всю историю для каждой страницы.
|
||||
Времена относятся только к указанному WSL2-стенду и не являются универсальным
|
||||
production-бенчмарком.
|
||||
|
||||
## Миграции
|
||||
|
||||
Первая миграция создаёт таблицы в порядке:
|
||||
|
||||
1. `users`;
|
||||
2. `chats`;
|
||||
3. `chat_members`;
|
||||
4. `messages`;
|
||||
5. `sessions`.
|
||||
|
||||
Откат удаляет таблицы в обратном порядке.
|
||||
|
||||
Применённые миграции учитываются в отдельной таблице версий. Повторный запуск
|
||||
не должен повторно создавать схему, дублировать или удалять данные.
|
||||
|
||||
Для применения используется `golang-migrate` версии `v4.20.1` как отдельный
|
||||
Compose-сервис. Миграции не запускаются автоматически каждой API-репликой.
|
||||
|
||||
Инструмент хранит текущую версию и состояние применения в служебной таблице
|
||||
`schema_migrations`. Неуспешная миграция останавливает запуск API и требует
|
||||
явного разбора причины, а не автоматического `force`.
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
# Track 2: план запроса и восстановление
|
||||
|
||||
## Цель и гипотеза
|
||||
|
||||
Эксперимент проверяет историю сообщений на реальной схеме приложения при
|
||||
неравномерной нагрузке и отдельно доказывает восстановимость логического backup.
|
||||
|
||||
Гипотезы:
|
||||
|
||||
1. Keyset-пагинация по `(chat_id, created_at, id)` должна читать число строк,
|
||||
близкое к размеру страницы, независимо от глубины истории, а `OFFSET` должен
|
||||
просматривать и отбрасывать все предыдущие строки.
|
||||
2. Покрывающий индекс с `INCLUDE (sender_id, text)` может дать `Index Only
|
||||
Scan`, но увеличит размер индекса и объём работы при записи.
|
||||
3. Custom-format `pg_dump` можно восстановить в отдельный PostgreSQL volume и
|
||||
получить те же количества и контрольные сообщения, что в snapshot источника.
|
||||
|
||||
## Повторяемая методика
|
||||
|
||||
Команда:
|
||||
|
||||
```sh
|
||||
make test-track2
|
||||
```
|
||||
|
||||
Полная накопительная проверка уровней 4 и 5:
|
||||
|
||||
```sh
|
||||
make test-level5 PYTHON=.venv/bin/python
|
||||
```
|
||||
|
||||
`scripts/run_track2.sh` создаёт временную базу в основном PostgreSQL-кластере,
|
||||
применяет настоящую миграцию `000001_initial.up.sql` и запускает
|
||||
`tests/track2_experiment.sql`. Рабочая база `messenger` не изменяется.
|
||||
|
||||
Создаются три чата и ровно 100 000 детерминированных сообщений:
|
||||
|
||||
| Чат | Сообщений | Доля |
|
||||
| --- | ---: | ---: |
|
||||
| hot | 90 000 | 90% |
|
||||
| medium | 9 000 | 9% |
|
||||
| small | 1 000 | 1% |
|
||||
|
||||
UUID, текст и время сообщений воспроизводимо выводятся из номера
|
||||
`generate_series(1, 100000)`. После каждой загрузки выполняется `VACUUM
|
||||
(ANALYZE)`. Искусственного прогрева нет; варианты выполняются последовательно
|
||||
на одном локальном стенде, поэтому абсолютное время не является production
|
||||
benchmark.
|
||||
|
||||
Сравниваются:
|
||||
|
||||
1. индекс миграции `(chat_id, created_at, id)` и keyset-запрос после позиции
|
||||
50 000;
|
||||
2. тот же индекс и запрос с `OFFSET 50000`;
|
||||
3. экспериментальный индекс `(chat_id, created_at, id) INCLUDE (sender_id,
|
||||
text)` и тот же keyset-запрос.
|
||||
|
||||
Для обоих вариантов индекса загрузка измеряется через `EXPLAIN (ANALYZE,
|
||||
BUFFERS, WAL)` на вставке всех 100 000 сообщений. Индекс второго варианта
|
||||
создаётся только во временной базе; миграция приложения не изменяется.
|
||||
|
||||
## Результаты плана чтения
|
||||
|
||||
Финальный из трёх последовательных проверочных запусков на окружении из
|
||||
`REPORT.md` дал:
|
||||
|
||||
| Вариант | План | Возвращено / просмотрено | Buffers hit | Execution Time |
|
||||
| --- | --- | ---: | ---: | ---: |
|
||||
| Обычный индекс + keyset | `Index Scan` | 101 / 101 | 6 | 0.112 ms |
|
||||
| Обычный индекс + `OFFSET 50000` | `Index Scan` | 101 / 50 101 | 1 383 | 6.703 ms |
|
||||
| Покрывающий индекс + keyset | `Index Only Scan`, `Heap Fetches: 0` | 101 / 101 | 6 | 0.073 ms |
|
||||
|
||||
`OFFSET` на этой странице просмотрел почти в 496 раз больше строк и затронул
|
||||
примерно в 230 раз больше buffer pages, чем keyset. В трёх запусках его время
|
||||
было примерно в 45–60 раз выше. Это не постоянные коэффициенты: они зависят от
|
||||
данных, кэша и железа, а стоимость `OFFSET` продолжает расти с номером страницы.
|
||||
|
||||
Покрывающий индекс после `VACUUM` действительно позволил отдать все выбранные
|
||||
поля из индекса без обращения к heap. Обычный keyset-запрос уже был быстрым,
|
||||
поэтому выигрыш одного локального измерения не оправдывает автоматическую
|
||||
замену production-индекса.
|
||||
|
||||
## Стоимость записи и хранения
|
||||
|
||||
| Вариант | INSERT 100 000 | WAL records | WAL bytes | Размер индекса |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| `(chat_id, created_at, id)` | 2 852.258 ms | 301 273 | 38 560 620 | 5 914 624 B (5 776 KiB) |
|
||||
| `... INCLUDE (sender_id, text)` | 3 086.374 ms | 302 607 | 49 573 476 | 16 842 752 B (16 MiB) |
|
||||
|
||||
Покрывающий индекс занял примерно в 2.85 раза больше места и сгенерировал
|
||||
примерно на 28.6% больше WAL. В финальном запуске вставка была на 8.2% дольше,
|
||||
но по трём последовательным запускам разница колебалась от −3.2% до +8.7%.
|
||||
Это иллюстрирует cache/order effect и не доказывает устойчивую разницу latency.
|
||||
WAL и размер надёжно показывают дополнительную стоимость; для сравнения времени
|
||||
нужны чередование вариантов и более длинная серия повторов.
|
||||
|
||||
Решение для приложения: сохранить узкий индекс миграции и keyset-пагинацию.
|
||||
Покрывающий вариант имеет смысл повторно рассмотреть только после профилирования
|
||||
реальной преимущественно читающей нагрузки.
|
||||
|
||||
## Backup, восстановление и сверка
|
||||
|
||||
После измерений временная source-база содержит настоящую схему и 100 000
|
||||
сообщений с покрывающим индексом. Скрипт:
|
||||
|
||||
1. создаёт transaction-consistent custom-format backup через `pg_dump`;
|
||||
2. запускает профиль `recovery` в уникальном Compose-проекте — отдельный
|
||||
контейнер PostgreSQL с новым named volume и без host-порта;
|
||||
3. создаёт в нём новую пустую базу и выполняет `pg_restore --exit-on-error`;
|
||||
4. строит канонический JSON fingerprint обеих баз и сравнивает его byte-for-byte;
|
||||
5. удаляет source-базу, dump, recovery-контейнер и его временный volume даже
|
||||
при ошибке.
|
||||
|
||||
Fingerprint включает количества `users`, `chats`, `chat_members`, `messages`,
|
||||
`sessions`, распределение 90 000/9 000/1 000, список индексов сообщений и полные
|
||||
идентификаторы/время/MD5 текста для первого, 50 000-го и 100 000-го сообщений.
|
||||
Raw dump создаётся во временном каталоге и не попадает в Git.
|
||||
|
||||
Наблюдаемый результат:
|
||||
|
||||
```text
|
||||
backup_bytes=3000682
|
||||
backup_ms=731
|
||||
recovery_ms=8269
|
||||
fingerprints_match=true
|
||||
PASS: Track 2 query/index and backup-to-separate-storage experiment completed.
|
||||
```
|
||||
|
||||
`recovery_ms` включает запуск отдельного контейнера до healthcheck, создание
|
||||
новой БД, `pg_restore` и fingerprint-сверку. Он не включает обнаружение аварии,
|
||||
получение backup из удалённого хранилища, переключение приложения/DNS и прогрев.
|
||||
В трёх последовательных запусках backup занимал 599–731 ms, а весь локальный
|
||||
recovery — 8 016–8 269 ms.
|
||||
|
||||
## RPO, RTO и ограничения
|
||||
|
||||
Для восстановленного snapshot наблюдаемый RPO равен нулю: все строки,
|
||||
попавшие в согласованный snapshot `pg_dump`, совпали. Это не означает нулевой
|
||||
операционный RPO. Без WAL archiving/PITR будут потеряны коммиты после начала
|
||||
последнего успешно сохранённого dump; практическая граница определяется
|
||||
интервалом backup и временем его создания.
|
||||
|
||||
Наблюдаемый локальный recovery занял 8.269 секунды, но это не production RTO.
|
||||
Данные маленькие, image уже находился локально, backup лежал на том же host, а
|
||||
проверка не моделировала повреждение host/volume или сетевую передачу. Логический
|
||||
backup удобен и переносим между совместимыми версиями PostgreSQL, однако для
|
||||
крупных баз обычно восстанавливается медленнее физического backup с WAL/PITR.
|
||||
|
||||
Эксперимент однопоточный и выполнен три раза на синтетических данных. Он не
|
||||
измеряет конкурентные чтения/записи, холодный disk cache, длительный churn,
|
||||
bloat, autovacuum, репликацию и поведение при заполненном диске.
|
||||
@@ -0,0 +1,145 @@
|
||||
# Доказательства уровня 3
|
||||
|
||||
Состояние: commit уровня 3 `158fed1` (`реализован уровень 3`).
|
||||
|
||||
## Окружение
|
||||
|
||||
```text
|
||||
Ubuntu 26.04 LTS, WSL2
|
||||
Go 1.27.1 linux/amd64
|
||||
Python 3.14.4
|
||||
Docker Engine 29.7.2
|
||||
Docker Compose 5.5.0
|
||||
PostgreSQL 16.15
|
||||
8 логических CPU
|
||||
MemTotal: 3905144 kB
|
||||
```
|
||||
|
||||
Использованы локальные синтетические пользователи и сообщения. Session tokens,
|
||||
пароли, database URL и содержимое secret-файлов в evidence не сохранялись.
|
||||
|
||||
## Статические и Go-проверки
|
||||
|
||||
```sh
|
||||
make go-check
|
||||
make check
|
||||
make validate PYTHON=.venv/bin/python
|
||||
make compose-config
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Результат:
|
||||
|
||||
```text
|
||||
go test ./... PASS
|
||||
go test -race ./... PASS
|
||||
go vet ./... PASS
|
||||
check_contract.py PASS
|
||||
validate_openapi.py PASS
|
||||
docker compose config PASS
|
||||
git diff --check PASS
|
||||
```
|
||||
|
||||
## Публичный smoke
|
||||
|
||||
```sh
|
||||
make test
|
||||
```
|
||||
|
||||
```text
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
```
|
||||
|
||||
Проверены регистрация, Basic login, Bearer authentication, запрет одного
|
||||
`X-User-Id`, защита чужого чата, создание/чтение сообщений, cursor pagination,
|
||||
ошибки входных данных и logout.
|
||||
|
||||
## Миграции
|
||||
|
||||
Повторный запуск:
|
||||
|
||||
```sh
|
||||
docker compose run --rm migrate
|
||||
```
|
||||
|
||||
```text
|
||||
no change
|
||||
```
|
||||
|
||||
Состояние `schema_migrations`:
|
||||
|
||||
```text
|
||||
version = 1
|
||||
dirty = false
|
||||
```
|
||||
|
||||
Фактически созданы прикладные таблицы `users`, `chats`, `chat_members`,
|
||||
`messages`, `sessions`, а также служебная `schema_migrations`.
|
||||
|
||||
Каталог PostgreSQL подтвердил 12 индексов и 23 ограничения, включая:
|
||||
|
||||
- `users_username_unique`;
|
||||
- `chat_members_primary_key`;
|
||||
- `chat_members_position_unique`;
|
||||
- `messages_sender_membership_foreign_key`;
|
||||
- `messages_chat_created_at_id_idx`;
|
||||
- `sessions_token_hash_length`;
|
||||
- `sessions_expiry_after_creation`;
|
||||
- `sessions_expires_at_idx`.
|
||||
|
||||
## Persistence
|
||||
|
||||
```sh
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
```
|
||||
|
||||
```text
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
```
|
||||
|
||||
В commit `158fed1` hook последовательно перезапускал `postgres`, ждал его
|
||||
healthcheck и перезапускал `api`; Redis был добавлен следующим этапом.
|
||||
`docker compose ps` после сценария показывал оба сервиса в
|
||||
состоянии `healthy`. Named volume:
|
||||
|
||||
```text
|
||||
mtusi2026lab2_postgres_data
|
||||
```
|
||||
|
||||
После повторных smoke/persistence-проверок в volume находились только
|
||||
синтетические данные:
|
||||
|
||||
```text
|
||||
users=18 chats=6 memberships=12 messages=9 sessions=15
|
||||
```
|
||||
|
||||
## Образы
|
||||
|
||||
```text
|
||||
golang:1.27.1-alpine
|
||||
sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414
|
||||
alpine:3.24
|
||||
sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
|
||||
postgres:16.15-alpine3.24
|
||||
sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
|
||||
migrate/migrate:v4.20.1
|
||||
sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7
|
||||
```
|
||||
|
||||
В Dockerfile и Compose используются ссылки `tag@digest`.
|
||||
|
||||
## Секреты и Git
|
||||
|
||||
`git check-ignore` подтвердил исключение:
|
||||
|
||||
```text
|
||||
.env
|
||||
.venv/
|
||||
secrets/postgres_password.txt
|
||||
secrets/database_url.txt
|
||||
```
|
||||
|
||||
`git ls-files` не обнаружил среди tracked-файлов `.env`, `.venv/`, `secrets/`
|
||||
или временный `CONTEXT.md`. Поиск credential-паттернов нашёл только явно
|
||||
обозначенный placeholder в `examples/requests.http`.
|
||||
@@ -0,0 +1,236 @@
|
||||
# Доказательства уровня 4
|
||||
|
||||
Состояние: полный уровень 4 в ветке `solution/bvt2301-churilin` на базе commit
|
||||
уровня 3 `158fed1`; результаты ниже получены перед публикацией изменений.
|
||||
|
||||
Все созданные пользователи, чаты и сообщения синтетические. Пароли, Bearer
|
||||
tokens, database URL и содержимое secret-файлов не сохранялись в evidence.
|
||||
|
||||
## Проверенное окружение
|
||||
|
||||
```text
|
||||
Ubuntu 26.04 LTS, WSL2, x86_64
|
||||
Intel Core i5-1135G7, 4 cores / 8 logical CPU
|
||||
Docker-visible RAM: 3.724 GiB
|
||||
Docker Engine 29.7.2, Docker Compose 5.5.0
|
||||
Go 1.27.1, Python 3.14.4
|
||||
PostgreSQL 16.15
|
||||
Redis 8.10.2, go-redis/v9 v9.23.0
|
||||
Redis Insight 3.8.0
|
||||
```
|
||||
|
||||
API и PostgreSQL не имеют отдельных Compose CPU/RAM quotas и используют лимиты
|
||||
Docker Desktop/WSL. Redis дополнительно ограничен `maxmemory=64mb`. Все
|
||||
контейнерные образы закреплены точным тегом и digest.
|
||||
|
||||
## Полная команда
|
||||
|
||||
После запуска стенда все накопительные проверки объединены целью:
|
||||
|
||||
```sh
|
||||
make test-level4 PYTHON=.venv/bin/python
|
||||
```
|
||||
|
||||
Она последовательно запускает Go tests/race/vet, offline check, OpenAPI
|
||||
validation, Compose validation, public smoke, транзакционные сценарии, короткий
|
||||
session TTL, отказ Redis, отказ PostgreSQL, полный restart и SQL EXPLAIN.
|
||||
|
||||
## Cache-aside и TTL
|
||||
|
||||
Ключ:
|
||||
|
||||
```text
|
||||
chat:v1:<chat_uuid>
|
||||
```
|
||||
|
||||
Значение — JSON `domain.Chat` с полями `id`, `title`, `member_ids` и
|
||||
`created_at`. Наблюдаемый TTL после чтения был 243 секунды из настроенных 300:
|
||||
|
||||
```text
|
||||
db0: keys=1, expires=1
|
||||
maxmemory=67108864
|
||||
maxmemory-policy=allkeys-lru
|
||||
save=""
|
||||
appendonly=no
|
||||
```
|
||||
|
||||
PostgreSQL остаётся источником истины. RDB/AOF и Redis volume намеренно
|
||||
отключены, так как потерянная карточка лениво восстанавливается из PostgreSQL.
|
||||
Unit-тесты подтверждают miss → source → fill, hit без второго source read,
|
||||
проверку членства на hit и игнорирование ошибки best-effort cache write.
|
||||
|
||||
## Отказ Redis
|
||||
|
||||
```sh
|
||||
make test-cache-fallback
|
||||
```
|
||||
|
||||
```text
|
||||
Stopping only Redis; hook output is suppressed.
|
||||
PASS: Redis outage used PostgreSQL fallback; readiness, session,
|
||||
authorization and writes remained correct.
|
||||
```
|
||||
|
||||
Сценарий прогревает карточку, останавливает только Redis, тем же Bearer-токеном
|
||||
проверяет readiness, читает существующий чат и создаёт новый. Запрос без
|
||||
корректного токена остаётся 401. После запуска Redis чтение нового чата снова
|
||||
заполняет кеш.
|
||||
|
||||
Наблюдаемые времена отдельного запуска:
|
||||
|
||||
```text
|
||||
cache hit GET: 0.84 ms
|
||||
fallback GET: 254.46 ms
|
||||
POST during outage: 254.31 ms
|
||||
first GET after recovery: 3.10 ms
|
||||
```
|
||||
|
||||
Redis timeout равен 250 ms. После сетевой ошибки чтения в том же запросе не
|
||||
выполняется вторая cache write, поэтому fallback не платит второй timeout.
|
||||
|
||||
## Конкурентная регистрация и rollback
|
||||
|
||||
```sh
|
||||
make test-level4-transactions
|
||||
```
|
||||
|
||||
```text
|
||||
PASS: concurrent username race produced one winner; failed composite chat
|
||||
creation rolled back and the connection remained usable.
|
||||
```
|
||||
|
||||
Четыре параллельных запроса регистрируют один и тот же уникальный username.
|
||||
Тест требует ровно один HTTP 201 и три HTTP 409. Решение принимает окончательное
|
||||
решение по ограничению `users_username_unique`, а не по небезопасной схеме
|
||||
check-then-insert.
|
||||
|
||||
Для rollback тест создаёт чат с существующим вызывающим и несуществующим UUID
|
||||
второго участника. Код успевает вставить строку `chats` и первого участника,
|
||||
затем получает `RowsAffected() == 0` на `INSERT ... SELECT FROM users`.
|
||||
Deferred rollback отменяет обе вставки. Чат не появляется в списке пользователя,
|
||||
а следующая составная операция через тот же API успешно завершается.
|
||||
|
||||
## Короткий expiry, неверный пароль и logout
|
||||
|
||||
```sh
|
||||
make test-session-security
|
||||
```
|
||||
|
||||
```text
|
||||
PASS: deployed short SESSION_TTL_SECONDS expired the token; wrong password
|
||||
and logout remained enforced.
|
||||
```
|
||||
|
||||
Action hook временно пересоздаёт API с `SESSION_TTL_SECONDS=2`. Автотест
|
||||
проверяет:
|
||||
|
||||
1. неправильный пароль получает 401;
|
||||
2. новый Bearer-токен сразу работает;
|
||||
3. через 3.25 секунды тот же токен получает 401;
|
||||
4. новая сессия создаётся с правильным паролем;
|
||||
5. logout возвращает 204;
|
||||
6. отозванный токен сразу получает 401.
|
||||
|
||||
Блок `finally` пересоздаёт API с обычной конфигурацией. После теста внутри
|
||||
контейнера подтверждено `SESSION_TTL_SECONDS=3600`.
|
||||
|
||||
## Отказ обязательной PostgreSQL
|
||||
|
||||
```sh
|
||||
make test-database-failure
|
||||
```
|
||||
|
||||
```text
|
||||
Stopping only PostgreSQL; hook output is suppressed.
|
||||
PASS: PostgreSQL outage returned bounded 503 responses, anonymous access
|
||||
stayed rejected, and the existing session recovered.
|
||||
```
|
||||
|
||||
Во время остановки только PostgreSQL:
|
||||
|
||||
- `/health/live` возвращает 200;
|
||||
- `/health/ready` возвращает ограниченный 503 `unavailable`;
|
||||
- запрос без Bearer отклоняется 401 до обращения к БД;
|
||||
- запрос с ранее действующим Bearer возвращает 503, а не считается доверенным;
|
||||
- запись пользователя возвращает 503 без деталей драйвера/SQL.
|
||||
|
||||
После запуска PostgreSQL существующий пул соединений восстанавливается, а
|
||||
прежний Bearer-токен снова получает исходного пользователя.
|
||||
|
||||
## План истории на 10 000 сообщений
|
||||
|
||||
```sh
|
||||
make explain-history
|
||||
```
|
||||
|
||||
Сценарий создаёт данные внутри транзакции, выполняет `ANALYZE` и в конце делает
|
||||
`ROLLBACK`. Постоянные таблицы после измерения не засоряются.
|
||||
|
||||
```text
|
||||
synthetic_message_count
|
||||
-----------------------
|
||||
10000
|
||||
```
|
||||
|
||||
Первая страница:
|
||||
|
||||
```text
|
||||
Limit (actual time=0.019..0.043 rows=101 loops=1)
|
||||
-> Index Scan using messages_chat_created_at_id_idx
|
||||
(actual time=0.018..0.037 rows=101 loops=1)
|
||||
Index Cond: (chat_id = ...)
|
||||
Buffers: shared hit=5
|
||||
Execution Time: 0.068 ms
|
||||
```
|
||||
|
||||
Страница после курсора на позиции 5000:
|
||||
|
||||
```text
|
||||
Limit (actual time=0.013..0.046 rows=101 loops=1)
|
||||
-> Index Scan using messages_chat_created_at_id_idx
|
||||
(actual time=0.012..0.040 rows=101 loops=1)
|
||||
Index Cond: chat_id = ... AND ROW(created_at, id) > ROW(...)
|
||||
Buffers: shared hit=6
|
||||
Execution Time: 0.111 ms
|
||||
```
|
||||
|
||||
Оба запроса используют индекс `(chat_id, created_at, id)`, не выполняют
|
||||
`Seq Scan` и возвращают только `limit + 1 = 101` строку. Времена относятся к
|
||||
описанному локальному стенду и не объявляются production-бенчмарком.
|
||||
|
||||
## Полный restart
|
||||
|
||||
```sh
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
```
|
||||
|
||||
```text
|
||||
PASS: persistence preserved confirmed data and existing session.
|
||||
```
|
||||
|
||||
Hook перезапускает PostgreSQL и Redis, ждёт оба healthcheck и перезапускает API.
|
||||
PostgreSQL volume сохраняет данные и сессию. Redis стартует пустым и лениво
|
||||
заполняется после следующего чтения.
|
||||
|
||||
## Redis Insight
|
||||
|
||||
```sh
|
||||
make compose-tools-up
|
||||
curl http://127.0.0.1:5540/api/health/
|
||||
```
|
||||
|
||||
```json
|
||||
{"status":"up"}
|
||||
```
|
||||
|
||||
Для ручного подключения внутри UI: host `redis`, port `6379`, database `0`,
|
||||
без TLS и пароля. Такая конфигурация допустима только для изолированного
|
||||
локального учебного стенда: Redis не публикует host-port, а UI привязан к
|
||||
`127.0.0.1`.
|
||||
|
||||
## Границы доказательства
|
||||
|
||||
Проверки подтверждают обязательные критерии уровня 4 в указанном одноузловом
|
||||
стенде. Они не доказывают HA PostgreSQL, поведение при произвольном network
|
||||
partition, максимальную пропускную способность или критерии выбранного Track 2
|
||||
уровня 5.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Доказательства уровня 5 — Track 2
|
||||
|
||||
Состояние: Track 2 «План запроса и восстановление» выполнен поверх commit уровня
|
||||
4 `09b4b1d`. Все данные синтетические; dump, credentials и токены в Git не
|
||||
сохраняются.
|
||||
|
||||
## Окружение и команда
|
||||
|
||||
Окружение совпадает с `evidence/level4.md`: Ubuntu 26.04 в WSL2, Intel Core
|
||||
i5-1135G7 (4 cores / 8 logical CPU), доступные Docker 3.724 GiB RAM, Docker
|
||||
29.7.2, Compose 5.5.0 и PostgreSQL 16.15.
|
||||
|
||||
```sh
|
||||
make test-track2
|
||||
```
|
||||
|
||||
Сценарий использует реальную миграцию в отдельной временной БД, а восстановление
|
||||
выполняет в отдельном PostgreSQL-контейнере и новом named volume уникального
|
||||
Compose-проекта. Рабочая база API не изменяется. Данные распределены по чатам
|
||||
как 90 000 / 9 000 / 1 000.
|
||||
|
||||
## Чтение и индексы
|
||||
|
||||
```text
|
||||
current index + keyset:
|
||||
Index Scan, rows=101, Buffers hit=6, Execution Time=0.112 ms
|
||||
|
||||
current index + OFFSET 50000:
|
||||
Index Scan, rows scanned=50101, Buffers hit=1383,
|
||||
Execution Time=6.703 ms
|
||||
|
||||
covering index + keyset:
|
||||
Index Only Scan, rows=101, Heap Fetches=0, Buffers hit=6,
|
||||
Execution Time=0.073 ms
|
||||
```
|
||||
|
||||
Keyset ограничивает работу размером страницы. `OFFSET` обязан пройти 50 000
|
||||
предыдущих строк. Покрывающий индекс устраняет heap fetch после `VACUUM`, но
|
||||
увеличивает стоимость хранения и записи.
|
||||
|
||||
## Стоимость записи
|
||||
|
||||
```text
|
||||
current (chat_id, created_at, id):
|
||||
100000 rows, 2852.258 ms, WAL records=301273,
|
||||
WAL bytes=38560620, index bytes=5914624
|
||||
|
||||
covering INCLUDE (sender_id, text):
|
||||
100000 rows, 3086.374 ms, WAL records=302607,
|
||||
WAL bytes=49573476, index bytes=16842752
|
||||
```
|
||||
|
||||
Покрывающий индекс оказался примерно в 2.85 раза больше и создал на 28.6%
|
||||
больше WAL. По трём последовательным запускам разница времени вставки менялась
|
||||
от −3.2% до +8.7%, поэтому latency не интерпретируется как устойчивое
|
||||
преимущество варианта; последовательный тест подвержен cache/order effect.
|
||||
|
||||
## Backup и новое хранилище
|
||||
|
||||
```text
|
||||
backup_bytes=3000682
|
||||
backup_ms=731
|
||||
recovery_ms=8269
|
||||
fingerprints_match=true
|
||||
|
||||
counts:
|
||||
users=3, chats=3, chat_members=3, messages=100000, sessions=0
|
||||
distribution:
|
||||
hot=90000, medium=9000, small=1000
|
||||
|
||||
PASS: Track 2 query/index and backup-to-separate-storage experiment completed.
|
||||
```
|
||||
|
||||
Source и restored fingerprint byte-for-byte совпали. Помимо количеств он
|
||||
проверяет распределение, индексы и первое/50 000-е/100 000-е сообщения вместе
|
||||
с UUID, временем, отправителем, чатом и MD5 текста.
|
||||
|
||||
Время recovery включает старт отдельного PostgreSQL, ожидание healthcheck,
|
||||
создание новой БД, restore и сверку. Для snapshot потерь нет. Без WAL/PITR
|
||||
коммиты после snapshot последнего dump будут потеряны, поэтому production RPO
|
||||
равен интервалу backup плюс граница snapshot, а измеренные 8.269 секунды не
|
||||
включают обнаружение аварии, загрузку удалённого backup и переключение трафика.
|
||||
|
||||
Полная методика, SQL-варианты и ограничения описаны в `docs/track2.md`.
|
||||
@@ -0,0 +1,21 @@
|
||||
module mtusi2026lab2
|
||||
|
||||
go 1.27.1
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,43 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/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.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
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=
|
||||
Vendored
+175
@@ -0,0 +1,175 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const chatKeyPrefix = "chat:v1:"
|
||||
|
||||
var ErrMiss = errors.New("cache miss")
|
||||
|
||||
// ChatCache хранит только производную копию неизменяемых данных чата.
|
||||
// PostgreSQL остаётся источником истины.
|
||||
type ChatCache interface {
|
||||
Get(ctx context.Context, chatID string) (domain.Chat, error)
|
||||
Set(ctx context.Context, chat domain.Chat) error
|
||||
}
|
||||
|
||||
type RedisChatCache struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
operationTimeout time.Duration
|
||||
}
|
||||
|
||||
func NewRedisChatCache(
|
||||
redisURL string,
|
||||
ttl time.Duration,
|
||||
operationTimeout time.Duration,
|
||||
poolSize int,
|
||||
) (*RedisChatCache, error) {
|
||||
options, err := redis.ParseURL(strings.TrimSpace(redisURL))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse Redis URL: %w", err)
|
||||
}
|
||||
|
||||
options.DialTimeout = operationTimeout
|
||||
options.ReadTimeout = operationTimeout
|
||||
options.WriteTimeout = operationTimeout
|
||||
options.PoolTimeout = operationTimeout
|
||||
options.PoolSize = poolSize
|
||||
options.MaxRetries = -1
|
||||
|
||||
return &RedisChatCache{
|
||||
client: redis.NewClient(options),
|
||||
ttl: ttl,
|
||||
operationTimeout: operationTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) Ping(ctx context.Context) error {
|
||||
operationContext, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := c.client.Ping(operationContext).Err(); err != nil {
|
||||
return fmt.Errorf("ping Redis: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) Close() error {
|
||||
return c.client.Close()
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) Get(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
) (domain.Chat, error) {
|
||||
operationContext, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
payload, err := c.client.Get(
|
||||
operationContext,
|
||||
chatKey(chatID),
|
||||
).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return domain.Chat{}, ErrMiss
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("get cached chat: %w", err)
|
||||
}
|
||||
|
||||
var chat domain.Chat
|
||||
if err = json.Unmarshal(payload, &chat); err != nil {
|
||||
c.deleteInvalidValue(operationContext, chatID)
|
||||
return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err)
|
||||
}
|
||||
|
||||
if err = validateCachedChat(chat, chatID); err != nil {
|
||||
c.deleteInvalidValue(operationContext, chatID)
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) Set(
|
||||
ctx context.Context,
|
||||
chat domain.Chat,
|
||||
) error {
|
||||
payload, err := json.Marshal(chat)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode chat for cache: %w", err)
|
||||
}
|
||||
|
||||
operationContext, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err = c.client.Set(
|
||||
operationContext,
|
||||
chatKey(chat.ID),
|
||||
payload,
|
||||
c.ttl,
|
||||
).Err(); err != nil {
|
||||
return fmt.Errorf("cache chat: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) withTimeout(
|
||||
ctx context.Context,
|
||||
) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, c.operationTimeout)
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) deleteInvalidValue(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
) {
|
||||
_ = c.client.Del(ctx, chatKey(chatID)).Err()
|
||||
}
|
||||
|
||||
func chatKey(chatID string) string {
|
||||
return chatKeyPrefix + chatID
|
||||
}
|
||||
|
||||
func validateCachedChat(chat domain.Chat, expectedID string) error {
|
||||
if chat.ID != expectedID {
|
||||
return errors.New("cached chat id does not match cache key")
|
||||
}
|
||||
if _, err := uuid.Parse(chat.ID); err != nil {
|
||||
return errors.New("cached chat contains invalid id")
|
||||
}
|
||||
if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() {
|
||||
return errors.New("cached chat is incomplete")
|
||||
}
|
||||
if len(chat.MemberIDs) == 0 {
|
||||
return errors.New("cached chat has no members")
|
||||
}
|
||||
|
||||
seenMembers := make(map[string]struct{}, len(chat.MemberIDs))
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if _, err := uuid.Parse(memberID); err != nil {
|
||||
return errors.New("cached chat contains invalid member id")
|
||||
}
|
||||
if _, exists := seenMembers[memberID]; exists {
|
||||
return errors.New("cached chat contains duplicate member id")
|
||||
}
|
||||
seenMembers[memberID] = struct{}{}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ ChatCache = (*RedisChatCache)(nil)
|
||||
@@ -0,0 +1,343 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
HTTPHost string
|
||||
HTTPPort string
|
||||
|
||||
SessionTTL time.Duration
|
||||
|
||||
DatabaseURL string
|
||||
DatabaseMaxConns int32
|
||||
DatabaseMinConns int32
|
||||
DatabaseMaxConnLifetime time.Duration
|
||||
DatabaseMaxConnIdleTime time.Duration
|
||||
DatabaseHealthCheckPeriod time.Duration
|
||||
DatabaseConnectTimeout time.Duration
|
||||
DatabaseQueryTimeout time.Duration
|
||||
|
||||
RedisURL string
|
||||
RedisCacheTTL time.Duration
|
||||
RedisOperationTimeout time.Duration
|
||||
RedisPoolSize int
|
||||
|
||||
ReadinessTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
sessionTTL, err := secondsDurationFromEnv(
|
||||
"SESSION_TTL_SECONDS",
|
||||
3600,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseURL, err := requiredValueOrFile(
|
||||
"DATABASE_URL",
|
||||
"DATABASE_URL_FILE",
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMaxConnLifetime, err := durationFromEnv(
|
||||
"DB_MAX_CONN_LIFETIME",
|
||||
30*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMaxConnIdleTime, err := durationFromEnv(
|
||||
"DB_MAX_CONN_IDLE_TIME",
|
||||
5*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseHealthCheckPeriod, err := durationFromEnv(
|
||||
"DB_HEALTH_CHECK_PERIOD",
|
||||
30*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseConnectTimeout, err := durationFromEnv(
|
||||
"DB_CONNECT_TIMEOUT",
|
||||
5*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseQueryTimeout, err := durationFromEnv(
|
||||
"DB_QUERY_TIMEOUT",
|
||||
3*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
redisCacheTTL, err := durationFromEnv(
|
||||
"CACHE_TTL",
|
||||
5*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
redisOperationTimeout, err := durationFromEnv(
|
||||
"CACHE_OPERATION_TIMEOUT",
|
||||
250*time.Millisecond,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
readinessTimeout, err := durationFromEnv(
|
||||
"READINESS_TIMEOUT",
|
||||
2*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
shutdownTimeout, err := durationFromEnv(
|
||||
"SHUTDOWN_TIMEOUT",
|
||||
10*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
if databaseMinConns > databaseMaxConns {
|
||||
return Config{}, errors.New(
|
||||
"DB_MIN_CONNS must not be greater than DB_MAX_CONNS",
|
||||
)
|
||||
}
|
||||
|
||||
return Config{
|
||||
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
|
||||
HTTPPort: envOrDefault("APP_PORT", "8080"),
|
||||
SessionTTL: sessionTTL,
|
||||
|
||||
DatabaseURL: databaseURL,
|
||||
DatabaseMaxConns: databaseMaxConns,
|
||||
DatabaseMinConns: databaseMinConns,
|
||||
DatabaseMaxConnLifetime: databaseMaxConnLifetime,
|
||||
DatabaseMaxConnIdleTime: databaseMaxConnIdleTime,
|
||||
DatabaseHealthCheckPeriod: databaseHealthCheckPeriod,
|
||||
DatabaseConnectTimeout: databaseConnectTimeout,
|
||||
DatabaseQueryTimeout: databaseQueryTimeout,
|
||||
|
||||
RedisURL: redisURL,
|
||||
RedisCacheTTL: redisCacheTTL,
|
||||
RedisOperationTimeout: redisOperationTimeout,
|
||||
RedisPoolSize: int(redisPoolSize),
|
||||
|
||||
ReadinessTimeout: readinessTimeout,
|
||||
ShutdownTimeout: shutdownTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c Config) HTTPAddress() string {
|
||||
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
|
||||
}
|
||||
|
||||
func requiredValueOrFile(valueEnv, fileEnv string) (string, error) {
|
||||
value, valueExists := os.LookupEnv(valueEnv)
|
||||
filePath, fileExists := os.LookupEnv(fileEnv)
|
||||
|
||||
if valueExists && fileExists {
|
||||
return "", fmt.Errorf(
|
||||
"%s and %s must not be set at the same time",
|
||||
valueEnv,
|
||||
fileEnv,
|
||||
)
|
||||
}
|
||||
|
||||
if valueExists {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", valueEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if fileExists {
|
||||
filePath = strings.TrimSpace(filePath)
|
||||
if filePath == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", fileEnv, err)
|
||||
}
|
||||
|
||||
value = strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv)
|
||||
}
|
||||
|
||||
func optionalValueOrFile(valueEnv, fileEnv string) (string, error) {
|
||||
value, valueExists := os.LookupEnv(valueEnv)
|
||||
filePath, fileExists := os.LookupEnv(fileEnv)
|
||||
|
||||
if valueExists && fileExists {
|
||||
return "", fmt.Errorf(
|
||||
"%s and %s must not be set at the same time",
|
||||
valueEnv,
|
||||
fileEnv,
|
||||
)
|
||||
}
|
||||
|
||||
if valueExists {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", valueEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if fileExists {
|
||||
filePath = strings.TrimSpace(filePath)
|
||||
if filePath == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", fileEnv, err)
|
||||
}
|
||||
|
||||
value = strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func envOrDefault(name, fallback string) string {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
value, err := strconv.ParseInt(raw, 10, 32)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s must be an integer: %w", name, err)
|
||||
}
|
||||
|
||||
if value < int64(minimum) {
|
||||
return 0, fmt.Errorf("%s must be at least %d", name, minimum)
|
||||
}
|
||||
|
||||
return int32(value), nil
|
||||
}
|
||||
|
||||
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
value, err := time.ParseDuration(raw)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(
|
||||
"%s must be a Go duration such as 3s or 5m: %w",
|
||||
name,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if value <= 0 {
|
||||
return 0, fmt.Errorf("%s must be positive", name)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func secondsDurationFromEnv(
|
||||
name string,
|
||||
fallbackSeconds int64,
|
||||
) (time.Duration, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
raw = strconv.FormatInt(fallbackSeconds, 10)
|
||||
}
|
||||
|
||||
seconds, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(
|
||||
"%s must be an integer number of seconds: %w",
|
||||
name,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if seconds <= 0 {
|
||||
return 0, fmt.Errorf("%s must be positive", name)
|
||||
}
|
||||
|
||||
duration, err := time.ParseDuration(raw + "s")
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s is too large: %w", name, err)
|
||||
}
|
||||
|
||||
return duration, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab2/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Open(
|
||||
ctx context.Context,
|
||||
cfg config.Config,
|
||||
) (*pgxpool.Pool, error) {
|
||||
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err)
|
||||
}
|
||||
|
||||
poolConfig.MaxConns = cfg.DatabaseMaxConns
|
||||
poolConfig.MinConns = cfg.DatabaseMinConns
|
||||
poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime
|
||||
poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime
|
||||
poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
}
|
||||
|
||||
// NewWithConfig создаёт структуру пула, но не гарантирует,
|
||||
// что PostgreSQL уже доступен. Ping обеспечивает fail-fast.
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
//регулярка по контракту
|
||||
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// страница выдачи истории сообщений
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (u *User) Validate() error {
|
||||
if !usernameRegex.MatchString(u.Username) {
|
||||
return fmt.Errorf("username must match [a-z0-9_]{3,32}")
|
||||
}
|
||||
|
||||
nameRunes := utf8.RuneCountInString(u.DisplayName)
|
||||
if nameRunes < 1 || nameRunes > 100 {
|
||||
return fmt.Errorf("display_name length must be between 1 and 100 code points")
|
||||
}
|
||||
|
||||
if strings.TrimSpace(u.DisplayName) == "" {
|
||||
return fmt.Errorf("display_name cannot be only whitespace")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateChatInput(title string, memberIDs []string, callerID string) error {
|
||||
titleRunes := utf8.RuneCountInString(title)
|
||||
if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" {
|
||||
return fmt.Errorf("invalid chat title")
|
||||
}
|
||||
|
||||
if len(memberIDs) == 0 {
|
||||
return fmt.Errorf("member_ids cannot be empty")
|
||||
}
|
||||
|
||||
if len(memberIDs) > 100 {
|
||||
return fmt.Errorf("member_ids must contain at most 100 users")
|
||||
}
|
||||
|
||||
hasCaller := false
|
||||
seen := make(map[string]bool)
|
||||
|
||||
for _, id := range memberIDs {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return fmt.Errorf("invalid member uuid: %s", id)
|
||||
}
|
||||
|
||||
if seen[id] {
|
||||
return fmt.Errorf("duplicate member_id: %s", id)
|
||||
}
|
||||
seen[id] = true
|
||||
|
||||
if id == callerID {
|
||||
hasCaller = true
|
||||
}
|
||||
}
|
||||
|
||||
if !hasCaller {
|
||||
return fmt.Errorf("caller must be in member_ids")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateMessageText(text string) error {
|
||||
textRunes := utf8.RuneCountInString(text)
|
||||
if textRunes < 1 || textRunes > 4000 {
|
||||
return fmt.Errorf("message text length must be between 1 and 4000 code points")
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return fmt.Errorf("message text cannot be only whitespace")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type CursorData struct {
|
||||
CreatedAt time.Time
|
||||
MessageID string
|
||||
ChatID string
|
||||
}
|
||||
|
||||
const messageCursorVersion = "v1"
|
||||
|
||||
func EncodeCursor(createdAt time.Time, messageID, chatID string) string {
|
||||
raw := fmt.Sprintf(
|
||||
"%s|%s|%s|%s",
|
||||
messageCursorVersion,
|
||||
createdAt.UTC().Format(time.RFC3339Nano),
|
||||
messageID,
|
||||
chatID,
|
||||
)
|
||||
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func DecodeCursor(
|
||||
cursorStr string,
|
||||
expectedChatID string,
|
||||
) (*CursorData, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursorStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid base64 cursor")
|
||||
}
|
||||
|
||||
parts := strings.Split(string(raw), "|")
|
||||
if len(parts) != 4 {
|
||||
return nil, fmt.Errorf("malformed cursor")
|
||||
}
|
||||
|
||||
if parts[0] != messageCursorVersion {
|
||||
return nil, fmt.Errorf("unsupported cursor version")
|
||||
}
|
||||
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid cursor timestamp")
|
||||
}
|
||||
|
||||
messageID := parts[2]
|
||||
chatID := parts[3]
|
||||
|
||||
if _, err := uuid.Parse(messageID); err != nil {
|
||||
return nil, fmt.Errorf("invalid cursor message_id")
|
||||
}
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
return nil, fmt.Errorf("invalid cursor chat_id")
|
||||
}
|
||||
if chatID != expectedChatID {
|
||||
return nil, fmt.Errorf("cursor belongs to another chat")
|
||||
}
|
||||
|
||||
return &CursorData{
|
||||
CreatedAt: createdAt.UTC(),
|
||||
MessageID: messageID,
|
||||
ChatID: chatID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// страница со списком чатов пользователя
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
const chatCursorVersion = "v1"
|
||||
|
||||
type ChatCursorData struct {
|
||||
CreatedAt time.Time
|
||||
ChatID string
|
||||
UserID string
|
||||
}
|
||||
|
||||
// EncodeChatCursor создаёт непрозрачную границу списка чатов.
|
||||
// Версия позволяет в будущем изменить внутренний формат курсора.
|
||||
func EncodeChatCursor(createdAt time.Time, chatID, userID string) string {
|
||||
raw := fmt.Sprintf(
|
||||
"%s|%s|%s|%s",
|
||||
chatCursorVersion,
|
||||
createdAt.UTC().Format(time.RFC3339Nano),
|
||||
chatID,
|
||||
userID,
|
||||
)
|
||||
|
||||
// RawURLEncoding не использует символы +, / и завершающий =,
|
||||
// поэтому курсор безопаснее передавать в query string.
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func DecodeChatCursor(
|
||||
cursorStr string,
|
||||
expectedUserID string,
|
||||
) (*ChatCursorData, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(cursorStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid base64 chat cursor")
|
||||
}
|
||||
|
||||
parts := strings.Split(string(decoded), "|")
|
||||
if len(parts) != 4 {
|
||||
return nil, fmt.Errorf("malformed chat cursor")
|
||||
}
|
||||
|
||||
if parts[0] != chatCursorVersion {
|
||||
return nil, fmt.Errorf("unsupported chat cursor version")
|
||||
}
|
||||
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid chat cursor timestamp")
|
||||
}
|
||||
|
||||
chatID := parts[2]
|
||||
if _, err = uuid.Parse(chatID); err != nil {
|
||||
return nil, fmt.Errorf("invalid chat cursor chat_id")
|
||||
}
|
||||
|
||||
userID := parts[3]
|
||||
if _, err = uuid.Parse(userID); err != nil {
|
||||
return nil, fmt.Errorf("invalid chat cursor user_id")
|
||||
}
|
||||
|
||||
if userID != expectedUserID {
|
||||
return nil, fmt.Errorf("chat cursor belongs to another user")
|
||||
}
|
||||
|
||||
return &ChatCursorData{
|
||||
CreatedAt: createdAt,
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory uint32 = 19 * 1024
|
||||
argonIterations uint32 = 2
|
||||
argonParallelism uint8 = 1
|
||||
argonSaltLength = 16
|
||||
argonKeyLength uint32 = 32
|
||||
|
||||
minPasswordLength = 12
|
||||
maxPasswordLength = 128
|
||||
)
|
||||
|
||||
var ErrInvalidPasswordHash = errors.New("invalid password hash")
|
||||
|
||||
func ValidatePassword(password string) error {
|
||||
if !utf8.ValidString(password) {
|
||||
return errors.New("password must be valid UTF-8")
|
||||
}
|
||||
|
||||
length := utf8.RuneCountInString(password)
|
||||
if length < minPasswordLength || length > maxPasswordLength {
|
||||
return fmt.Errorf(
|
||||
"password length must be between %d and %d code points",
|
||||
minPasswordLength,
|
||||
maxPasswordLength,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
if err := ValidatePassword(password); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
argonIterations,
|
||||
argonMemory,
|
||||
argonParallelism,
|
||||
argonKeyLength,
|
||||
)
|
||||
|
||||
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
|
||||
encoded := fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
argonMemory,
|
||||
argonIterations,
|
||||
argonParallelism,
|
||||
encodedSalt,
|
||||
encodedHash,
|
||||
)
|
||||
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func VerifyPassword(
|
||||
password string,
|
||||
encodedHash string,
|
||||
) (bool, error) {
|
||||
parameters, salt, expectedHash, err := decodePasswordHash(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
actualHash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
parameters.iterations,
|
||||
parameters.memory,
|
||||
parameters.parallelism,
|
||||
uint32(len(expectedHash)),
|
||||
)
|
||||
|
||||
matches := subtle.ConstantTimeCompare(
|
||||
actualHash,
|
||||
expectedHash,
|
||||
) == 1
|
||||
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
type argonParameters struct {
|
||||
memory uint32
|
||||
iterations uint32
|
||||
parallelism uint8
|
||||
}
|
||||
|
||||
func decodePasswordHash(
|
||||
encodedHash string,
|
||||
) (argonParameters, []byte, []byte, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 ||
|
||||
parts[0] != "" ||
|
||||
parts[1] != "argon2id" {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
if version != argon2.Version {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
var parameters argonParameters
|
||||
if _, err := fmt.Sscanf(
|
||||
parts[3],
|
||||
"m=%d,t=%d,p=%d",
|
||||
¶meters.memory,
|
||||
¶meters.iterations,
|
||||
¶meters.parallelism,
|
||||
); err != nil {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
// Ограничения не позволяют повреждённой строке из БД запросить
|
||||
// гигантский объём памяти или процессорного времени.
|
||||
if parameters.memory < 8*1024 ||
|
||||
parameters.memory > 256*1024 ||
|
||||
parameters.iterations < 1 ||
|
||||
parameters.iterations > 10 ||
|
||||
parameters.parallelism < 1 ||
|
||||
parameters.parallelism > 8 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) < 16 || len(salt) > 64 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(hash) < 16 || len(hash) > 64 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
return parameters, salt, hash, nil
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordHashAndVerify(t *testing.T) {
|
||||
password := "Correct-password-123"
|
||||
|
||||
encodedHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
if strings.Contains(encodedHash, password) {
|
||||
t.Fatal("encoded hash contains plaintext password")
|
||||
}
|
||||
|
||||
matches, err := VerifyPassword(password, encodedHash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||
}
|
||||
if !matches {
|
||||
t.Fatal("correct password did not match")
|
||||
}
|
||||
|
||||
matches, err = VerifyPassword("Wrong-password-123", encodedHash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||
}
|
||||
if matches {
|
||||
t.Fatal("wrong password matched")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashesUseDifferentSalts(t *testing.T) {
|
||||
password := "Correct-password-123"
|
||||
|
||||
firstHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("first HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
secondHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("second HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
if firstHash == secondHash {
|
||||
t.Fatal("equal passwords produced equal encoded hashes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordValidation(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
password string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "minimum length",
|
||||
password: "123456789012",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "unicode",
|
||||
password: "пароль-проверка-123",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "colon is allowed",
|
||||
password: "password:with:colon",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "too short",
|
||||
password: "short",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
err := ValidatePassword(testCase.password)
|
||||
|
||||
if testCase.wantErr && err == nil {
|
||||
t.Fatal("expected validation error")
|
||||
}
|
||||
if !testCase.wantErr && err != nil {
|
||||
t.Fatalf("unexpected validation error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedPasswordHash(t *testing.T) {
|
||||
_, err := VerifyPassword(
|
||||
"Correct-password-123",
|
||||
"not-an-argon2-hash",
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected malformed hash error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const sessionTokenBytes = 32
|
||||
|
||||
func GenerateSessionToken() (string, []byte, error) {
|
||||
randomBytes := make([]byte, sessionTokenBytes)
|
||||
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
return "", nil, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
tokenHash := HashSessionToken(token)
|
||||
|
||||
return token, tokenHash, nil
|
||||
}
|
||||
|
||||
func HashSessionToken(token string) []byte {
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
|
||||
hash := make([]byte, len(digest))
|
||||
copy(hash, digest[:])
|
||||
|
||||
return hash
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateSessionToken(t *testing.T) {
|
||||
firstToken, firstHash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||
}
|
||||
|
||||
secondToken, secondHash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||
}
|
||||
|
||||
if firstToken == secondToken {
|
||||
t.Fatal("generated session tokens are equal")
|
||||
}
|
||||
|
||||
if bytes.Equal(firstHash, secondHash) {
|
||||
t.Fatal("generated session token hashes are equal")
|
||||
}
|
||||
|
||||
if len(firstHash) != 32 {
|
||||
t.Fatalf("expected 32-byte token hash, got %d", len(firstHash))
|
||||
}
|
||||
|
||||
recalculatedHash := HashSessionToken(firstToken)
|
||||
if !bytes.Equal(firstHash, recalculatedHash) {
|
||||
t.Fatal("token hash is not reproducible")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
|
||||
applicationCache "mtusi2026lab2/internal/cache"
|
||||
"mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
// CachedRepository декорирует основной Repository. Все операции, кроме чтения
|
||||
// и создания чата, автоматически делегируются встроенному Repository.
|
||||
type CachedRepository struct {
|
||||
Repository
|
||||
chatCache applicationCache.ChatCache
|
||||
logger *log.Logger
|
||||
}
|
||||
|
||||
func NewCachedRepository(
|
||||
repository Repository,
|
||||
chatCache applicationCache.ChatCache,
|
||||
logger *log.Logger,
|
||||
) *CachedRepository {
|
||||
if logger == nil {
|
||||
logger = log.Default()
|
||||
}
|
||||
|
||||
return &CachedRepository{
|
||||
Repository: repository,
|
||||
chatCache: chatCache,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *CachedRepository) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
chat, err := r.Repository.CreateChat(ctx, title, memberIDs)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
// Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не
|
||||
// должна превращать успешную бизнес-операцию в 503.
|
||||
if err = r.chatCache.Set(ctx, chat); err != nil {
|
||||
r.logger.Printf("[WARN] Redis chat cache write failed: %v", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (r *CachedRepository) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
chat, err := r.chatCache.Get(ctx, chatID)
|
||||
if err == nil {
|
||||
if !containsMember(chat.MemberIDs, callerID) {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
shouldFillCache := errors.Is(err, applicationCache.ErrMiss)
|
||||
if !shouldFillCache {
|
||||
r.logger.Printf("[WARN] Redis chat cache read failed: %v", err)
|
||||
}
|
||||
|
||||
chat, err = r.Repository.GetChatByID(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
if shouldFillCache {
|
||||
if err = r.chatCache.Set(ctx, chat); err != nil {
|
||||
r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func containsMember(memberIDs []string, callerID string) bool {
|
||||
for _, memberID := range memberIDs {
|
||||
if memberID == callerID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var _ Repository = (*CachedRepository)(nil)
|
||||
@@ -0,0 +1,181 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"testing"
|
||||
|
||||
applicationCache "mtusi2026lab2/internal/cache"
|
||||
"mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
type fakeChatCache struct {
|
||||
chats map[string]domain.Chat
|
||||
getErr error
|
||||
setErr error
|
||||
sets int
|
||||
}
|
||||
|
||||
func (c *fakeChatCache) Get(
|
||||
_ context.Context,
|
||||
chatID string,
|
||||
) (domain.Chat, error) {
|
||||
if c.getErr != nil {
|
||||
return domain.Chat{}, c.getErr
|
||||
}
|
||||
|
||||
chat, exists := c.chats[chatID]
|
||||
if !exists {
|
||||
return domain.Chat{}, applicationCache.ErrMiss
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *fakeChatCache) Set(
|
||||
_ context.Context,
|
||||
chat domain.Chat,
|
||||
) error {
|
||||
c.sets++
|
||||
if c.setErr != nil {
|
||||
return c.setErr
|
||||
}
|
||||
c.chats[chat.ID] = chat
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type countingRepository struct {
|
||||
Repository
|
||||
getChatCalls int
|
||||
}
|
||||
|
||||
func (r *countingRepository) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
r.getChatCalls++
|
||||
return r.Repository.GetChatByID(ctx, chatID, callerID)
|
||||
}
|
||||
|
||||
func cachedRepositoryFixture(
|
||||
t *testing.T,
|
||||
) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) {
|
||||
t.Helper()
|
||||
|
||||
legacy := NewMemoryStore()
|
||||
member, err := legacy.CreateUser("cache_member", "Участник")
|
||||
if err != nil {
|
||||
t.Fatalf("create member: %v", err)
|
||||
}
|
||||
outsider, err := legacy.CreateUser("cache_outsider", "Посторонний")
|
||||
if err != nil {
|
||||
t.Fatalf("create outsider: %v", err)
|
||||
}
|
||||
chat, err := legacy.CreateChat("Кешируемый чат", []string{member.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create chat: %v", err)
|
||||
}
|
||||
|
||||
repository := &countingRepository{
|
||||
Repository: NewMemoryRepository(legacy),
|
||||
}
|
||||
chatCache := &fakeChatCache{
|
||||
chats: make(map[string]domain.Chat),
|
||||
}
|
||||
|
||||
return repository, chatCache, member, outsider, chat
|
||||
}
|
||||
|
||||
func TestCachedRepositoryMissThenHit(t *testing.T) {
|
||||
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
|
||||
cached := NewCachedRepository(
|
||||
repository,
|
||||
chatCache,
|
||||
log.New(io.Discard, "", 0),
|
||||
)
|
||||
|
||||
first, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("first read: %v", err)
|
||||
}
|
||||
second, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("second read: %v", err)
|
||||
}
|
||||
|
||||
if repository.getChatCalls != 1 {
|
||||
t.Fatalf("expected one source read, got %d", repository.getChatCalls)
|
||||
}
|
||||
if chatCache.sets != 1 {
|
||||
t.Fatalf("expected one cache fill, got %d", chatCache.sets)
|
||||
}
|
||||
if first.ID != expected.ID || second.ID != expected.ID {
|
||||
t.Fatal("cache changed chat identity")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedRepositoryFallsBackWhenCacheUnavailable(t *testing.T) {
|
||||
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
|
||||
chatCache.getErr = errors.New("redis unavailable")
|
||||
chatCache.setErr = errors.New("redis unavailable")
|
||||
cached := NewCachedRepository(
|
||||
repository,
|
||||
chatCache,
|
||||
log.New(io.Discard, "", 0),
|
||||
)
|
||||
|
||||
chat, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("fallback read: %v", err)
|
||||
}
|
||||
if chat.ID != expected.ID || repository.getChatCalls != 1 {
|
||||
t.Fatal("source repository was not used after cache failure")
|
||||
}
|
||||
if chatCache.sets != 0 {
|
||||
t.Fatal("failed cache read must not trigger another cache operation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) {
|
||||
repository, chatCache, _, outsider, expected := cachedRepositoryFixture(t)
|
||||
chatCache.chats[expected.ID] = expected
|
||||
cached := NewCachedRepository(
|
||||
repository,
|
||||
chatCache,
|
||||
log.New(io.Discard, "", 0),
|
||||
)
|
||||
|
||||
_, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound for outsider, got %v", err)
|
||||
}
|
||||
if repository.getChatCalls != 0 {
|
||||
t.Fatal("cache hit unexpectedly queried source repository")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedRepositoryIgnoresWriteFailure(t *testing.T) {
|
||||
repository, chatCache, member, _, _ := cachedRepositoryFixture(t)
|
||||
chatCache.setErr = errors.New("redis unavailable")
|
||||
cached := NewCachedRepository(
|
||||
repository,
|
||||
chatCache,
|
||||
log.New(io.Discard, "", 0),
|
||||
)
|
||||
|
||||
chat, err := cached.CreateChat(
|
||||
context.Background(),
|
||||
"Новый чат",
|
||||
[]string{member.ID},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create chat with unavailable cache: %v", err)
|
||||
}
|
||||
if chat.ID == "" || chatCache.sets != 1 {
|
||||
t.Fatal("chat was not created before best-effort cache write")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package store
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
)
|
||||
@@ -0,0 +1,345 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
usersByID map[string]domain.User //key = user UUID
|
||||
usersByUsername map[string]string //key = username для быстрой проверки уникальности
|
||||
|
||||
chatsByID map[string]domain.Chat //key = chat UUID
|
||||
|
||||
messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
usersByID: make(map[string]domain.User),
|
||||
usersByUsername: make(map[string]string),
|
||||
chatsByID: make(map[string]domain.Chat),
|
||||
messagesByChatID: make(map[string][]domain.Message),
|
||||
}
|
||||
}
|
||||
|
||||
// ---пользователи---
|
||||
|
||||
func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// дубликат username -> 409 Conflict
|
||||
if _, exists := s.usersByUsername[username]; exists {
|
||||
return domain.User{}, ErrConflict
|
||||
}
|
||||
|
||||
user := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.usersByID[user.ID] = user
|
||||
s.usersByUsername[user.Username] = user.ID
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetUserByID(id string) (domain.User, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, exists := s.usersByID[id]
|
||||
if !exists {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// ---чаты---
|
||||
|
||||
func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
//все участники рил существуют
|
||||
for _, memberID := range memberIDs {
|
||||
if _, exists := s.usersByID[memberID]; !exists {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"%w: member %s",
|
||||
ErrNotFound,
|
||||
memberID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.chatsByID[chat.ID] = chat
|
||||
s.messagesByChatID[chat.ID] = make([]domain.Message, 0)
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
// Требование безопасности: посторонний получает 404, а не 403
|
||||
isMember := false
|
||||
for _, m := range chat.MemberIDs {
|
||||
if m == callerID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !isMember {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatsForUser(
|
||||
userID string,
|
||||
limit int,
|
||||
cursorStr string,
|
||||
) (domain.ChatPage, error) {
|
||||
var cursorData *domain.ChatCursorData
|
||||
|
||||
if cursorStr != "" {
|
||||
decodedCursor, err := domain.DecodeChatCursor(cursorStr, userID)
|
||||
if err != nil {
|
||||
return domain.ChatPage{},
|
||||
fmt.Errorf("%w: %v", ErrInvalidCursor, err)
|
||||
}
|
||||
|
||||
cursorData = decodedCursor
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chats := make([]domain.Chat, 0)
|
||||
|
||||
for _, chat := range s.chatsByID {
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == userID {
|
||||
chats = append(chats, chat)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(chats, func(i, j int) bool {
|
||||
if chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
|
||||
return chats[i].ID < chats[j].ID
|
||||
}
|
||||
|
||||
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
|
||||
})
|
||||
|
||||
start := 0
|
||||
|
||||
if cursorData != nil {
|
||||
start = sort.Search(len(chats), func(index int) bool {
|
||||
chat := chats[index]
|
||||
|
||||
if chat.CreatedAt.After(cursorData.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
|
||||
return chat.CreatedAt.Equal(cursorData.CreatedAt) &&
|
||||
chat.ID > cursorData.ChatID
|
||||
})
|
||||
}
|
||||
|
||||
page := domain.ChatPage{
|
||||
Items: make([]domain.Chat, 0),
|
||||
NextCursor: nil,
|
||||
}
|
||||
|
||||
if start >= len(chats) {
|
||||
return page, nil
|
||||
}
|
||||
|
||||
end := start + limit
|
||||
if end > len(chats) {
|
||||
end = len(chats)
|
||||
}
|
||||
|
||||
page.Items = make([]domain.Chat, end-start)
|
||||
copy(page.Items, chats[start:end])
|
||||
|
||||
if end < len(chats) {
|
||||
lastChat := page.Items[len(page.Items)-1]
|
||||
nextCursor := domain.EncodeChatCursor(
|
||||
lastChat.CreatedAt,
|
||||
lastChat.ID,
|
||||
userID,
|
||||
)
|
||||
page.NextCursor = &nextCursor
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// ---Сообщения---
|
||||
|
||||
func (s *MemoryStore) CreateMessage(
|
||||
chatID, senderID, text string,
|
||||
) (domain.Message, error) {
|
||||
messageID := uuid.NewString()
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
isMember := false
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == senderID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isMember {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
createdAt := time.Now().UTC()
|
||||
|
||||
messages := s.messagesByChatID[chatID]
|
||||
if len(messages) > 0 {
|
||||
lastCreatedAt := messages[len(messages)-1].CreatedAt
|
||||
|
||||
// Обеспечиваем строго возрастающее время внутри каждого чата.
|
||||
if !createdAt.After(lastCreatedAt) {
|
||||
createdAt = lastCreatedAt.Add(time.Nanosecond)
|
||||
}
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: messageID,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
|
||||
s.messagesByChatID[chatID] = append(messages, message)
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetMessages(
|
||||
chatID, callerID string,
|
||||
limit int,
|
||||
cursorStr string,
|
||||
) (domain.MessagePage, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return domain.MessagePage{}, ErrNotFound
|
||||
}
|
||||
|
||||
isMember := false
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == callerID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isMember {
|
||||
return domain.MessagePage{}, ErrNotFound
|
||||
}
|
||||
|
||||
var cursorData *domain.CursorData
|
||||
if cursorStr != "" {
|
||||
decodedCursor, err := domain.DecodeCursor(cursorStr, chatID)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"%w: %v",
|
||||
ErrInvalidCursor,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
cursorData = decodedCursor
|
||||
}
|
||||
|
||||
messages := s.messagesByChatID[chatID]
|
||||
|
||||
start := 0
|
||||
|
||||
if cursorData != nil {
|
||||
// Срез уже упорядочен во время записи, поэтому вместо
|
||||
// полного прохода используем бинарный поиск.
|
||||
start = sort.Search(len(messages), func(index int) bool {
|
||||
message := messages[index]
|
||||
|
||||
if message.CreatedAt.After(cursorData.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
|
||||
return message.CreatedAt.Equal(cursorData.CreatedAt) &&
|
||||
message.ID > cursorData.MessageID
|
||||
})
|
||||
}
|
||||
|
||||
page := domain.MessagePage{
|
||||
Items: make([]domain.Message, 0),
|
||||
NextCursor: nil,
|
||||
}
|
||||
|
||||
if start >= len(messages) {
|
||||
return page, nil
|
||||
}
|
||||
|
||||
end := len(messages)
|
||||
if limit > 0 && end-start > limit {
|
||||
end = start + limit
|
||||
}
|
||||
|
||||
// копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез
|
||||
page.Items = make([]domain.Message, end-start)
|
||||
copy(page.Items, messages[start:end])
|
||||
|
||||
if end < len(messages) {
|
||||
lastItem := page.Items[len(page.Items)-1]
|
||||
nextCursor := domain.EncodeCursor(
|
||||
lastItem.CreatedAt,
|
||||
lastItem.ID,
|
||||
chatID,
|
||||
)
|
||||
page.NextCursor = &nextCursor
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
type memorySession struct {
|
||||
userID string
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type MemoryRepository struct {
|
||||
legacy *MemoryStore
|
||||
|
||||
mu sync.RWMutex
|
||||
passwordByUserID map[string]string
|
||||
userIDByUsername map[string]string
|
||||
sessionsByHashKey map[[32]byte]memorySession
|
||||
}
|
||||
|
||||
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
|
||||
return &MemoryRepository{
|
||||
legacy: legacy,
|
||||
passwordByUserID: make(map[string]string),
|
||||
userIDByUsername: make(map[string]string),
|
||||
sessionsByHashKey: make(map[[32]byte]memorySession),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
user, err := r.legacy.CreateUser(username, displayName)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
r.passwordByUserID[user.ID] = passwordHash
|
||||
r.userIDByUsername[user.Username] = user.ID
|
||||
r.mu.Unlock()
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetUserByID(userID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, "", err
|
||||
}
|
||||
|
||||
r.mu.RLock()
|
||||
userID, exists := r.userIDByUsername[username]
|
||||
passwordHash := r.passwordByUserID[userID]
|
||||
r.mu.RUnlock()
|
||||
|
||||
if !exists {
|
||||
return domain.User{}, "", ErrNotFound
|
||||
}
|
||||
|
||||
user, err := r.legacy.GetUserByID(userID)
|
||||
if err != nil {
|
||||
return domain.User{}, "", err
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return r.legacy.CreateChat(title, memberIDs)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetChatByID(chatID, callerID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (domain.ChatPage, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.ChatPage{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetChatsForUser(userID, limit, cursor)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
) (domain.Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
return r.legacy.CreateMessage(chatID, senderID, text)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (domain.MessagePage, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetMessages(
|
||||
chatID,
|
||||
callerID,
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
r.sessionsByHashKey[key] = memorySession{
|
||||
userID: userID,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
|
||||
r.mu.RLock()
|
||||
session, exists := r.sessionsByHashKey[key]
|
||||
r.mu.RUnlock()
|
||||
|
||||
if !exists || !session.expiresAt.After(time.Now().UTC()) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
|
||||
return r.legacy.GetUserByID(session.userID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
delete(r.sessionsByHashKey, key)
|
||||
r.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
|
||||
var key [32]byte
|
||||
|
||||
if len(tokenHash) != len(key) {
|
||||
return key, fmt.Errorf(
|
||||
"session token hash must contain %d bytes",
|
||||
len(key),
|
||||
)
|
||||
}
|
||||
|
||||
copy(key[:], tokenHash)
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
||||
var _ Repository = (*MemoryRepository)(nil)
|
||||
@@ -0,0 +1,40 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type PostgreSQLStore struct {
|
||||
pool *pgxpool.Pool
|
||||
queryTimeout time.Duration
|
||||
}
|
||||
|
||||
func NewPostgreSQLStore(
|
||||
pool *pgxpool.Pool,
|
||||
queryTimeout time.Duration,
|
||||
) *PostgreSQLStore {
|
||||
return &PostgreSQLStore{
|
||||
pool: pool,
|
||||
queryTimeout: queryTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) Ping(ctx context.Context) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.pool.Ping(queryContext)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) withTimeout(
|
||||
ctx context.Context,
|
||||
) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
transaction, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"begin create chat transaction: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = transaction.Rollback(queryContext)
|
||||
}()
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO chats (
|
||||
id,
|
||||
title
|
||||
)
|
||||
VALUES ($1, $2)
|
||||
RETURNING created_at
|
||||
`,
|
||||
chat.ID,
|
||||
chat.Title,
|
||||
).Scan(&chat.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
for position, memberID := range memberIDs {
|
||||
commandTag, insertErr := transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO chat_members (
|
||||
chat_id,
|
||||
user_id,
|
||||
position
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
id,
|
||||
$3
|
||||
FROM users
|
||||
WHERE id = $2
|
||||
`,
|
||||
chat.ID,
|
||||
memberID,
|
||||
position,
|
||||
)
|
||||
if insertErr != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"insert chat member %s: %w",
|
||||
memberID,
|
||||
insertErr,
|
||||
)
|
||||
}
|
||||
|
||||
// INSERT ... SELECT не вставляет строку, если пользователя нет.
|
||||
// Возврат из функции активирует deferred Rollback: уже созданные
|
||||
// chat и предыдущие membership-строки не останутся в базе.
|
||||
if commandTag.RowsAffected() != 1 {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"%w: member %s",
|
||||
ErrNotFound,
|
||||
memberID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"commit create chat transaction: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var chat domain.Chat
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chats AS chat
|
||||
JOIN chat_members AS caller
|
||||
ON caller.chat_id = chat.id
|
||||
AND caller.user_id = $2
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE chat.id = $1
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
`,
|
||||
chatID,
|
||||
callerID,
|
||||
).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("select chat by id: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursorString string,
|
||||
) (domain.ChatPage, error) {
|
||||
var cursor *domain.ChatCursorData
|
||||
|
||||
if cursorString != "" {
|
||||
decodedCursor, err := domain.DecodeChatCursor(
|
||||
cursorString,
|
||||
userID,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, fmt.Errorf(
|
||||
"%w: %v",
|
||||
ErrInvalidCursor,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
cursor = decodedCursor
|
||||
}
|
||||
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chat_members AS own_membership
|
||||
JOIN chats AS chat
|
||||
ON chat.id = own_membership.chat_id
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE own_membership.user_id = $1
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
ORDER BY
|
||||
chat.created_at,
|
||||
chat.id
|
||||
LIMIT $2
|
||||
`,
|
||||
userID,
|
||||
limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chat_members AS own_membership
|
||||
JOIN chats AS chat
|
||||
ON chat.id = own_membership.chat_id
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE own_membership.user_id = $1
|
||||
AND (chat.created_at, chat.id) > ($2, $3)
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
ORDER BY
|
||||
chat.created_at,
|
||||
chat.id
|
||||
LIMIT $4
|
||||
`,
|
||||
userID,
|
||||
cursor.CreatedAt,
|
||||
cursor.ChatID,
|
||||
limit+1,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, fmt.Errorf(
|
||||
"query chats for user: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := domain.ChatPage{
|
||||
Items: make([]domain.Chat, 0, limit),
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
var chat domain.Chat
|
||||
|
||||
if err := rows.Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
); err != nil {
|
||||
return domain.ChatPage{}, fmt.Errorf(
|
||||
"scan chat page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
page.Items = append(page.Items, chat)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return domain.ChatPage{}, fmt.Errorf(
|
||||
"iterate chat page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if len(page.Items) > limit {
|
||||
page.Items = page.Items[:limit]
|
||||
|
||||
lastChat := page.Items[len(page.Items)-1]
|
||||
nextCursor := domain.EncodeChatCursor(
|
||||
lastChat.CreatedAt,
|
||||
lastChat.ID,
|
||||
userID,
|
||||
)
|
||||
page.NextCursor = &nextCursor
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
) (domain.Message, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
message := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
}
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO messages (
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4
|
||||
FROM chat_members
|
||||
WHERE chat_id = $2
|
||||
AND user_id = $3
|
||||
RETURNING created_at
|
||||
`,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
message.SenderID,
|
||||
message.Text,
|
||||
).Scan(&message.CreatedAt)
|
||||
|
||||
if err == nil {
|
||||
return message, nil
|
||||
}
|
||||
|
||||
// INSERT ... SELECT возвращает zero rows, если отправитель
|
||||
// не является участником указанного чата.
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
return domain.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursorString string,
|
||||
) (domain.MessagePage, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var isMember bool
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
`,
|
||||
chatID,
|
||||
callerID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"check chat membership: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if !isMember {
|
||||
return domain.MessagePage{}, ErrNotFound
|
||||
}
|
||||
|
||||
var cursor *domain.CursorData
|
||||
|
||||
if cursorString != "" {
|
||||
decodedCursor, err := domain.DecodeCursor(
|
||||
cursorString,
|
||||
chatID,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"%w: %v",
|
||||
ErrInvalidCursor,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
cursor = decodedCursor
|
||||
}
|
||||
|
||||
var rows pgx.Rows
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
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(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY
|
||||
created_at,
|
||||
id
|
||||
LIMIT $4
|
||||
`,
|
||||
chatID,
|
||||
cursor.CreatedAt,
|
||||
cursor.MessageID,
|
||||
limit+1,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"query messages: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := domain.MessagePage{
|
||||
Items: make([]domain.Message, 0, limit),
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
var message domain.Message
|
||||
|
||||
if err := rows.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
); err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"scan message page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
page.Items = append(page.Items, message)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"iterate message page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if len(page.Items) > limit {
|
||||
page.Items = page.Items[:limit]
|
||||
|
||||
lastMessage := page.Items[len(page.Items)-1]
|
||||
nextCursor := domain.EncodeCursor(
|
||||
lastMessage.CreatedAt,
|
||||
lastMessage.ID,
|
||||
chatID,
|
||||
)
|
||||
page.NextCursor = &nextCursor
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO sessions (
|
||||
token_hash,
|
||||
user_id,
|
||||
expires_at
|
||||
)
|
||||
VALUES ($1, $2, $3)
|
||||
`,
|
||||
tokenHash,
|
||||
userID,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user domain.User
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
app_user.id::text,
|
||||
app_user.username,
|
||||
app_user.display_name,
|
||||
app_user.created_at
|
||||
FROM sessions AS session
|
||||
JOIN users AS app_user
|
||||
ON app_user.id = session.user_id
|
||||
WHERE session.token_hash = $1
|
||||
AND session.expires_at > CURRENT_TIMESTAMP
|
||||
`,
|
||||
tokenHash,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf(
|
||||
"select user by session: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
`,
|
||||
tokenHash,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
}
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at
|
||||
`,
|
||||
user.ID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
passwordHash,
|
||||
).Scan(&user.CreatedAt)
|
||||
|
||||
if err == nil {
|
||||
return user, nil
|
||||
}
|
||||
|
||||
var postgresError *pgconn.PgError
|
||||
if errors.As(err, &postgresError) &&
|
||||
postgresError.Code == "23505" &&
|
||||
postgresError.ConstraintName == "users_username_unique" {
|
||||
return domain.User{}, ErrConflict
|
||||
}
|
||||
|
||||
return domain.User{}, fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user domain.User
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
username,
|
||||
display_name,
|
||||
created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`,
|
||||
userID,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("select user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
user domain.User
|
||||
passwordHash string
|
||||
)
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
username,
|
||||
display_name,
|
||||
created_at,
|
||||
password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`,
|
||||
username,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
&passwordHash,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, "", fmt.Errorf(
|
||||
"select user by username: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error)
|
||||
|
||||
GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error)
|
||||
|
||||
GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error)
|
||||
|
||||
CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error)
|
||||
|
||||
GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error)
|
||||
|
||||
GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (domain.ChatPage, error)
|
||||
|
||||
CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
) (domain.Message, error)
|
||||
|
||||
GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (domain.MessagePage, error)
|
||||
|
||||
CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error
|
||||
|
||||
GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error)
|
||||
|
||||
DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error
|
||||
}
|
||||
|
||||
var _ Repository = (*PostgreSQLStore)(nil)
|
||||
@@ -0,0 +1,168 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var req CreateChatRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeDecodeJSONError(w, reqID, err)
|
||||
return
|
||||
}
|
||||
|
||||
//вызывающий есть в списке, нет дубликатов, валидные UUID
|
||||
if err := domain.ValidateChatInput(req.Title, req.MemberIDs, currentUser.ID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.CreateChat(
|
||||
r.Context(),
|
||||
req.Title,
|
||||
req.MemberIDs,
|
||||
)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"one or more members do not exist",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusCreated, chat, reqID)
|
||||
}
|
||||
|
||||
// инфа о чате
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChatByID(
|
||||
r.Context(),
|
||||
chatID,
|
||||
currentUser.ID,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
//посторонний или несуществующий чат -> 404
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||
return
|
||||
}
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, chat, reqID)
|
||||
}
|
||||
|
||||
// список всех чатов текущего пользователя
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
query := r.URL.Query()
|
||||
|
||||
limit := 50
|
||||
|
||||
if query.Has("limit") {
|
||||
limitStr := query.Get("limit")
|
||||
val, err := strconv.Atoi(limitStr)
|
||||
|
||||
if err != nil || val < 1 || val > 100 {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"limit must be an integer between 1 and 100",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
limit = val
|
||||
}
|
||||
|
||||
cursor := query.Get("cursor")
|
||||
if query.Has("cursor") && cursor == "" {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"cursor must not be empty",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.store.GetChatsForUser(
|
||||
r.Context(),
|
||||
currentUser.ID,
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrInvalidCursor) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"invalid cursor",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, page, reqID)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const maxJSONBodyBytes = 1 << 20
|
||||
|
||||
var (
|
||||
errUnsupportedMediaType = errors.New("unsupported media type")
|
||||
errJSONBodyTooLarge = errors.New("JSON body exceeds 1 MiB")
|
||||
)
|
||||
|
||||
type ReadinessChecker interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Option func(*Handler)
|
||||
|
||||
type Handler struct {
|
||||
store store.Repository
|
||||
readinessChecker ReadinessChecker
|
||||
readinessTimeout time.Duration
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func NewHandler(
|
||||
repository store.Repository,
|
||||
options ...Option,
|
||||
) *Handler {
|
||||
handler := &Handler{
|
||||
store: repository,
|
||||
readinessTimeout: 2 * time.Second,
|
||||
sessionTTL: time.Hour,
|
||||
}
|
||||
|
||||
for _, option := range options {
|
||||
option(handler)
|
||||
}
|
||||
|
||||
return handler
|
||||
}
|
||||
|
||||
func WithReadiness(
|
||||
checker ReadinessChecker,
|
||||
timeout time.Duration,
|
||||
) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.readinessChecker = checker
|
||||
handler.readinessTimeout = timeout
|
||||
}
|
||||
}
|
||||
|
||||
func WithSessionTTL(ttl time.Duration) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.sessionTTL = ttl
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, destination any) error {
|
||||
mediaType, parameters, err := mime.ParseMediaType(
|
||||
r.Header.Get("Content-Type"),
|
||||
)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
if charset, exists := parameters["charset"]; exists &&
|
||||
!strings.EqualFold(charset, "utf-8") {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
|
||||
if r.Body == nil {
|
||||
return errors.New("request body is empty")
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
payload, err := io.ReadAll(io.LimitReader(
|
||||
r.Body,
|
||||
maxJSONBodyBytes+1,
|
||||
))
|
||||
if err != nil {
|
||||
return errors.New("read request body")
|
||||
}
|
||||
if len(payload) > maxJSONBodyBytes {
|
||||
return errJSONBodyTooLarge
|
||||
}
|
||||
if !utf8.Valid(payload) {
|
||||
return errors.New("request body must be valid UTF-8")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var extra json.RawMessage
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return errors.New("extra data after JSON")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeDecodeJSONError(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
err error,
|
||||
) {
|
||||
switch {
|
||||
case errors.Is(err, errUnsupportedMediaType):
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"Content-Type must be application/json",
|
||||
requestID,
|
||||
)
|
||||
case errors.Is(err, errJSONBodyTooLarge):
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
err.Error(),
|
||||
requestID,
|
||||
)
|
||||
default:
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"malformed or invalid JSON: "+err.Error(),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// HealthLive проверяет только то, что HTTP-процесс работает.
|
||||
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
// HealthReady проверяет зависимости, без которых API не может обслуживать трафик.
|
||||
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Этот вариант сохраняет работоспособность изолированных unit-тестов,
|
||||
// в которых PostgreSQL намеренно не создаётся.
|
||||
if h.readinessChecker == nil {
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(
|
||||
r.Context(),
|
||||
h.readinessTimeout,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if err := h.readinessChecker.Ping(ctx); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is not ready",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// CreateMessage отправляет сообщение в чат
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
var req CreateMessageRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeDecodeJSONError(w, reqID, err)
|
||||
return
|
||||
}
|
||||
|
||||
//не пустой, не только пробелы, до 4000 рун
|
||||
if err := domain.ValidateMessageText(req.Text); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
return
|
||||
}
|
||||
|
||||
//автор сообщения строго выводится из сессии (currentUser.ID)
|
||||
msg, err := h.store.CreateMessage(
|
||||
r.Context(),
|
||||
chatID,
|
||||
currentUser.ID,
|
||||
req.Text,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
// чата нет/пользователь не участник -> 404
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||
return
|
||||
}
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusCreated, msg, reqID)
|
||||
}
|
||||
|
||||
// GetMessages возвращает историю сообщений чата с пагинацией по курсору
|
||||
func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID)
|
||||
return
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
|
||||
limit := 50
|
||||
if query.Has("limit") {
|
||||
limitString := query.Get("limit")
|
||||
|
||||
parsedLimit, err := strconv.Atoi(limitString)
|
||||
if err != nil || parsedLimit < 1 || parsedLimit > 100 {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"limit must be an integer between 1 and 100",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
limit = parsedLimit
|
||||
}
|
||||
|
||||
cursor := query.Get("cursor")
|
||||
if query.Has("cursor") && cursor == "" {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"cursor must not be empty",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.store.GetMessages(
|
||||
r.Context(),
|
||||
chatID,
|
||||
currentUser.ID,
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
response.CodeNotFound,
|
||||
"chat not found",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if errors.Is(err, store.ErrInvalidCursor) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"invalid cursor",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// сообщений нет, [] вместо null
|
||||
if page.Items == nil {
|
||||
page.Items = make([]domain.Message, 0)
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, page, reqID)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/security"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
|
||||
// dummyPasswordHash keeps the expensive Argon2id path for an unknown username.
|
||||
// The all-zero digest is intentionally not a real user's credential; only the
|
||||
// encoded parameters and lengths need to be valid for constant-cost checking.
|
||||
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
|
||||
"AAAAAAAAAAAAAAAAAAAAAA$" +
|
||||
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
|
||||
func (h *Handler) CreateSession(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" ||
|
||||
!utf8.ValidString(username) || !utf8.ValidString(password) {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := h.store.GetUserByUsername(
|
||||
r.Context(),
|
||||
username,
|
||||
)
|
||||
userNotFound := errors.Is(err, store.ErrNotFound)
|
||||
if userNotFound {
|
||||
passwordHash = dummyPasswordHash
|
||||
}
|
||||
if err != nil {
|
||||
if !userNotFound {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
passwordMatches, err := security.VerifyPassword(
|
||||
password,
|
||||
passwordHash,
|
||||
)
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"stored password hash is invalid",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if userNotFound || !passwordMatches {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
token, tokenHash, err := security.GenerateSessionToken()
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"failed to create session",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
expiresAt := time.Now().UTC().Add(h.sessionTTL)
|
||||
|
||||
if err := h.store.CreateSession(
|
||||
r.Context(),
|
||||
tokenHash,
|
||||
user.ID,
|
||||
expiresAt,
|
||||
); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
session := domain.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
User: user,
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
session,
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteCurrentSession(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
tokenHash := middleware.GetCurrentSessionTokenHash(r.Context())
|
||||
|
||||
if err := h.store.DeleteSession(
|
||||
r.Context(),
|
||||
tokenHash,
|
||||
); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusNoContent,
|
||||
nil,
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
func writeBasicUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", basicChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid username or password",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/security"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
var request CreateUserRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
userCandidate := domain.User{
|
||||
Username: request.Username,
|
||||
DisplayName: request.DisplayName,
|
||||
}
|
||||
|
||||
if err := userCandidate.Validate(); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
err.Error(),
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if err := security.ValidatePassword(request.Password); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
err.Error(),
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := security.HashPassword(request.Password)
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"failed to process password",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := h.store.CreateUser(
|
||||
r.Context(),
|
||||
request.Username,
|
||||
request.DisplayName,
|
||||
passwordHash,
|
||||
)
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
response.CodeConflict,
|
||||
"username already exists",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
createdUser,
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
currentUser,
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/security"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const bearerChallenge = `Bearer realm="messenger"`
|
||||
|
||||
const (
|
||||
UserContextKey contextKey = "current_user"
|
||||
sessionTokenHashKey contextKey = "session_token_hash"
|
||||
)
|
||||
|
||||
type SessionAuthenticator interface {
|
||||
GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error)
|
||||
}
|
||||
|
||||
func RequireAuth(
|
||||
authenticator SessionAuthenticator,
|
||||
next http.HandlerFunc,
|
||||
) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := GetRequestID(r.Context())
|
||||
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
tokenHash := security.HashSessionToken(token)
|
||||
|
||||
user, err := authenticator.GetUserBySession(
|
||||
r.Context(),
|
||||
tokenHash,
|
||||
)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(
|
||||
r.Context(),
|
||||
UserContextKey,
|
||||
user,
|
||||
)
|
||||
ctx = context.WithValue(
|
||||
ctx,
|
||||
sessionTokenHashKey,
|
||||
tokenHash,
|
||||
)
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func GetCurrentUser(ctx context.Context) domain.User {
|
||||
user, _ := ctx.Value(UserContextKey).(domain.User)
|
||||
return user
|
||||
}
|
||||
|
||||
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
|
||||
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
|
||||
|
||||
result := make([]byte, len(tokenHash))
|
||||
copy(result, tokenHash)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func bearerToken(authorization string) (string, bool) {
|
||||
parts := strings.Fields(authorization)
|
||||
|
||||
if len(parts) != 2 ||
|
||||
!strings.EqualFold(parts[0], "Bearer") ||
|
||||
parts[1] == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return parts[1], true
|
||||
}
|
||||
|
||||
func writeBearerUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", bearerChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid or expired bearer token",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// responseWriterInterceptor перехватывает статус-код ответа для логов
|
||||
type responseWriterInterceptor struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *responseWriterInterceptor) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Logger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
interceptor := &responseWriterInterceptor{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK, // дефолтный статус если WriteHeader не вызывался
|
||||
}
|
||||
|
||||
next.ServeHTTP(interceptor, r)
|
||||
|
||||
reqID := GetRequestID(r.Context())
|
||||
duration := time.Since(start)
|
||||
|
||||
// метаданные без r.Body
|
||||
log.Printf(
|
||||
"[HTTP] %s %s | status: %d | duration: %v | request_id: %s",
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
interceptor.statusCode,
|
||||
duration,
|
||||
reqID,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// Recovery перехватывает панику и возвращает клиенту валидный JSON 500
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
reqID := GetRequestID(r.Context())
|
||||
//из контракта: не раскрывать stack trace и внутренности
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"internal server error",
|
||||
reqID,
|
||||
)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RequestIDKey contextKey = "request_id"
|
||||
|
||||
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := r.Header.Get("X-Request-Id")
|
||||
if reqID == "" {
|
||||
reqID = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// GetRequestID достает ID запроса из контекста
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
if val, ok := ctx.Value(RequestIDKey).(string); ok {
|
||||
return val
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// коды ошибок по контракту
|
||||
const (
|
||||
CodeInvalidRequest = "invalid_request"
|
||||
CodePayloadTooLarge = "payload_too_large"
|
||||
CodeUnsupportedMediaType = "unsupported_media_type"
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodeUnavailable = "unavailable"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
type ErrorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// ErrorResponse — строгое тело ответа при любой ошибке
|
||||
type ErrorResponse struct {
|
||||
Error ErrorPayload `json:"error"`
|
||||
}
|
||||
|
||||
// WriteJSON отправляет любой успешный ответ с правильными заголовками
|
||||
func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
if data != nil {
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке
|
||||
func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
resp := ErrorResponse{
|
||||
Error: ErrorPayload{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
BEGIN;
|
||||
|
||||
DROP TABLE sessions;
|
||||
DROP TABLE messages;
|
||||
DROP TABLE chat_members;
|
||||
DROP TABLE chats;
|
||||
DROP TABLE users;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,112 @@
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY,
|
||||
username VARCHAR(32) NOT NULL,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT users_username_unique
|
||||
UNIQUE (username),
|
||||
|
||||
CONSTRAINT users_username_format
|
||||
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
|
||||
CONSTRAINT users_display_name_length
|
||||
CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
|
||||
CONSTRAINT users_display_name_not_blank
|
||||
CHECK (btrim(display_name) <> ''),
|
||||
|
||||
CONSTRAINT users_password_hash_not_blank
|
||||
CHECK (btrim(password_hash) <> '')
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT chats_title_length
|
||||
CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
|
||||
CONSTRAINT chats_title_not_blank
|
||||
CHECK (btrim(title) <> '')
|
||||
);
|
||||
|
||||
CREATE INDEX chats_created_at_id_idx
|
||||
ON chats (created_at, id);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id UUID NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
position SMALLINT NOT NULL,
|
||||
|
||||
CONSTRAINT chat_members_primary_key
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
|
||||
CONSTRAINT chat_members_position_unique
|
||||
UNIQUE (chat_id, position),
|
||||
|
||||
CONSTRAINT chat_members_position_range
|
||||
CHECK (position BETWEEN 0 AND 99),
|
||||
|
||||
CONSTRAINT chat_members_chat_foreign_key
|
||||
FOREIGN KEY (chat_id)
|
||||
REFERENCES chats (id)
|
||||
ON DELETE RESTRICT,
|
||||
|
||||
CONSTRAINT chat_members_user_foreign_key
|
||||
FOREIGN KEY (user_id)
|
||||
REFERENCES users (id)
|
||||
ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_chat_idx
|
||||
ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL,
|
||||
sender_id UUID NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT messages_text_length
|
||||
CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
|
||||
CONSTRAINT messages_text_not_blank
|
||||
CHECK (btrim(text) <> ''),
|
||||
|
||||
CONSTRAINT messages_sender_membership_foreign_key
|
||||
FOREIGN KEY (chat_id, sender_id)
|
||||
REFERENCES chat_members (chat_id, user_id)
|
||||
ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_created_at_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash BYTEA PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT sessions_user_foreign_key
|
||||
FOREIGN KEY (user_id)
|
||||
REFERENCES users (id)
|
||||
ON DELETE RESTRICT,
|
||||
|
||||
CONSTRAINT sessions_token_hash_length
|
||||
CHECK (octet_length(token_hash) = 32),
|
||||
|
||||
CONSTRAINT sessions_expiry_after_creation
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_expires_at_idx
|
||||
ON sessions (expires_at);
|
||||
|
||||
COMMIT;
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
env_file=${ENV_FILE:-.env}
|
||||
|
||||
docker compose --env-file "$env_file" exec -T postgres sh -ec \
|
||||
'exec psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"' \
|
||||
< tests/explain_history.sql
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
env_file=${ENV_FILE:-.env}
|
||||
|
||||
case "${DATABASE_ACTION:-}" in
|
||||
stop)
|
||||
docker compose --env-file "$env_file" stop postgres
|
||||
;;
|
||||
start)
|
||||
docker compose --env-file "$env_file" up -d --wait postgres
|
||||
;;
|
||||
*)
|
||||
echo "DATABASE_ACTION must be stop or start" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
env_file=${ENV_FILE:-.env}
|
||||
|
||||
case "${CACHE_ACTION:-}" in
|
||||
stop)
|
||||
docker compose --env-file "$env_file" stop redis
|
||||
;;
|
||||
start)
|
||||
docker compose --env-file "$env_file" up -d --wait redis
|
||||
;;
|
||||
*)
|
||||
echo "CACHE_ACTION must be stop or start" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
env_file=${ENV_FILE:-.env}
|
||||
|
||||
# PostgreSQL хранит все обязательные данные и сессии в named volume.
|
||||
# Redis содержит только восстанавливаемый кеш и намеренно не имеет volume.
|
||||
docker compose --env-file "$env_file" restart postgres redis
|
||||
docker compose --env-file "$env_file" up -d --wait postgres redis
|
||||
|
||||
# API перезапускается после восстановления обязательной БД и кеша.
|
||||
docker compose --env-file "$env_file" restart api
|
||||
Executable
+106
@@ -0,0 +1,106 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
env_file=${ENV_FILE:-.env}
|
||||
run_id="$(date +%s)_$$"
|
||||
source_db="track2_source_$run_id"
|
||||
restore_db="track2_restore_$run_id"
|
||||
recovery_project="mtusi2026lab2_recovery_$run_id"
|
||||
temp_dir=$(mktemp -d)
|
||||
backup_file="$temp_dir/track2.dump"
|
||||
source_fingerprint="$temp_dir/source.fingerprint"
|
||||
restore_fingerprint="$temp_dir/restore.fingerprint"
|
||||
source_created=0
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT HUP INT TERM
|
||||
|
||||
docker compose -p "$recovery_project" --env-file "$env_file" \
|
||||
--profile recovery down --volumes --remove-orphans >/dev/null 2>&1 || true
|
||||
|
||||
if [ "$source_created" -eq 1 ]; then
|
||||
docker compose --env-file "$env_file" exec -T \
|
||||
-e TARGET_DB="$source_db" postgres sh -ec \
|
||||
'dropdb --if-exists -U "$POSTGRES_USER" "$TARGET_DB"' \
|
||||
>/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
rm -f "$backup_file" "$source_fingerprint" "$restore_fingerprint"
|
||||
rmdir "$temp_dir" 2>/dev/null || true
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 129' HUP
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
source_created=1
|
||||
docker compose --env-file "$env_file" exec -T \
|
||||
-e TARGET_DB="$source_db" postgres sh -ec \
|
||||
'createdb -U "$POSTGRES_USER" "$TARGET_DB"'
|
||||
|
||||
docker compose --env-file "$env_file" exec -T \
|
||||
-e TARGET_DB="$source_db" postgres sh -ec \
|
||||
'exec psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$TARGET_DB"' \
|
||||
< migrations/000001_initial.up.sql
|
||||
|
||||
echo "Running isolated 100000-message query/index experiment."
|
||||
docker compose --env-file "$env_file" exec -T \
|
||||
-e TARGET_DB="$source_db" postgres sh -ec \
|
||||
'exec psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$TARGET_DB"' \
|
||||
< tests/track2_experiment.sql
|
||||
|
||||
docker compose --env-file "$env_file" exec -T \
|
||||
-e TARGET_DB="$source_db" postgres sh -ec \
|
||||
'exec psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$TARGET_DB"' \
|
||||
< tests/track2_fingerprint.sql > "$source_fingerprint"
|
||||
|
||||
backup_started=$(date +%s%N)
|
||||
docker compose --env-file "$env_file" exec -T \
|
||||
-e TARGET_DB="$source_db" postgres sh -ec \
|
||||
'exec pg_dump -U "$POSTGRES_USER" -d "$TARGET_DB" \
|
||||
--format=custom --compress=6 --no-owner --no-privileges' \
|
||||
> "$backup_file"
|
||||
backup_finished=$(date +%s%N)
|
||||
|
||||
recovery_started=$(date +%s%N)
|
||||
docker compose -p "$recovery_project" --env-file "$env_file" --profile recovery \
|
||||
up -d --wait postgres-restore
|
||||
|
||||
docker compose -p "$recovery_project" --env-file "$env_file" \
|
||||
--profile recovery exec -T \
|
||||
-e TARGET_DB="$restore_db" postgres-restore sh -ec \
|
||||
'createdb -U "$POSTGRES_USER" "$TARGET_DB"'
|
||||
|
||||
docker compose -p "$recovery_project" --env-file "$env_file" \
|
||||
--profile recovery exec -T \
|
||||
-e TARGET_DB="$restore_db" postgres-restore sh -ec \
|
||||
'exec pg_restore --exit-on-error -U "$POSTGRES_USER" -d "$TARGET_DB" \
|
||||
--no-owner --no-privileges' \
|
||||
< "$backup_file"
|
||||
|
||||
docker compose -p "$recovery_project" --env-file "$env_file" \
|
||||
--profile recovery exec -T \
|
||||
-e TARGET_DB="$restore_db" postgres-restore sh -ec \
|
||||
'exec psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$TARGET_DB"' \
|
||||
< tests/track2_fingerprint.sql > "$restore_fingerprint"
|
||||
|
||||
cmp -s "$source_fingerprint" "$restore_fingerprint"
|
||||
recovery_finished=$(date +%s%N)
|
||||
|
||||
backup_ms=$(( (backup_finished - backup_started) / 1000000 ))
|
||||
recovery_ms=$(( (recovery_finished - recovery_started) / 1000000 ))
|
||||
backup_bytes=$(wc -c < "$backup_file" | tr -d ' ')
|
||||
|
||||
echo "BACKUP_RESTORE_RESULT"
|
||||
echo "backup_bytes=$backup_bytes"
|
||||
echo "backup_ms=$backup_ms"
|
||||
echo "recovery_ms=$recovery_ms"
|
||||
echo "fingerprints_match=true"
|
||||
echo "source_and_restored_fingerprint:"
|
||||
cat "$source_fingerprint"
|
||||
echo "PASS: Track 2 query/index and backup-to-separate-storage experiment completed."
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
env_file=${ENV_FILE:-.env}
|
||||
|
||||
case "${SESSION_TTL_ACTION:-}" in
|
||||
short)
|
||||
ttl=${SHORT_SESSION_TTL_SECONDS:-2}
|
||||
case "$ttl" in
|
||||
''|*[!0-9]*|0)
|
||||
echo "SHORT_SESSION_TTL_SECONDS must be a positive integer" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
SESSION_TTL_SECONDS="$ttl" docker compose --env-file "$env_file" \
|
||||
up -d --no-deps --force-recreate --wait api
|
||||
;;
|
||||
restore)
|
||||
docker compose --env-file "$env_file" \
|
||||
up -d --no-deps --force-recreate --wait api
|
||||
;;
|
||||
*)
|
||||
echo "SESSION_TTL_ACTION must be short or restore" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,352 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/security"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/handlers"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
const testPassword = "Test-password-123"
|
||||
|
||||
func setupSessionTestServer(
|
||||
t *testing.T,
|
||||
sessionTTL time.Duration,
|
||||
) (*httptest.Server, *store.MemoryRepository) {
|
||||
t.Helper()
|
||||
|
||||
repository := store.NewMemoryRepository(store.NewMemoryStore())
|
||||
handler := handlers.NewHandler(
|
||||
repository,
|
||||
handlers.WithSessionTTL(sessionTTL),
|
||||
)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", handler.CreateSession)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/users/me",
|
||||
middleware.RequireAuth(repository, handler.GetMe),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"DELETE /api/v1/auth/sessions/current",
|
||||
middleware.RequireAuth(repository, handler.DeleteCurrentSession),
|
||||
)
|
||||
|
||||
var root http.Handler = mux
|
||||
root = middleware.Recovery(root)
|
||||
root = middleware.RequestID(root)
|
||||
|
||||
return httptest.NewServer(root), repository
|
||||
}
|
||||
|
||||
func registerSessionTestUser(
|
||||
t *testing.T,
|
||||
baseURL string,
|
||||
username string,
|
||||
) domain.User {
|
||||
t.Helper()
|
||||
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"username": username,
|
||||
"display_name": "Session test user",
|
||||
"password": testPassword,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal registration request: %v", err)
|
||||
}
|
||||
|
||||
response, err := http.Post(
|
||||
baseURL+"/api/v1/users",
|
||||
"application/json",
|
||||
bytes.NewReader(payload),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("register user: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf("expected registration status 201, got %d: %s", response.StatusCode, body)
|
||||
}
|
||||
|
||||
var user domain.User
|
||||
if err := json.NewDecoder(response.Body).Decode(&user); err != nil {
|
||||
t.Fatalf("decode registered user: %v", err)
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func createSessionRequest(
|
||||
t *testing.T,
|
||||
baseURL string,
|
||||
username string,
|
||||
password string,
|
||||
) *http.Response {
|
||||
t.Helper()
|
||||
|
||||
credentials := base64.StdEncoding.EncodeToString(
|
||||
[]byte(username + ":" + password),
|
||||
)
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
baseURL+"/api/v1/auth/sessions",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create login request: %v", err)
|
||||
}
|
||||
request.Header.Set("Authorization", "Basic "+credentials)
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send login request: %v", err)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func TestSessionAuthenticationLifecycle(t *testing.T) {
|
||||
testServer, repository := setupSessionTestServer(t, time.Hour)
|
||||
defer testServer.Close()
|
||||
|
||||
alice := registerSessionTestUser(t, testServer.URL, "session_alice")
|
||||
eve := registerSessionTestUser(t, testServer.URL, "session_eve")
|
||||
|
||||
_, passwordHash, err := repository.GetUserByUsername(
|
||||
t.Context(),
|
||||
alice.Username,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("read registered user credentials: %v", err)
|
||||
}
|
||||
if passwordHash == testPassword || bytes.Contains(
|
||||
[]byte(passwordHash),
|
||||
[]byte(testPassword),
|
||||
) {
|
||||
t.Fatal("repository contains plaintext password")
|
||||
}
|
||||
passwordMatches, err := security.VerifyPassword(testPassword, passwordHash)
|
||||
if err != nil || !passwordMatches {
|
||||
t.Fatalf("stored password hash does not verify: matches=%v err=%v", passwordMatches, err)
|
||||
}
|
||||
|
||||
wrongPasswordResponse := createSessionRequest(
|
||||
t,
|
||||
testServer.URL,
|
||||
alice.Username,
|
||||
"Wrong-password-123",
|
||||
)
|
||||
wrongPasswordResponse.Body.Close()
|
||||
if wrongPasswordResponse.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for wrong password, got %d", wrongPasswordResponse.StatusCode)
|
||||
}
|
||||
if got := wrongPasswordResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("unexpected Basic challenge: %q", got)
|
||||
}
|
||||
|
||||
unknownUserResponse := createSessionRequest(
|
||||
t,
|
||||
testServer.URL,
|
||||
"unknown_session_user",
|
||||
"Wrong-password-123",
|
||||
)
|
||||
unknownUserResponse.Body.Close()
|
||||
if unknownUserResponse.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for unknown username, got %d", unknownUserResponse.StatusCode)
|
||||
}
|
||||
if got := unknownUserResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("unexpected Basic challenge for unknown username: %q", got)
|
||||
}
|
||||
|
||||
loginResponse := createSessionRequest(
|
||||
t,
|
||||
testServer.URL,
|
||||
alice.Username,
|
||||
testPassword,
|
||||
)
|
||||
defer loginResponse.Body.Close()
|
||||
if loginResponse.StatusCode != http.StatusCreated {
|
||||
body, _ := io.ReadAll(loginResponse.Body)
|
||||
t.Fatalf("expected login status 201, got %d: %s", loginResponse.StatusCode, body)
|
||||
}
|
||||
|
||||
var session domain.Session
|
||||
if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil {
|
||||
t.Fatalf("decode session: %v", err)
|
||||
}
|
||||
if session.Token == "" || session.TokenType != "Bearer" {
|
||||
t.Fatalf("unexpected session token response: type=%q empty=%v", session.TokenType, session.Token == "")
|
||||
}
|
||||
if session.User != alice {
|
||||
t.Fatalf("session belongs to another user: got %s, want %s", session.User.ID, alice.ID)
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
authorization string
|
||||
userIDHeader string
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "X-User-Id alone is rejected",
|
||||
userIDHeader: alice.ID,
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "Basic is rejected on business endpoint",
|
||||
authorization: "Basic " + base64.StdEncoding.EncodeToString([]byte(alice.Username+":"+testPassword)),
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "Bearer identity wins over X-User-Id",
|
||||
authorization: "Bearer " + session.Token,
|
||||
userIDHeader: eve.ID,
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
request, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
testServer.URL+"/api/v1/users/me",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create authenticated request: %v", err)
|
||||
}
|
||||
if testCase.authorization != "" {
|
||||
request.Header.Set("Authorization", testCase.authorization)
|
||||
}
|
||||
if testCase.userIDHeader != "" {
|
||||
request.Header.Set("X-User-Id", testCase.userIDHeader)
|
||||
}
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send authenticated request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != testCase.wantStatus {
|
||||
t.Fatalf("expected status %d, got %d", testCase.wantStatus, response.StatusCode)
|
||||
}
|
||||
|
||||
if testCase.wantStatus == http.StatusUnauthorized {
|
||||
if got := response.Header.Get("WWW-Authenticate"); got != `Bearer realm="messenger"` {
|
||||
t.Fatalf("unexpected Bearer challenge: %q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var currentUser domain.User
|
||||
if err := json.NewDecoder(response.Body).Decode(¤tUser); err != nil {
|
||||
t.Fatalf("decode current user: %v", err)
|
||||
}
|
||||
if currentUser.ID != alice.ID {
|
||||
t.Fatalf("X-User-Id overrode Bearer identity: got %s, want %s", currentUser.ID, alice.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
logoutRequest, err := http.NewRequest(
|
||||
http.MethodDelete,
|
||||
testServer.URL+"/api/v1/auth/sessions/current",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create logout request: %v", err)
|
||||
}
|
||||
logoutRequest.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
|
||||
logoutResponse, err := http.DefaultClient.Do(logoutRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("send logout request: %v", err)
|
||||
}
|
||||
logoutBody, err := io.ReadAll(logoutResponse.Body)
|
||||
logoutResponse.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("read logout response: %v", err)
|
||||
}
|
||||
if logoutResponse.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("expected logout status 204, got %d", logoutResponse.StatusCode)
|
||||
}
|
||||
if len(logoutBody) != 0 {
|
||||
t.Fatalf("logout response contains a body: %q", logoutBody)
|
||||
}
|
||||
|
||||
revokedRequest, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
testServer.URL+"/api/v1/users/me",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create revoked-token request: %v", err)
|
||||
}
|
||||
revokedRequest.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
|
||||
revokedResponse, err := http.DefaultClient.Do(revokedRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("send revoked-token request: %v", err)
|
||||
}
|
||||
revokedResponse.Body.Close()
|
||||
if revokedResponse.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for revoked token, got %d", revokedResponse.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
testServer, _ := setupSessionTestServer(t, 25*time.Millisecond)
|
||||
defer testServer.Close()
|
||||
|
||||
user := registerSessionTestUser(t, testServer.URL, "session_expiry")
|
||||
loginResponse := createSessionRequest(
|
||||
t,
|
||||
testServer.URL,
|
||||
user.Username,
|
||||
testPassword,
|
||||
)
|
||||
|
||||
var session domain.Session
|
||||
if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil {
|
||||
loginResponse.Body.Close()
|
||||
t.Fatalf("decode session: %v", err)
|
||||
}
|
||||
loginResponse.Body.Close()
|
||||
|
||||
time.Sleep(75 * time.Millisecond)
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
testServer.URL+"/api/v1/users/me",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create expired-token request: %v", err)
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send expired-token request: %v", err)
|
||||
}
|
||||
response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for expired token, got %d", response.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
func fetchCursorPage(
|
||||
t *testing.T,
|
||||
baseURL, chatID, userID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) domain.MessagePage {
|
||||
t.Helper()
|
||||
|
||||
endpoint := fmt.Sprintf(
|
||||
"%s/api/v1/chats/%s/messages?limit=%d",
|
||||
baseURL,
|
||||
chatID,
|
||||
limit,
|
||||
)
|
||||
if cursor != "" {
|
||||
endpoint += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("X-User-Id", userID)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
t.Fatalf("expected 200, got %d: %s", res.StatusCode, body)
|
||||
}
|
||||
|
||||
var page domain.MessagePage
|
||||
if err := json.NewDecoder(res.Body).Decode(&page); err != nil {
|
||||
t.Fatalf("decode message page: %v", err)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
func TestCursorTraversalAfterConcurrentWrites(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
const (
|
||||
clients = 10
|
||||
messagesPerClient = 100
|
||||
expectedMessages = clients * messagesPerClient
|
||||
)
|
||||
|
||||
memberIDs := make([]string, 0, clients)
|
||||
for client := 0; client < clients; client++ {
|
||||
user, err := st.CreateUser(
|
||||
fmt.Sprintf("cursor_client_%d", client),
|
||||
fmt.Sprintf("Cursor client %d", client),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
memberIDs = append(memberIDs, user.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Concurrent cursor test", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
var writers sync.WaitGroup
|
||||
for client := 0; client < clients; client++ {
|
||||
writers.Add(1)
|
||||
go func(client int) {
|
||||
defer writers.Done()
|
||||
<-start
|
||||
for message := 0; message < messagesPerClient; message++ {
|
||||
_, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[client],
|
||||
fmt.Sprintf("client=%d message=%d", client, message),
|
||||
)
|
||||
if err != nil {
|
||||
t.Errorf("create message: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}(client)
|
||||
}
|
||||
|
||||
close(start)
|
||||
writers.Wait()
|
||||
|
||||
seen := make(map[string]struct{}, expectedMessages)
|
||||
duplicateCount := 0
|
||||
var previous *domain.Message
|
||||
firstOrderingViolation := ""
|
||||
cursor := ""
|
||||
pageCount := 0
|
||||
|
||||
for {
|
||||
pageCount++
|
||||
if pageCount > expectedMessages {
|
||||
t.Fatal("pagination did not terminate")
|
||||
}
|
||||
|
||||
page := fetchCursorPage(t, ts.URL, chat.ID, memberIDs[0], 17, cursor)
|
||||
for index := range page.Items {
|
||||
message := page.Items[index]
|
||||
if _, duplicate := seen[message.ID]; duplicate {
|
||||
duplicateCount++
|
||||
}
|
||||
seen[message.ID] = struct{}{}
|
||||
|
||||
if previous != nil {
|
||||
outOfOrder := message.CreatedAt.Before(previous.CreatedAt) ||
|
||||
(message.CreatedAt.Equal(previous.CreatedAt) && message.ID <= previous.ID)
|
||||
if outOfOrder && firstOrderingViolation == "" {
|
||||
firstOrderingViolation = fmt.Sprintf(
|
||||
"previous=(%s,%s), current=(%s,%s)",
|
||||
previous.CreatedAt.Format("15:04:05.999999999"), previous.ID,
|
||||
message.CreatedAt.Format("15:04:05.999999999"), message.ID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
messageCopy := message
|
||||
previous = &messageCopy
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
|
||||
if len(seen) != expectedMessages || duplicateCount != 0 {
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d unique messages of %d and %d duplicates; first ordering violation: %s",
|
||||
len(seen), expectedMessages, duplicateCount, firstOrderingViolation,
|
||||
)
|
||||
}
|
||||
if firstOrderingViolation != "" {
|
||||
t.Fatalf("history is not ordered: %s", firstOrderingViolation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorTraversalDuringConcurrentWrites(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
const (
|
||||
clients = 16
|
||||
messagesPerClient = 100
|
||||
seedMessages = 100
|
||||
pageLimit = 7
|
||||
expectedTotal = seedMessages + clients*messagesPerClient
|
||||
)
|
||||
|
||||
memberIDs := make([]string, 0, clients)
|
||||
for client := 0; client < clients; client++ {
|
||||
user, err := st.CreateUser(
|
||||
fmt.Sprintf("live_cursor_client_%d", client),
|
||||
fmt.Sprintf("Live cursor client %d", client),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create user %d: %v", client, err)
|
||||
}
|
||||
memberIDs = append(memberIDs, user.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Live concurrent cursor test", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatalf("create chat: %v", err)
|
||||
}
|
||||
|
||||
// Начальные сообщения нужны, чтобы читатель сразу начал
|
||||
// двигать курсор, пока остальные сообщения ещё записываются.
|
||||
expectedIDs := make(map[string]struct{}, expectedTotal)
|
||||
for index := 0; index < seedMessages; index++ {
|
||||
message, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[0],
|
||||
fmt.Sprintf("seed message=%d", index),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create seed message %d: %v", index, err)
|
||||
}
|
||||
expectedIDs[message.ID] = struct{}{}
|
||||
}
|
||||
|
||||
var expectedMu sync.Mutex
|
||||
var writers sync.WaitGroup
|
||||
var ready sync.WaitGroup
|
||||
|
||||
start := make(chan struct{})
|
||||
writerErrors := make(chan error, clients)
|
||||
|
||||
for client := 0; client < clients; client++ {
|
||||
writers.Add(1)
|
||||
ready.Add(1)
|
||||
|
||||
go func(client int) {
|
||||
defer writers.Done()
|
||||
|
||||
ready.Done()
|
||||
<-start
|
||||
|
||||
for index := 0; index < messagesPerClient; index++ {
|
||||
// Отдаём планировщику возможность чаще переключать
|
||||
// конкурентные горутины.
|
||||
runtime.Gosched()
|
||||
|
||||
message, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[client],
|
||||
fmt.Sprintf("client=%d message=%d", client, index),
|
||||
)
|
||||
if err != nil {
|
||||
writerErrors <- fmt.Errorf(
|
||||
"client %d, message %d: %w",
|
||||
client,
|
||||
index,
|
||||
err,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
expectedMu.Lock()
|
||||
expectedIDs[message.ID] = struct{}{}
|
||||
expectedMu.Unlock()
|
||||
|
||||
// Не даём всем писателям завершиться до того,
|
||||
// как читатель успеет продвинуть курсор.
|
||||
time.Sleep(50 * time.Microsecond)
|
||||
}
|
||||
}(client)
|
||||
}
|
||||
|
||||
// Сначала убеждаемся, что все горутины готовы,
|
||||
// и только потом одновременно разрешаем запись.
|
||||
ready.Wait()
|
||||
|
||||
writersDone := make(chan struct{})
|
||||
go func() {
|
||||
writers.Wait()
|
||||
close(writersDone)
|
||||
}()
|
||||
|
||||
close(start)
|
||||
|
||||
seen := make(map[string]struct{}, expectedTotal)
|
||||
cursor := ""
|
||||
var previous *domain.Message
|
||||
|
||||
const maxPageRequests = expectedTotal * 4
|
||||
finished := false
|
||||
|
||||
for requestNumber := 0; requestNumber < maxPageRequests; requestNumber++ {
|
||||
page := fetchCursorPage(
|
||||
t,
|
||||
ts.URL,
|
||||
chat.ID,
|
||||
memberIDs[0],
|
||||
pageLimit,
|
||||
cursor,
|
||||
)
|
||||
|
||||
for index := range page.Items {
|
||||
message := page.Items[index]
|
||||
|
||||
if _, duplicate := seen[message.ID]; duplicate {
|
||||
t.Fatalf(
|
||||
"message %s was returned more than once",
|
||||
message.ID,
|
||||
)
|
||||
}
|
||||
|
||||
if previous != nil {
|
||||
outOfOrder :=
|
||||
message.CreatedAt.Before(previous.CreatedAt) ||
|
||||
(message.CreatedAt.Equal(previous.CreatedAt) &&
|
||||
message.ID <= previous.ID)
|
||||
|
||||
if outOfOrder {
|
||||
t.Fatalf(
|
||||
"messages are out of order: previous=(%s,%s), current=(%s,%s)",
|
||||
previous.CreatedAt.Format(time.RFC3339Nano),
|
||||
previous.ID,
|
||||
message.CreatedAt.Format(time.RFC3339Nano),
|
||||
message.ID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
seen[message.ID] = struct{}{}
|
||||
messageCopy := message
|
||||
previous = &messageCopy
|
||||
}
|
||||
|
||||
// Для продолжающегося чтения строим курсор по последнему
|
||||
// фактически полученному сообщению. Это позволяет опрашивать
|
||||
// историю, даже если в промежуточный момент сервер вернул
|
||||
// NextCursor=nil.
|
||||
if len(page.Items) > 0 {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
cursor = domain.EncodeCursor(
|
||||
last.CreatedAt,
|
||||
last.ID,
|
||||
chat.ID,
|
||||
)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-writersDone:
|
||||
finished = true
|
||||
default:
|
||||
}
|
||||
|
||||
// Все писатели завершились, а после текущего курсора
|
||||
// больше ничего нет: обход закончен.
|
||||
if finished && len(page.Items) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
if len(page.Items) == 0 {
|
||||
runtime.Gosched()
|
||||
}
|
||||
|
||||
if requestNumber == maxPageRequests-1 {
|
||||
t.Fatalf(
|
||||
"pagination did not terminate after %d requests",
|
||||
maxPageRequests,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
<-writersDone
|
||||
close(writerErrors)
|
||||
|
||||
for writerErr := range writerErrors {
|
||||
t.Errorf("create message: %v", writerErr)
|
||||
}
|
||||
|
||||
expectedMu.Lock()
|
||||
missingIDs := make([]string, 0)
|
||||
for id := range expectedIDs {
|
||||
if _, found := seen[id]; !found {
|
||||
missingIDs = append(missingIDs, id)
|
||||
}
|
||||
}
|
||||
expectedCount := len(expectedIDs)
|
||||
expectedMu.Unlock()
|
||||
|
||||
if expectedCount != expectedTotal {
|
||||
t.Fatalf(
|
||||
"writers confirmed %d messages, expected %d",
|
||||
expectedCount,
|
||||
expectedTotal,
|
||||
)
|
||||
}
|
||||
|
||||
if len(missingIDs) != 0 {
|
||||
const displayedMissingIDs = 5
|
||||
if len(missingIDs) > displayedMissingIDs {
|
||||
missingIDs = missingIDs[:displayedMissingIDs]
|
||||
}
|
||||
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d of %d confirmed messages; "+
|
||||
"examples of missing IDs: %v",
|
||||
len(seen),
|
||||
expectedTotal,
|
||||
missingIDs,
|
||||
)
|
||||
}
|
||||
|
||||
if len(seen) != expectedTotal {
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d messages, expected %d",
|
||||
len(seen),
|
||||
expectedTotal,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,649 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/handlers"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func requireLegacyAuth(
|
||||
memoryStore *store.MemoryStore,
|
||||
next http.HandlerFunc,
|
||||
) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
|
||||
user, err := memoryStore.GetUserByID(userID)
|
||||
if err != nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(
|
||||
r.Context(),
|
||||
middleware.UserContextKey,
|
||||
user,
|
||||
)
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// изолированный серв для тестов
|
||||
func setupTestServer() (*httptest.Server, *store.MemoryStore) {
|
||||
memoryStore := store.NewMemoryStore()
|
||||
repository := store.NewMemoryRepository(memoryStore)
|
||||
handler := handlers.NewHandler(repository)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/users/me",
|
||||
requireLegacyAuth(memoryStore, handler.GetMe),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats",
|
||||
requireLegacyAuth(memoryStore, handler.CreateChat),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats",
|
||||
requireLegacyAuth(memoryStore, handler.ListChats),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats/{chat_id}",
|
||||
requireLegacyAuth(memoryStore, handler.GetChat),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats/{chat_id}/messages",
|
||||
requireLegacyAuth(memoryStore, handler.CreateMessage),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats/{chat_id}/messages",
|
||||
requireLegacyAuth(memoryStore, handler.GetMessages),
|
||||
)
|
||||
|
||||
var root http.Handler = mux
|
||||
root = middleware.Recovery(root)
|
||||
root = middleware.RequestID(root)
|
||||
|
||||
return httptest.NewServer(root), memoryStore
|
||||
}
|
||||
|
||||
// 1 тест на дубликат username -> 409 Conflict
|
||||
func TestDuplicateUsername(t *testing.T) {
|
||||
ts, _ := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
body := `{
|
||||
"username":"bob_the_builder",
|
||||
"display_name":"Боб",
|
||||
"password":"Test-password-123"}`
|
||||
|
||||
// Первый раз — 201 Created
|
||||
res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body))
|
||||
if res1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// Второй раз тот же username — 409 Conflict
|
||||
res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body))
|
||||
if res2.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("expected 409 Conflict for duplicate username, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 2 тест на неверный JSON и лишние поля -> 400 Invalid Request
|
||||
func TestInvalidAndExtraJSON(t *testing.T) {
|
||||
ts, _ := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
// Кривой JSON (malformed)
|
||||
res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username": "bad"`))
|
||||
if res1.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for malformed json, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// Лишнее поле "age" (проверка DisallowUnknownFields)
|
||||
res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username":"valid_user","display_name":"User","age":25}`))
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for extra fields, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 3 тст на пустое сообщение и сообщение из одних пробелов -> 400 Invalid Request
|
||||
func TestEmptyMessageValidation(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("user_msg_test", "Tester")
|
||||
chat, _ := st.CreateChat("Test Chat", []string{u.ID})
|
||||
|
||||
// Пустой текст
|
||||
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":""}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", u.ID)
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for empty text, got %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// Текст только из пробелов
|
||||
reqSpaces, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":" "}`))
|
||||
reqSpaces.Header.Set("Content-Type", "application/json")
|
||||
reqSpaces.Header.Set("X-User-Id", u.ID)
|
||||
|
||||
resSpaces, _ := http.DefaultClient.Do(reqSpaces)
|
||||
if resSpaces.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for whitespace-only text, got %d", resSpaces.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 4 тест: чужой чат для постороннего -> 404 Not Found (не 403!)
|
||||
func TestOutsiderChatAccess(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
alice, _ := st.CreateUser("alice_secret", "Алиса")
|
||||
eve, _ := st.CreateUser("eve_eavesdropper", "Ева")
|
||||
|
||||
chat, _ := st.CreateChat("Секретный чат", []string{alice.ID})
|
||||
|
||||
// Ева пытается прочитать чат Алисы
|
||||
req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/chats/%s", ts.URL, chat.ID), nil)
|
||||
req.Header.Set("X-User-Id", eve.ID)
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
if res.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 Not Found (no leak via 403), got %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 5 Тест: пагинация по нескольким страницам с курсором
|
||||
func TestCursorPaginationMultiplePages(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("paging_user", "Пейджер")
|
||||
chat, _ := st.CreateChat("Чат пагинации", []string{u.ID})
|
||||
|
||||
// Отправляем 5 сообщений
|
||||
for i := 1; i <= 5; i++ {
|
||||
st.CreateMessage(chat.ID, u.ID, fmt.Sprintf("Message %d", i))
|
||||
}
|
||||
|
||||
// Запрашиваем порциями по limit=2
|
||||
var allReceived []string
|
||||
cursor := ""
|
||||
|
||||
for {
|
||||
url := fmt.Sprintf("%s/api/v1/chats/%s/messages?limit=2", ts.URL, chat.ID)
|
||||
if cursor != "" {
|
||||
url += "&cursor=" + cursor
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, url, nil)
|
||||
req.Header.Set("X-User-Id", u.ID)
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
|
||||
var page domain.MessagePage
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
json.Unmarshal(body, &page)
|
||||
res.Body.Close()
|
||||
|
||||
for _, m := range page.Items {
|
||||
allReceived = append(allReceived, m.Text)
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
|
||||
if len(allReceived) != 5 {
|
||||
t.Fatalf("expected 5 messages total across pages, got %d", len(allReceived))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCursorPaginationMultiplePages(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
user, err := st.CreateUser("chat_paging_user", "Пейджер чатов")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create user: %v", err)
|
||||
}
|
||||
|
||||
outsider, err := st.CreateUser("chat_paging_outsider", "Посторонний")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create outsider: %v", err)
|
||||
}
|
||||
|
||||
createdChats := make([]domain.Chat, 0, 5)
|
||||
|
||||
for i := 1; i <= 5; i++ {
|
||||
chat, createErr := st.CreateChat(
|
||||
fmt.Sprintf("Chat %d", i),
|
||||
[]string{user.ID},
|
||||
)
|
||||
if createErr != nil {
|
||||
t.Fatalf("failed to create chat %d: %v", i, createErr)
|
||||
}
|
||||
|
||||
createdChats = append(createdChats, chat)
|
||||
|
||||
// Чужой чат создаётся между доступными чатами и не должен
|
||||
// влиять на размер страницы или next_cursor пользователя.
|
||||
if i == 3 {
|
||||
if _, createErr = st.CreateChat(
|
||||
"Outsider chat",
|
||||
[]string{outsider.ID},
|
||||
); createErr != nil {
|
||||
t.Fatalf("failed to create outsider chat: %v", createErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(createdChats, func(i, j int) bool {
|
||||
if createdChats[i].CreatedAt.Equal(createdChats[j].CreatedAt) {
|
||||
return createdChats[i].ID < createdChats[j].ID
|
||||
}
|
||||
|
||||
return createdChats[i].CreatedAt.Before(createdChats[j].CreatedAt)
|
||||
})
|
||||
|
||||
var receivedIDs []string
|
||||
seenIDs := make(map[string]bool)
|
||||
seenCursors := make(map[string]bool)
|
||||
cursor := ""
|
||||
finished := false
|
||||
|
||||
for pageNumber := 1; pageNumber <= 10; pageNumber++ {
|
||||
requestURL := ts.URL + "/api/v1/chats?limit=2"
|
||||
if cursor != "" {
|
||||
requestURL += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, requestURL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("X-User-Id", user.ID)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list chats: %v", err)
|
||||
}
|
||||
|
||||
var page domain.ChatPage
|
||||
decodeErr := json.NewDecoder(res.Body).Decode(&page)
|
||||
res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", res.StatusCode)
|
||||
}
|
||||
if decodeErr != nil {
|
||||
t.Fatalf("failed to decode chat page: %v", decodeErr)
|
||||
}
|
||||
if len(page.Items) > 2 {
|
||||
t.Fatalf("page contains %d chats with limit=2", len(page.Items))
|
||||
}
|
||||
|
||||
for _, chat := range page.Items {
|
||||
if seenIDs[chat.ID] {
|
||||
t.Fatalf("chat %s was returned more than once", chat.ID)
|
||||
}
|
||||
|
||||
seenIDs[chat.ID] = true
|
||||
receivedIDs = append(receivedIDs, chat.ID)
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
finished = true
|
||||
break
|
||||
}
|
||||
|
||||
if seenCursors[*page.NextCursor] {
|
||||
t.Fatalf("cursor cycle detected")
|
||||
}
|
||||
|
||||
seenCursors[*page.NextCursor] = true
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
|
||||
if !finished {
|
||||
t.Fatal("chat pagination did not finish")
|
||||
}
|
||||
|
||||
if len(receivedIDs) != len(createdChats) {
|
||||
t.Fatalf(
|
||||
"expected %d chats across all pages, got %d",
|
||||
len(createdChats),
|
||||
len(receivedIDs),
|
||||
)
|
||||
}
|
||||
|
||||
for i, chat := range createdChats {
|
||||
if receivedIDs[i] != chat.ID {
|
||||
t.Fatalf(
|
||||
"chat order differs at position %d: expected %s, got %s",
|
||||
i,
|
||||
chat.ID,
|
||||
receivedIDs[i],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCursorValidation(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
alice, err := st.CreateUser("chat_cursor_alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create Alice: %v", err)
|
||||
}
|
||||
|
||||
bob, err := st.CreateUser("chat_cursor_bob", "Боб")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create Bob: %v", err)
|
||||
}
|
||||
|
||||
for i := 1; i <= 2; i++ {
|
||||
if _, err = st.CreateChat(
|
||||
fmt.Sprintf("Alice chat %d", i),
|
||||
[]string{alice.ID},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to create Alice chat: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err = st.CreateChat("Bob chat", []string{bob.ID}); err != nil {
|
||||
t.Fatalf("failed to create Bob chat: %v", err)
|
||||
}
|
||||
|
||||
firstRequest, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
ts.URL+"/api/v1/chats?limit=1",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create first request: %v", err)
|
||||
}
|
||||
firstRequest.Header.Set("X-User-Id", alice.ID)
|
||||
|
||||
firstResponse, err := http.DefaultClient.Do(firstRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to request first page: %v", err)
|
||||
}
|
||||
|
||||
var firstPage domain.ChatPage
|
||||
decodeErr := json.NewDecoder(firstResponse.Body).Decode(&firstPage)
|
||||
firstResponse.Body.Close()
|
||||
|
||||
if firstResponse.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected first page status 200, got %d", firstResponse.StatusCode)
|
||||
}
|
||||
if decodeErr != nil {
|
||||
t.Fatalf("failed to decode first page: %v", decodeErr)
|
||||
}
|
||||
if firstPage.NextCursor == nil {
|
||||
t.Fatal("expected next_cursor for Alice")
|
||||
}
|
||||
|
||||
foreignRequest, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
ts.URL+"/api/v1/chats?limit=1&cursor="+
|
||||
url.QueryEscape(*firstPage.NextCursor),
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create foreign cursor request: %v", err)
|
||||
}
|
||||
foreignRequest.Header.Set("X-User-Id", bob.ID)
|
||||
|
||||
foreignResponse, err := http.DefaultClient.Do(foreignRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to send foreign cursor request: %v", err)
|
||||
}
|
||||
foreignResponse.Body.Close()
|
||||
|
||||
if foreignResponse.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf(
|
||||
"expected 400 for another user's cursor, got %d",
|
||||
foreignResponse.StatusCode,
|
||||
)
|
||||
}
|
||||
|
||||
malformedRequest, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
ts.URL+"/api/v1/chats?cursor=not-valid-base64!",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create malformed cursor request: %v", err)
|
||||
}
|
||||
malformedRequest.Header.Set("X-User-Id", alice.ID)
|
||||
|
||||
malformedResponse, err := http.DefaultClient.Do(malformedRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to send malformed cursor request: %v", err)
|
||||
}
|
||||
malformedResponse.Body.Close()
|
||||
|
||||
if malformedResponse.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf(
|
||||
"expected 400 for malformed cursor, got %d",
|
||||
malformedResponse.StatusCode,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 6 тест: 100 сообщений от 10 клиентов одновременно, защита от гонок
|
||||
func TestConcurrent100MessagesFrom10Clients(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
// Создаем 10 пользователей
|
||||
var memberIDs []string
|
||||
for i := 0; i < 10; i++ {
|
||||
u, _ := st.CreateUser(fmt.Sprintf("client_%d", i), fmt.Sprintf("Client %d", i))
|
||||
memberIDs = append(memberIDs, u.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Highload Chat", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create chat: %v", err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
totalClients := 10
|
||||
messagesPerClient := 10
|
||||
|
||||
for i := 0; i < totalClients; i++ {
|
||||
wg.Add(1)
|
||||
clientID := memberIDs[i]
|
||||
|
||||
go func(senderID string, clientIndex int) {
|
||||
defer wg.Done()
|
||||
|
||||
for m := 0; m < messagesPerClient; m++ {
|
||||
text := fmt.Sprintf("Client %d - Message %d", clientIndex, m)
|
||||
payload := fmt.Sprintf(`{"text":"%s"}`, text)
|
||||
|
||||
req, _ := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID),
|
||||
bytes.NewBufferString(payload),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", senderID)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil || res.StatusCode != http.StatusCreated {
|
||||
t.Errorf("failed to send concurrent message: %v", err)
|
||||
}
|
||||
if res != nil {
|
||||
res.Body.Close()
|
||||
}
|
||||
}
|
||||
}(clientID, i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// должно быть 100 сообщений в чате
|
||||
page, err := st.GetMessages(chat.ID, memberIDs[0], 200, "")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get messages: %v", err)
|
||||
}
|
||||
|
||||
if len(page.Items) != 100 {
|
||||
t.Fatalf("RACE CONDITION DETECTED: expected exactly 100 messages, got %d", len(page.Items))
|
||||
}
|
||||
|
||||
// уникальность ID
|
||||
seenIDs := make(map[string]bool)
|
||||
for _, m := range page.Items {
|
||||
if seenIDs[m.ID] {
|
||||
t.Fatalf("duplicate message ID found: %s", m.ID)
|
||||
}
|
||||
seenIDs[m.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
// 7 тест: защита от подделки курсора (чужой чат или битый Base64) -> 400
|
||||
func TestForeignAndMalformedCursor(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("cursor_tester", "Tester")
|
||||
chatA, _ := st.CreateChat("Chat A", []string{u.ID})
|
||||
chatB, _ := st.CreateChat("Chat B", []string{u.ID})
|
||||
|
||||
// В Чат А кладем несколько сообщений, чтобы при limit=1 появился NextCursor
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 1 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 2 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 3 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 4 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 5 in A")
|
||||
|
||||
st.CreateMessage(chatB.ID, u.ID, "Message 1 in B")
|
||||
st.CreateMessage(chatB.ID, u.ID, "Message 2 in B")
|
||||
|
||||
// Получаем валидный курсор из Чата А (запрашиваем 1 из 2)
|
||||
pageA, err := st.GetMessages(chatA.ID, u.ID, 1, "")
|
||||
if err != nil || pageA.NextCursor == nil {
|
||||
t.Fatalf("expected next_cursor in Chat A, err: %v", err)
|
||||
}
|
||||
|
||||
// 1. Пытаемся применить курсор от Чата А к Чату Б -> строго 400!
|
||||
urlForeign := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=%s", ts.URL, chatB.ID, *pageA.NextCursor)
|
||||
reqForeign, _ := http.NewRequest(http.MethodGet, urlForeign, nil)
|
||||
reqForeign.Header.Set("X-User-Id", u.ID)
|
||||
resForeign, _ := http.DefaultClient.Do(reqForeign)
|
||||
|
||||
if resForeign.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for foreign chat cursor, got %d", resForeign.StatusCode)
|
||||
}
|
||||
|
||||
// 2. Битый (невалидный) Base64 -> 400
|
||||
urlBad := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=not-a-valid-base64!@#", ts.URL, chatB.ID)
|
||||
reqBad, _ := http.NewRequest(http.MethodGet, urlBad, nil)
|
||||
reqBad.Header.Set("X-User-Id", u.ID)
|
||||
resBad, _ := http.DefaultClient.Do(reqBad)
|
||||
|
||||
if resBad.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for malformed cursor, got %d", resBad.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 8 тест валидации создания чата (создателя нет в списке / несуществующий юзер / дубликат) -> 400
|
||||
func TestChatCreationValidation(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
alice, _ := st.CreateUser("alice_chat_val", "Alice")
|
||||
bob, _ := st.CreateUser("bob_chat_val", "Bob")
|
||||
|
||||
// 1. Создатель (Alice) забыла добавить себя в member_ids
|
||||
bodyNoCaller := fmt.Sprintf(`{"title":"No Caller Chat","member_ids":["%s"]}`, bob.ID)
|
||||
req1, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyNoCaller))
|
||||
req1.Header.Set("Content-Type", "application/json")
|
||||
req1.Header.Set("X-User-Id", alice.ID)
|
||||
res1, _ := http.DefaultClient.Do(req1)
|
||||
if res1.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 when caller is not in member_ids, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// 2. В участниках передан несуществующий UUID
|
||||
bodyFakeUser := fmt.Sprintf(`{"title":"Fake User Chat","member_ids":["%s","00000000-0000-0000-0000-000000000000"]}`, alice.ID)
|
||||
req2, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyFakeUser))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
req2.Header.Set("X-User-Id", alice.ID)
|
||||
res2, _ := http.DefaultClient.Do(req2)
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for non-existent member_id, got %d", res2.StatusCode)
|
||||
}
|
||||
|
||||
// 3. Дубликат участника в списке
|
||||
bodyDuplicate := fmt.Sprintf(`{"title":"Duplicate Member","member_ids":["%s","%s"]}`, alice.ID, alice.ID)
|
||||
req3, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyDuplicate))
|
||||
req3.Header.Set("Content-Type", "application/json")
|
||||
req3.Header.Set("X-User-Id", alice.ID)
|
||||
res3, _ := http.DefaultClient.Do(req3)
|
||||
if res3.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for duplicate member_ids, got %d", res3.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 9 тест лимитов символов Unicode (длина до 4000 рун и отказ при >4000)
|
||||
func TestUnicodeLimits(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("unicode_master", "Иван 🚀")
|
||||
chat, _ := st.CreateChat("Unicode Chat", []string{u.ID})
|
||||
|
||||
// Ровно 4000 смайликов (в байтах это 16000 байт, но в рунах — ровно 4000!)
|
||||
validRunes := make([]rune, 4000)
|
||||
for i := range validRunes {
|
||||
validRunes[i] = '🔥'
|
||||
}
|
||||
bodyValid := fmt.Sprintf(`{"text":"%s"}`, string(validRunes))
|
||||
req1, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyValid))
|
||||
req1.Header.Set("Content-Type", "application/json")
|
||||
req1.Header.Set("X-User-Id", u.ID)
|
||||
res1, _ := http.DefaultClient.Do(req1)
|
||||
if res1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201 for 4000 unicode runes, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// 4001 символ -> строго 400 Invalid Request!
|
||||
tooLongRunes := make([]rune, 4001)
|
||||
for i := range tooLongRunes {
|
||||
tooLongRunes[i] = 'a'
|
||||
}
|
||||
bodyTooLong := fmt.Sprintf(`{"text":"%s"}`, string(tooLongRunes))
|
||||
req2, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyTooLong))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
req2.Header.Set("X-User-Id", u.ID)
|
||||
res2, _ := http.DefaultClient.Do(req2)
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for 4001 runes, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type contractErrorResponse struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
func requireContractError(
|
||||
t *testing.T,
|
||||
response *http.Response,
|
||||
wantStatus int,
|
||||
wantCode string,
|
||||
) {
|
||||
t.Helper()
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != wantStatus {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf(
|
||||
"expected status %d, got %d: %s",
|
||||
wantStatus,
|
||||
response.StatusCode,
|
||||
body,
|
||||
)
|
||||
}
|
||||
|
||||
requestID := response.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
t.Fatal("error response has no X-Request-Id")
|
||||
}
|
||||
if contentType := response.Header.Get("Content-Type"); contentType != "application/json; charset=utf-8" {
|
||||
t.Fatalf("unexpected error Content-Type: %q", contentType)
|
||||
}
|
||||
|
||||
var payload contractErrorResponse
|
||||
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
|
||||
t.Fatalf("decode error response: %v", err)
|
||||
}
|
||||
if payload.Error.Code != wantCode {
|
||||
t.Fatalf(
|
||||
"expected error code %q, got %q",
|
||||
wantCode,
|
||||
payload.Error.Code,
|
||||
)
|
||||
}
|
||||
if payload.Error.Message == "" {
|
||||
t.Fatal("error response has an empty message")
|
||||
}
|
||||
if payload.Error.RequestID != requestID {
|
||||
t.Fatal("body request_id differs from X-Request-Id")
|
||||
}
|
||||
}
|
||||
|
||||
func sendRegistration(
|
||||
t *testing.T,
|
||||
baseURL string,
|
||||
contentType string,
|
||||
body []byte,
|
||||
) *http.Response {
|
||||
t.Helper()
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
baseURL+"/api/v1/users",
|
||||
bytes.NewReader(body),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create registration request: %v", err)
|
||||
}
|
||||
if contentType != "" {
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send registration request: %v", err)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func TestJSONRequestRequiresApplicationJSON(t *testing.T) {
|
||||
testServer, _ := setupTestServer()
|
||||
defer testServer.Close()
|
||||
|
||||
body := []byte(
|
||||
`{"username":"mime_probe","display_name":"Test",` +
|
||||
`"password":"123456789012"}`,
|
||||
)
|
||||
|
||||
for _, contentType := range []string{
|
||||
"",
|
||||
"text/plain",
|
||||
"application/xml",
|
||||
"application/json; charset=iso-8859-1",
|
||||
} {
|
||||
contentType := contentType
|
||||
t.Run(contentType, func(t *testing.T) {
|
||||
response := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
contentType,
|
||||
body,
|
||||
)
|
||||
requireContractError(
|
||||
t,
|
||||
response,
|
||||
http.StatusUnsupportedMediaType,
|
||||
"unsupported_media_type",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
response := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
"application/json; charset=UTF-8",
|
||||
body,
|
||||
)
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
responseBody, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf(
|
||||
"expected application/json with UTF-8 charset to be accepted, "+
|
||||
"got %d: %s",
|
||||
response.StatusCode,
|
||||
responseBody,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONRequestRejectsInvalidUTF8WithoutMutation(t *testing.T) {
|
||||
testServer, _ := setupTestServer()
|
||||
defer testServer.Close()
|
||||
|
||||
body := append(
|
||||
[]byte(
|
||||
`{"username":"utf8_probe","display_name":"Test",`+
|
||||
`"password":"12345678901`,
|
||||
),
|
||||
0xff,
|
||||
)
|
||||
body = append(body, []byte(`"}`)...)
|
||||
|
||||
response := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
"application/json",
|
||||
body,
|
||||
)
|
||||
requireContractError(
|
||||
t,
|
||||
response,
|
||||
http.StatusBadRequest,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
validBody := []byte(
|
||||
`{"username":"utf8_probe","display_name":"Test",` +
|
||||
`"password":"12345678901�"}`,
|
||||
)
|
||||
validResponse := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
"application/json",
|
||||
validBody,
|
||||
)
|
||||
defer validResponse.Body.Close()
|
||||
if validResponse.StatusCode != http.StatusCreated {
|
||||
responseBody, _ := io.ReadAll(validResponse.Body)
|
||||
t.Fatalf(
|
||||
"invalid UTF-8 request mutated storage; expected subsequent "+
|
||||
"valid registration 201, got %d: %s",
|
||||
validResponse.StatusCode,
|
||||
responseBody,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONRequestRejectsOversizedBody(t *testing.T) {
|
||||
testServer, _ := setupTestServer()
|
||||
defer testServer.Close()
|
||||
|
||||
response := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
"application/json",
|
||||
bytes.Repeat([]byte(" "), (1<<20)+1),
|
||||
)
|
||||
requireContractError(
|
||||
t,
|
||||
response,
|
||||
http.StatusRequestEntityTooLarge,
|
||||
"payload_too_large",
|
||||
)
|
||||
}
|
||||
|
||||
func TestBasicAuthRejectsInvalidUTF8(t *testing.T) {
|
||||
testServer, _ := setupSessionTestServer(t, 0)
|
||||
defer testServer.Close()
|
||||
|
||||
credentials := append([]byte("unknown:"), 0xff)
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
testServer.URL+"/api/v1/auth/sessions",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create session request: %v", err)
|
||||
}
|
||||
request.Header.Set(
|
||||
"Authorization",
|
||||
"Basic "+base64.StdEncoding.EncodeToString(credentials),
|
||||
)
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send session request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusUnauthorized {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf(
|
||||
"expected invalid UTF-8 Basic credentials to return 401, "+
|
||||
"got %d: %s",
|
||||
response.StatusCode,
|
||||
body,
|
||||
)
|
||||
}
|
||||
if got := response.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("unexpected Basic challenge: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,19 @@ python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json
|
||||
|
||||
Это простой **closed-loop** генератор POST сообщений; он ограничен производительностью клиента и страдает coordinated omission. Он выдаёт successful RPS, ошибки и p50/p95/p99 **только успешных запросов**. Во время нагрузки нет прозрачных retry; timeout мог скрыть совершённую запись, поэтому это throughput HTTP-подтверждений, не точный счётчик COMMIT. Изменение размера истории входит в профиль. Для серьёзного исследования используйте k6/Locust/wrk либо свой обоснованный генератор, а не выводите максимальную пропускную способность из одного запуска этого скрипта. Для нагрузки pipeline изображений нужен отдельный сценарий студента.
|
||||
|
||||
## Track 2: 100 000 сообщений и восстановление
|
||||
|
||||
```sh
|
||||
make test-track2
|
||||
```
|
||||
|
||||
Сценарий создаёт временную БД на реальной миграции, сравнивает keyset,
|
||||
`OFFSET 50000` и покрывающий индекс через `EXPLAIN (ANALYZE, BUFFERS, WAL)`,
|
||||
затем делает `pg_dump` и восстанавливает его в отдельный PostgreSQL volume.
|
||||
Source/restored fingerprint включает counts, распределение, индексы и три
|
||||
выбранных сообщения. Временные БД и dump удаляются автоматически; рабочая БД
|
||||
API не изменяется. Методика и ограничения: `docs/track2.md`.
|
||||
|
||||
## HTTPS, lab7
|
||||
|
||||
```sh
|
||||
|
||||
Executable
+105
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify that Redis outage degrades to PostgreSQL without bypassing auth."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def execute_hook(script, action):
|
||||
env = dict(os.environ)
|
||||
env['CACHE_ACTION'] = action
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[str(script)],
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=90,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure('Redis outage hook exceeded 90 seconds') from None
|
||||
check(result.returncode == 0, 'Redis outage hook failed for action ' + action)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument(
|
||||
'--action-script',
|
||||
required=True,
|
||||
help='Executable student hook controlled by CACHE_ACTION=stop|start',
|
||||
)
|
||||
|
||||
args = arguments(
|
||||
'Redis failure scenario; creates only synthetic API data',
|
||||
configure,
|
||||
)
|
||||
script = Path(args.action_script).expanduser().resolve()
|
||||
check(
|
||||
script.is_file() and os.access(script, os.X_OK),
|
||||
'action script must exist and be executable (chmod +x)',
|
||||
)
|
||||
|
||||
client = Client(args.base_url, args.ca_file, timeout=3)
|
||||
alice, bob, _, original_chat = client.bootstrap()
|
||||
path = '/api/v1/chats/' + original_chat['id']
|
||||
|
||||
warmed = client.call(
|
||||
'GET',
|
||||
path,
|
||||
actor=bob,
|
||||
schema='Chat',
|
||||
)['json']
|
||||
check(warmed == original_chat, 'warm read changed chat data')
|
||||
|
||||
print('Stopping only Redis; hook output is suppressed.')
|
||||
execute_hook(script, 'stop')
|
||||
|
||||
created_during_outage = None
|
||||
try:
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
|
||||
fallback = client.call(
|
||||
'GET',
|
||||
path,
|
||||
actor=bob,
|
||||
schema='Chat',
|
||||
)['json']
|
||||
check(fallback == original_chat, 'PostgreSQL fallback changed chat data')
|
||||
|
||||
created_during_outage = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
201,
|
||||
actor=alice,
|
||||
body={
|
||||
'title': 'Redis outage ' + uuid.uuid4().hex[:8],
|
||||
'member_ids': [alice['id'], bob['id']],
|
||||
},
|
||||
schema='Chat',
|
||||
)['json']
|
||||
|
||||
client.call('GET', path, 401, actor={'id': 'unused', 'token': 'invalid'})
|
||||
finally:
|
||||
execute_hook(script, 'start')
|
||||
|
||||
check(created_during_outage is not None, 'chat was not created during outage')
|
||||
recovered = client.call(
|
||||
'GET',
|
||||
'/api/v1/chats/' + created_during_outage['id'],
|
||||
actor=bob,
|
||||
schema='Chat',
|
||||
)['json']
|
||||
check(recovered == created_during_outage, 'cache recovery changed chat data')
|
||||
|
||||
print(
|
||||
'PASS: Redis outage used PostgreSQL fallback; readiness, session, '
|
||||
'authorization and writes remained correct.'
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+120
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify bounded behavior while mandatory PostgreSQL is unavailable."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def execute_hook(script, action):
|
||||
env = dict(os.environ)
|
||||
env['DATABASE_ACTION'] = action
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[str(script)],
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=90,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure('PostgreSQL outage hook exceeded 90 seconds') from None
|
||||
check(
|
||||
result.returncode == 0,
|
||||
'PostgreSQL outage hook failed for action ' + action,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument(
|
||||
'--action-script',
|
||||
required=True,
|
||||
help='Executable hook controlled by DATABASE_ACTION=stop|start',
|
||||
)
|
||||
|
||||
args = arguments(
|
||||
'PostgreSQL failure scenario; creates only synthetic API data',
|
||||
configure,
|
||||
)
|
||||
script = Path(args.action_script).expanduser().resolve()
|
||||
check(
|
||||
script.is_file() and os.access(script, os.X_OK),
|
||||
'action script must exist and be executable (chmod +x)',
|
||||
)
|
||||
|
||||
client = Client(args.base_url, args.ca_file, timeout=8)
|
||||
alice, _, _, _ = client.bootstrap()
|
||||
|
||||
print('Stopping only PostgreSQL; hook output is suppressed.')
|
||||
execute_hook(script, 'stop')
|
||||
try:
|
||||
client.call('GET', '/health/live', schema='Health')
|
||||
readiness = client.call('GET', '/health/ready', 503)
|
||||
check(
|
||||
readiness['json']['error']['code'] == 'unavailable',
|
||||
'readiness did not return a bounded unavailable error',
|
||||
)
|
||||
|
||||
client.call('GET', '/api/v1/users/me', 401)
|
||||
authenticated = client.call(
|
||||
'GET',
|
||||
'/api/v1/users/me',
|
||||
503,
|
||||
actor=alice,
|
||||
)
|
||||
check(
|
||||
authenticated['json']['error']['code'] == 'unavailable',
|
||||
'database auth failure did not return unavailable',
|
||||
)
|
||||
|
||||
registration = client.call(
|
||||
'POST',
|
||||
'/api/v1/users',
|
||||
503,
|
||||
body={
|
||||
'username': 'db_down_' + uuid.uuid4().hex[:16],
|
||||
'display_name': 'Database outage',
|
||||
'password': 'T3st-' + uuid.uuid4().hex,
|
||||
},
|
||||
)
|
||||
check(
|
||||
registration['json']['error']['code'] == 'unavailable',
|
||||
'write during database outage did not return unavailable',
|
||||
)
|
||||
finally:
|
||||
execute_hook(script, 'start')
|
||||
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
try:
|
||||
recovered = client.call(
|
||||
'GET',
|
||||
'/api/v1/users/me',
|
||||
actor=alice,
|
||||
schema='User',
|
||||
)['json']
|
||||
break
|
||||
except Failure:
|
||||
check(
|
||||
time.monotonic() < deadline,
|
||||
'PostgreSQL pool did not recover within 20 seconds',
|
||||
)
|
||||
time.sleep(0.5)
|
||||
|
||||
check(
|
||||
recovered['id'] == alice['id'],
|
||||
'existing session changed after PostgreSQL recovery',
|
||||
)
|
||||
print(
|
||||
'PASS: PostgreSQL outage returned bounded 503 responses, '
|
||||
'anonymous access stayed rejected, and the existing session recovered.'
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+114
@@ -0,0 +1,114 @@
|
||||
\set ON_ERROR_STOP on
|
||||
\pset pager off
|
||||
|
||||
BEGIN;
|
||||
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES (
|
||||
'00000000-0000-4000-8000-000000000041',
|
||||
'level4_explain_user',
|
||||
'Level 4 EXPLAIN user',
|
||||
'synthetic-not-a-login-hash'
|
||||
);
|
||||
|
||||
INSERT INTO chats (
|
||||
id,
|
||||
title
|
||||
)
|
||||
VALUES (
|
||||
'00000000-0000-4000-8000-000000000042',
|
||||
'Level 4 EXPLAIN chat'
|
||||
);
|
||||
|
||||
INSERT INTO chat_members (
|
||||
chat_id,
|
||||
user_id,
|
||||
position
|
||||
)
|
||||
VALUES (
|
||||
'00000000-0000-4000-8000-000000000042',
|
||||
'00000000-0000-4000-8000-000000000041',
|
||||
0
|
||||
);
|
||||
|
||||
WITH generated AS (
|
||||
SELECT
|
||||
number,
|
||||
md5('level4-message-' || number::text) AS digest
|
||||
FROM generate_series(1, 10000) AS series(number)
|
||||
)
|
||||
INSERT INTO messages (
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
(
|
||||
substr(digest, 1, 8) || '-' ||
|
||||
substr(digest, 9, 4) || '-4' ||
|
||||
substr(digest, 14, 3) || '-a' ||
|
||||
substr(digest, 18, 3) || '-' ||
|
||||
substr(digest, 21, 12)
|
||||
)::uuid,
|
||||
'00000000-0000-4000-8000-000000000042',
|
||||
'00000000-0000-4000-8000-000000000041',
|
||||
'Synthetic history message ' || number,
|
||||
TIMESTAMPTZ '2026-01-01 00:00:00+00'
|
||||
+ number * INTERVAL '1 microsecond'
|
||||
FROM generated;
|
||||
|
||||
ANALYZE messages;
|
||||
|
||||
\echo 'Synthetic message count (must be 10000):'
|
||||
SELECT count(*) AS synthetic_message_count
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000042';
|
||||
|
||||
\echo 'First page plan:'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000042'
|
||||
ORDER BY created_at, id
|
||||
LIMIT 101;
|
||||
|
||||
SELECT
|
||||
id AS cursor_id,
|
||||
created_at AS cursor_created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000042'
|
||||
ORDER BY created_at, id
|
||||
OFFSET 4999
|
||||
LIMIT 1
|
||||
\gset
|
||||
|
||||
\echo 'Page after cursor plan:'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000042'
|
||||
AND (created_at, id) > (
|
||||
:'cursor_created_at'::timestamptz,
|
||||
:'cursor_id'::uuid
|
||||
)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 101;
|
||||
|
||||
ROLLBACK;
|
||||
Executable
+130
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify PostgreSQL uniqueness and atomic chat creation through the public API."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import uuid
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def register_same_user(base_url, ca_file, body):
|
||||
client = Client(base_url, ca_file, timeout=15)
|
||||
return client.call(
|
||||
'POST',
|
||||
'/api/v1/users',
|
||||
[201, 409],
|
||||
body=body,
|
||||
schema='User',
|
||||
)
|
||||
|
||||
|
||||
def login(client, registration):
|
||||
credential = base64.b64encode(
|
||||
(
|
||||
registration['username']
|
||||
+ ':'
|
||||
+ registration['password']
|
||||
).encode()
|
||||
).decode()
|
||||
session = client.call(
|
||||
'POST',
|
||||
'/api/v1/auth/sessions',
|
||||
201,
|
||||
headers={'Authorization': 'Basic ' + credential},
|
||||
schema='Session',
|
||||
)['json']
|
||||
return {
|
||||
'id': session['user']['id'],
|
||||
'user': session['user'],
|
||||
'registration': registration,
|
||||
'token': session['token'],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(
|
||||
'Level 4 PostgreSQL race and transaction checks; creates synthetic data'
|
||||
)
|
||||
client = Client(args.base_url, args.ca_file, timeout=15)
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
|
||||
registration = {
|
||||
'username': 'race_' + uuid.uuid4().hex[:16],
|
||||
'display_name': 'Concurrent registration',
|
||||
'password': 'T3st-' + uuid.uuid4().hex,
|
||||
}
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as executor:
|
||||
futures = [
|
||||
executor.submit(
|
||||
register_same_user,
|
||||
args.base_url,
|
||||
args.ca_file,
|
||||
registration,
|
||||
)
|
||||
for _ in range(4)
|
||||
]
|
||||
results = [future.result() for future in futures]
|
||||
|
||||
statuses = [result['status'] for result in results]
|
||||
check(
|
||||
statuses.count(201) == 1 and statuses.count(409) == 3,
|
||||
'concurrent duplicate registration must yield one 201 and three 409 responses',
|
||||
)
|
||||
|
||||
actor = login(client, registration)
|
||||
before = client.call(
|
||||
'GET',
|
||||
'/api/v1/chats?limit=100',
|
||||
actor=actor,
|
||||
schema='ChatPage',
|
||||
)['json']
|
||||
check(not before['items'], 'new race-test user unexpectedly has chats')
|
||||
|
||||
failed_title = 'Rollback proof ' + uuid.uuid4().hex[:8]
|
||||
client.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
400,
|
||||
actor=actor,
|
||||
body={
|
||||
'title': failed_title,
|
||||
'member_ids': [actor['id'], str(uuid.uuid4())],
|
||||
},
|
||||
)
|
||||
|
||||
after = client.call(
|
||||
'GET',
|
||||
'/api/v1/chats?limit=100',
|
||||
actor=actor,
|
||||
schema='ChatPage',
|
||||
)['json']
|
||||
check(
|
||||
not after['items'],
|
||||
'failed composite chat creation left visible partial data',
|
||||
)
|
||||
|
||||
successful = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
201,
|
||||
actor=actor,
|
||||
body={
|
||||
'title': 'After rollback ' + uuid.uuid4().hex[:8],
|
||||
'member_ids': [actor['id']],
|
||||
},
|
||||
schema='Chat',
|
||||
)['json']
|
||||
check(
|
||||
successful['member_ids'] == [actor['id']],
|
||||
'connection did not recover after rolled-back transaction',
|
||||
)
|
||||
|
||||
print(
|
||||
'PASS: concurrent username race produced one winner; '
|
||||
'failed composite chat creation rolled back and the connection remained usable.'
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify deployed short session TTL, wrong password and logout."""
|
||||
import base64
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def execute_hook(script, action, ttl_seconds):
|
||||
env = dict(os.environ)
|
||||
env['SESSION_TTL_ACTION'] = action
|
||||
env['SHORT_SESSION_TTL_SECONDS'] = str(ttl_seconds)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[str(script)],
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=90,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure('session TTL hook exceeded 90 seconds') from None
|
||||
check(
|
||||
result.returncode == 0,
|
||||
'session TTL hook failed for action ' + action,
|
||||
)
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
encoded = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
return {'Authorization': 'Basic ' + encoded}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument(
|
||||
'--action-script',
|
||||
required=True,
|
||||
help='Executable hook controlled by SESSION_TTL_ACTION=short|restore',
|
||||
)
|
||||
parser.add_argument('--ttl-seconds', type=int, default=2)
|
||||
|
||||
args = arguments(
|
||||
'Short deployed session TTL, wrong-password and logout checks',
|
||||
configure,
|
||||
)
|
||||
check(
|
||||
1 <= args.ttl_seconds <= 10,
|
||||
'ttl-seconds must be between 1 and 10 for this test',
|
||||
)
|
||||
|
||||
script = Path(args.action_script).expanduser().resolve()
|
||||
check(
|
||||
script.is_file() and os.access(script, os.X_OK),
|
||||
'action script must exist and be executable (chmod +x)',
|
||||
)
|
||||
|
||||
execute_hook(script, 'short', args.ttl_seconds)
|
||||
try:
|
||||
client = Client(args.base_url, args.ca_file, timeout=10)
|
||||
actor = client.user('short_ttl')
|
||||
registration = actor['registration']
|
||||
|
||||
client.call(
|
||||
'POST',
|
||||
'/api/v1/auth/sessions',
|
||||
401,
|
||||
headers=basic(registration['username'], 'Wrong-password-123'),
|
||||
)
|
||||
client.call(
|
||||
'GET',
|
||||
'/api/v1/users/me',
|
||||
actor=actor,
|
||||
schema='User',
|
||||
)
|
||||
|
||||
time.sleep(args.ttl_seconds + 1.25)
|
||||
client.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
|
||||
session = client.call(
|
||||
'POST',
|
||||
'/api/v1/auth/sessions',
|
||||
201,
|
||||
headers=basic(
|
||||
registration['username'],
|
||||
registration['password'],
|
||||
),
|
||||
schema='Session',
|
||||
)['json']
|
||||
fresh_actor = {
|
||||
'id': actor['id'],
|
||||
'token': session['token'],
|
||||
}
|
||||
client.call(
|
||||
'DELETE',
|
||||
'/api/v1/auth/sessions/current',
|
||||
204,
|
||||
actor=fresh_actor,
|
||||
)
|
||||
client.call('GET', '/api/v1/users/me', 401, actor=fresh_actor)
|
||||
finally:
|
||||
execute_hook(script, 'restore', args.ttl_seconds)
|
||||
|
||||
print(
|
||||
'PASS: deployed short SESSION_TTL_SECONDS expired the token; '
|
||||
'wrong password and logout remained enforced.'
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,272 @@
|
||||
\set ON_ERROR_STOP on
|
||||
\pset pager off
|
||||
\timing off
|
||||
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000001',
|
||||
'track2_hot_user',
|
||||
'Track 2 hot chat user',
|
||||
'synthetic-not-a-login-hash'
|
||||
),
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000002',
|
||||
'track2_medium_user',
|
||||
'Track 2 medium chat user',
|
||||
'synthetic-not-a-login-hash'
|
||||
),
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000003',
|
||||
'track2_small_user',
|
||||
'Track 2 small chat user',
|
||||
'synthetic-not-a-login-hash'
|
||||
);
|
||||
|
||||
INSERT INTO chats (
|
||||
id,
|
||||
title
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000101',
|
||||
'Track 2 hot chat'
|
||||
),
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000102',
|
||||
'Track 2 medium chat'
|
||||
),
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000103',
|
||||
'Track 2 small chat'
|
||||
);
|
||||
|
||||
INSERT INTO chat_members (
|
||||
chat_id,
|
||||
user_id,
|
||||
position
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000101',
|
||||
'00000000-0000-4000-8000-000000000001',
|
||||
0
|
||||
),
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000102',
|
||||
'00000000-0000-4000-8000-000000000002',
|
||||
0
|
||||
),
|
||||
(
|
||||
'00000000-0000-4000-8000-000000000103',
|
||||
'00000000-0000-4000-8000-000000000003',
|
||||
0
|
||||
);
|
||||
|
||||
\echo 'WRITE PLAN: current index (chat_id, created_at, id)'
|
||||
EXPLAIN (ANALYZE, BUFFERS, WAL)
|
||||
WITH generated AS (
|
||||
SELECT
|
||||
number,
|
||||
md5('track2-message-' || number::text) AS digest,
|
||||
CASE
|
||||
WHEN number <= 90000
|
||||
THEN '00000000-0000-4000-8000-000000000101'::uuid
|
||||
WHEN number <= 99000
|
||||
THEN '00000000-0000-4000-8000-000000000102'::uuid
|
||||
ELSE '00000000-0000-4000-8000-000000000103'::uuid
|
||||
END AS chat_id,
|
||||
CASE
|
||||
WHEN number <= 90000
|
||||
THEN '00000000-0000-4000-8000-000000000001'::uuid
|
||||
WHEN number <= 99000
|
||||
THEN '00000000-0000-4000-8000-000000000002'::uuid
|
||||
ELSE '00000000-0000-4000-8000-000000000003'::uuid
|
||||
END AS sender_id
|
||||
FROM generate_series(1, 100000) AS series(number)
|
||||
)
|
||||
INSERT INTO messages (
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
(
|
||||
substr(digest, 1, 8) || '-' ||
|
||||
substr(digest, 9, 4) || '-4' ||
|
||||
substr(digest, 14, 3) || '-a' ||
|
||||
substr(digest, 18, 3) || '-' ||
|
||||
substr(digest, 21, 12)
|
||||
)::uuid,
|
||||
chat_id,
|
||||
sender_id,
|
||||
'Synthetic Track 2 message ' || number ||
|
||||
' with deterministic payload for index comparison',
|
||||
TIMESTAMPTZ '2026-01-01 00:00:00+00'
|
||||
+ number * INTERVAL '1 microsecond'
|
||||
FROM generated;
|
||||
|
||||
VACUUM (ANALYZE) messages;
|
||||
|
||||
\echo 'UNEVEN DISTRIBUTION: current variant'
|
||||
SELECT
|
||||
chat_id,
|
||||
count(*) AS message_count
|
||||
FROM messages
|
||||
GROUP BY chat_id
|
||||
ORDER BY message_count DESC;
|
||||
|
||||
\echo 'INDEX SIZE: current variant'
|
||||
SELECT
|
||||
pg_relation_size('messages_chat_created_at_id_idx') AS index_bytes,
|
||||
pg_size_pretty(
|
||||
pg_relation_size('messages_chat_created_at_id_idx')
|
||||
) AS index_size;
|
||||
|
||||
SELECT
|
||||
id AS cursor_id,
|
||||
created_at AS cursor_created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000101'
|
||||
ORDER BY created_at, id
|
||||
OFFSET 49999
|
||||
LIMIT 1
|
||||
\gset
|
||||
|
||||
\echo 'READ PLAN: current index plus keyset cursor'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000101'
|
||||
AND (created_at, id) > (
|
||||
:'cursor_created_at'::timestamptz,
|
||||
:'cursor_id'::uuid
|
||||
)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 101;
|
||||
|
||||
\echo 'READ PLAN: current index plus OFFSET 50000'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000101'
|
||||
ORDER BY created_at, id
|
||||
OFFSET 50000
|
||||
LIMIT 101;
|
||||
|
||||
DROP INDEX messages_chat_created_at_id_idx;
|
||||
TRUNCATE TABLE messages;
|
||||
|
||||
CREATE INDEX messages_chat_created_at_id_covering_idx
|
||||
ON messages (chat_id, created_at, id)
|
||||
INCLUDE (sender_id, text);
|
||||
|
||||
\echo 'WRITE PLAN: covering index with INCLUDE (sender_id, text)'
|
||||
EXPLAIN (ANALYZE, BUFFERS, WAL)
|
||||
WITH generated AS (
|
||||
SELECT
|
||||
number,
|
||||
md5('track2-message-' || number::text) AS digest,
|
||||
CASE
|
||||
WHEN number <= 90000
|
||||
THEN '00000000-0000-4000-8000-000000000101'::uuid
|
||||
WHEN number <= 99000
|
||||
THEN '00000000-0000-4000-8000-000000000102'::uuid
|
||||
ELSE '00000000-0000-4000-8000-000000000103'::uuid
|
||||
END AS chat_id,
|
||||
CASE
|
||||
WHEN number <= 90000
|
||||
THEN '00000000-0000-4000-8000-000000000001'::uuid
|
||||
WHEN number <= 99000
|
||||
THEN '00000000-0000-4000-8000-000000000002'::uuid
|
||||
ELSE '00000000-0000-4000-8000-000000000003'::uuid
|
||||
END AS sender_id
|
||||
FROM generate_series(1, 100000) AS series(number)
|
||||
)
|
||||
INSERT INTO messages (
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
(
|
||||
substr(digest, 1, 8) || '-' ||
|
||||
substr(digest, 9, 4) || '-4' ||
|
||||
substr(digest, 14, 3) || '-a' ||
|
||||
substr(digest, 18, 3) || '-' ||
|
||||
substr(digest, 21, 12)
|
||||
)::uuid,
|
||||
chat_id,
|
||||
sender_id,
|
||||
'Synthetic Track 2 message ' || number ||
|
||||
' with deterministic payload for index comparison',
|
||||
TIMESTAMPTZ '2026-01-01 00:00:00+00'
|
||||
+ number * INTERVAL '1 microsecond'
|
||||
FROM generated;
|
||||
|
||||
VACUUM (ANALYZE) messages;
|
||||
|
||||
\echo 'UNEVEN DISTRIBUTION: covering variant'
|
||||
SELECT
|
||||
chat_id,
|
||||
count(*) AS message_count
|
||||
FROM messages
|
||||
GROUP BY chat_id
|
||||
ORDER BY message_count DESC;
|
||||
|
||||
\echo 'INDEX SIZE: covering variant'
|
||||
SELECT
|
||||
pg_relation_size(
|
||||
'messages_chat_created_at_id_covering_idx'
|
||||
) AS index_bytes,
|
||||
pg_size_pretty(
|
||||
pg_relation_size(
|
||||
'messages_chat_created_at_id_covering_idx'
|
||||
)
|
||||
) AS index_size;
|
||||
|
||||
SELECT
|
||||
id AS cursor_id,
|
||||
created_at AS cursor_created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000101'
|
||||
ORDER BY created_at, id
|
||||
OFFSET 49999
|
||||
LIMIT 1
|
||||
\gset
|
||||
|
||||
\echo 'READ PLAN: covering index plus keyset cursor'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000101'
|
||||
AND (created_at, id) > (
|
||||
:'cursor_created_at'::timestamptz,
|
||||
:'cursor_id'::uuid
|
||||
)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 101;
|
||||
@@ -0,0 +1,94 @@
|
||||
\set ON_ERROR_STOP on
|
||||
\pset tuples_only on
|
||||
\pset format unaligned
|
||||
\pset pager off
|
||||
|
||||
WITH selected_messages AS (
|
||||
(
|
||||
SELECT
|
||||
id::text AS id,
|
||||
chat_id::text AS chat_id,
|
||||
sender_id::text AS sender_id,
|
||||
md5(text) AS text_md5,
|
||||
to_char(
|
||||
created_at AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'
|
||||
) AS created_at
|
||||
FROM messages
|
||||
ORDER BY created_at, id
|
||||
LIMIT 1
|
||||
)
|
||||
UNION ALL
|
||||
(
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
md5(text),
|
||||
to_char(
|
||||
created_at AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'
|
||||
)
|
||||
FROM messages
|
||||
ORDER BY created_at, id
|
||||
OFFSET 49999
|
||||
LIMIT 1
|
||||
)
|
||||
UNION ALL
|
||||
(
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
md5(text),
|
||||
to_char(
|
||||
created_at AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'
|
||||
)
|
||||
FROM messages
|
||||
ORDER BY created_at, id
|
||||
OFFSET 99999
|
||||
LIMIT 1
|
||||
)
|
||||
),
|
||||
distribution AS (
|
||||
SELECT
|
||||
chat_id::text AS chat_id,
|
||||
count(*) AS message_count
|
||||
FROM messages
|
||||
GROUP BY chat_id
|
||||
)
|
||||
SELECT jsonb_build_object(
|
||||
'counts',
|
||||
jsonb_build_object(
|
||||
'users', (SELECT count(*) FROM users),
|
||||
'chats', (SELECT count(*) FROM chats),
|
||||
'chat_members', (SELECT count(*) FROM chat_members),
|
||||
'messages', (SELECT count(*) FROM messages),
|
||||
'sessions', (SELECT count(*) FROM sessions)
|
||||
),
|
||||
'message_distribution',
|
||||
(
|
||||
SELECT jsonb_object_agg(
|
||||
chat_id,
|
||||
message_count
|
||||
ORDER BY chat_id
|
||||
)
|
||||
FROM distribution
|
||||
),
|
||||
'selected_messages',
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
to_jsonb(selected_messages)
|
||||
ORDER BY created_at, id
|
||||
)
|
||||
FROM selected_messages
|
||||
),
|
||||
'message_indexes',
|
||||
(
|
||||
SELECT jsonb_agg(indexname ORDER BY indexname)
|
||||
FROM pg_indexes
|
||||
WHERE schemaname = 'public'
|
||||
AND tablename = 'messages'
|
||||
)
|
||||
)::text;
|
||||
Reference in New Issue
Block a user