Compare commits
2
Commits
master
...
d8b178e290
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8b178e290 | ||
|
|
6ea767732e |
+36
-9
@@ -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.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
# Local synthetic teaching stand. Copy to .env (or run `make env`, which
|
||||
# generates strong random passwords and never prints them) and never commit
|
||||
# the result. There are no real/production credentials in this project.
|
||||
#
|
||||
# Compose reads this file for interpolation; the application receives only the
|
||||
# resolved values. File-based variants are supported by the binary as
|
||||
# DATABASE_URL_FILE and CACHE_URL_FILE for operators that prefer mounted
|
||||
# secrets; the local stand uses the ignored .env file.
|
||||
|
||||
# Host port published on 127.0.0.1 only. The process always listens on 8080
|
||||
# inside the container/network.
|
||||
HOST_PORT=8080
|
||||
APP_ENV=lab
|
||||
LOG_LEVEL=info
|
||||
APP_VERSION=1.0.0
|
||||
|
||||
# PostgreSQL (named volume mtusi-lab2-melnikov-pgdata).
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_DB=messenger
|
||||
POSTGRES_PASSWORD=
|
||||
|
||||
# Valkey (named volume mtusi-lab2-melnikov-valkeydata, AOF everysec).
|
||||
VALKEY_PASSWORD=
|
||||
|
||||
# Server-side session lifetime. The contract default is 3600; the expiry test
|
||||
# temporarily starts the API with a short value.
|
||||
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
|
||||
|
||||
# Bounded pool and timeouts (level 4).
|
||||
DB_MAX_CONNS=8
|
||||
DB_MIN_CONNS=1
|
||||
DB_CONNECT_TIMEOUT_SECONDS=3
|
||||
DB_STATEMENT_TIMEOUT_SECONDS=3
|
||||
DB_QUERY_TIMEOUT_SECONDS=3
|
||||
CACHE_POOL_SIZE=8
|
||||
CACHE_TIMEOUT_SECONDS=2
|
||||
SHUTDOWN_TIMEOUT_SECONDS=8
|
||||
STARTUP_TIMEOUT_SECONDS=30
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# Compile stage. Dependencies are vendored, so the build needs no module proxy
|
||||
# and the same source tree produces the same binary from a clean clone.
|
||||
FROM golang:1.25.1-alpine3.22@sha256:b6ed3fd0452c0e9bcdef5597f29cc1418f61672e9d3a2f55bf02e7222c014abd AS build
|
||||
|
||||
WORKDIR /src
|
||||
ENV CGO_ENABLED=0 \
|
||||
GOTOOLCHAIN=local \
|
||||
GOFLAGS=-mod=vendor
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
COPY vendor ./vendor
|
||||
COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
|
||||
ARG VERSION=1.0.0
|
||||
RUN go build \
|
||||
-trimpath \
|
||||
-buildvcs=false \
|
||||
-ldflags="-s -w -buildid= -X main.version=${VERSION}" \
|
||||
-o /out/messenger \
|
||||
./cmd/messenger
|
||||
|
||||
# Runtime stage: minimal Alpine pinned by digest, no shell tooling and no
|
||||
# package manager calls. The process runs as the unprivileged uid 10001.
|
||||
FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 AS runtime
|
||||
|
||||
LABEL org.opencontainers.image.title="mtusi-messenger-lab2" \
|
||||
org.opencontainers.image.description="MTUSI highload lab 2: PostgreSQL, sessions, Valkey" \
|
||||
org.opencontainers.image.version="1.0.0"
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=build --chown=10001:10001 /out/messenger /app/messenger
|
||||
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
|
||||
ENV APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080 \
|
||||
APP_ENV=lab \
|
||||
LOG_LEVEL=info \
|
||||
SESSION_TTL_SECONDS=3600 \
|
||||
SHUTDOWN_TIMEOUT_SECONDS=8
|
||||
|
||||
# The same binary implements -healthcheck, so the image needs no curl/wget and
|
||||
# the probe runs as the unprivileged user.
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=10s --retries=3 \
|
||||
CMD ["/app/messenger", "-healthcheck"]
|
||||
|
||||
ENTRYPOINT ["/app/messenger"]
|
||||
@@ -0,0 +1,105 @@
|
||||
# Черновик MR
|
||||
|
||||
- **Заголовок:** `ЛР 2 — БВТ2301 — Мельников — на 5`
|
||||
- **Ветка:** `solution/bvt2301-melnikov`
|
||||
- **Базовая ветка:** ветка skeleton преподавателя `master`
|
||||
(`65003b61195361aac238f19c9bff0027ca58e09e`); контракт не менялся.
|
||||
- **Fork/URL:** пока не опубликован. После публикации подставить реальный URL
|
||||
своего fork и открыть PR в исходный репозиторий преподавателя. Push, fork и
|
||||
MR в рамках этой работы не выполнялись; файл является готовым текстом MR.
|
||||
- **Ревизия решения:** `6ea767732e2cf43dbadba6be36186c9ab1bd0a19`.
|
||||
REPORT.md/MR.md/evidence добавлены отдельным commit; дерево приложения не
|
||||
меняется. Точный HEAD — `git log -1`.
|
||||
|
||||
---
|
||||
|
||||
## Лабораторная 2
|
||||
|
||||
Автор / группа: Мельников Иван Дмитриевич / БВТ2301
|
||||
Целевая оценка (3/4/5): 5
|
||||
Трек 5: трек 2 «План запроса и восстановление»
|
||||
|
||||
**Что реализовано.** Go 1.25.1 API мессенджера с PostgreSQL 16.4 как
|
||||
источником истины для пользователей, чатов, членства и сообщений, и Valkey
|
||||
8.0.2 как единственным хранилищем серверных сессий с TTL и AOF
|
||||
(`appendfsync everysec`) на named volume. Регистрация требует password и
|
||||
хранит Argon2id PHC-строку; вход — Basic только на `POST /auth/sessions`;
|
||||
бизнес-endpoint принимают только opaque Bearer из 256 бит; `X-User-Id`
|
||||
игнорируется. Есть logout, absolute expiry, строгая JSON-валидация, keyset
|
||||
pagination `(created_at,id)` по составному индексу, миграции с checksum и
|
||||
advisory lock, bounded pgx pool и таймауты, 503 при недоступности
|
||||
Valkey/PostgreSQL, graceful shutdown. Compose-стенд поднимает api+postgres+
|
||||
valkey с фиксированными версиями/digest, named volumes и non-root read-only
|
||||
API. Из lab1 перенесены нужные исходники, валидация, курсоры, Dockerfile-подход
|
||||
и собственные тесты; публичные `tests/`, `contracts/`, README/COURSE не
|
||||
изменялись.
|
||||
|
||||
**Команды запуска из чистого clone** (подробности — REPORT.md):
|
||||
|
||||
```sh
|
||||
git clone --branch solution/bvt2301-melnikov <URL_ВАШЕГО_ФОРКА> mtusi2026lab2
|
||||
cd mtusi2026lab2
|
||||
make env
|
||||
make up
|
||||
make check && make validate
|
||||
make test
|
||||
make test-student
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-expiry
|
||||
make test-failure
|
||||
make test-container
|
||||
make test-db
|
||||
make track5
|
||||
```
|
||||
|
||||
**Результаты проверок** (ревизия 6ea7677, образ
|
||||
`sha256:888fc645…`, evidence в репозитории):
|
||||
|
||||
- `make check` — PASS; `make validate` — PASS (OpenAPI 3.1 + JSON Schema).
|
||||
- `make test` — PASS на Python 3.9.6 и 3.14.4.
|
||||
- `make test-student` — PASS: Go unit tests + 78 black-box проверок;
|
||||
`go test -race` и `go vet` — PASS.
|
||||
- `make test-persistence` — PASS: прежний токен и подтверждённые сообщения
|
||||
после перезапуска API, PostgreSQL и Valkey; StartedAt всех контейнеров
|
||||
изменился, volumes сохранены, миграции `1,2` не продублировались.
|
||||
- `make test-expiry` — PASS: TTL 15.05 с, токен пережил API-only restart,
|
||||
после абсолютного дедлайна 401.
|
||||
- `make test-failure` — PASS: Valkey/PostgreSQL down → `/health/live` 200,
|
||||
`/health/ready` 503, защищённый запрос 503, анонимный 401; после
|
||||
восстановления сессия/данные целы, volumes не удалены.
|
||||
- `make test-container` — PASS: real containers/volumes, uid 10001, read-only
|
||||
rootfs, cap drop ALL, graceful shutdown 0.078 с, токены/пароли/текст в логах
|
||||
отсутствуют, AOF everysec.
|
||||
- `make test-db` — PASS: 14 constraint-имён, 4 индекса, Argon2id, 0
|
||||
дубликатов username, rollback составного чата, стабильные counts при
|
||||
повторных миграциях, EXPLAIN на 60 000 сообщений: keyset 50 строк,
|
||||
OFFSET 30 050.
|
||||
- `make track5` — PASS: 100 000 сообщений в 6 чатах (60k/25k/10k/4k/900/100);
|
||||
composite index 50 строк/0.076 мс против chat_id-only 29 999 heap + 60 000
|
||||
bitmap/14.859 мс; запись 20k строк 46.601 против 45.997 мс (медианы);
|
||||
dump 0.272 с/3 362 659 B → restore в новый контейнер 0.361 с → полная
|
||||
сверка counts/md5/selected; RTO 1.616 с, RPO = момент dump.
|
||||
- Чистый clone: `make env && make up` на пустых volumes → миграции с нуля
|
||||
(`migrations=2, users=0` до тестов), `make check`, `go test`, `make test`,
|
||||
78 black-box checks — PASS; временные clean-контейнеры/volumes удалены.
|
||||
|
||||
**Ограничения.** Один Docker-host и один API-процесс (нет HA/LB/реплик —
|
||||
lab3+); Valkey AOF everysec допускает потерю до 1 с при жёстком падении;
|
||||
backup — offline `pg_dump`, не PITR; rate limiting/TLS/вложения не входят в
|
||||
обязательный lab2; измерения сняты на Colima 2 vCPU/2 GB и не являются SLA.
|
||||
Секреты локальные синтетические, `.env` не коммитится. Публикация fork/push
|
||||
и сообщения преподавателю требуют отдельного указания пользователя.
|
||||
|
||||
**Источники и ИИ.** Skeleton mtusi2026lab2 revision 65003b6, OpenAPI 1.2.0,
|
||||
PostgreSQL/Valkey docs, Go stdlib + pgx v5.7.2, go-redis v9.7.0,
|
||||
golang.org/x/crypto v0.31.0; сторонний код приложения не копировался.
|
||||
Реализация, тесты, experiment и отчёт подготовлены DeepSeek-агентом Orca;
|
||||
решения проверены командами и evidence в репозитории.
|
||||
|
||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с
|
||||
объявленными переходами API.
|
||||
- [x] Контракт и публичные тесты не ослаблены.
|
||||
- [x] `make check` и `make test` выполнены; реальный вывод в `evidence/`.
|
||||
- [x] Сценарии отказов/безопасности уровня 3/4 и трек 5 воспроизведены.
|
||||
- [x] Все секреты и приватные ключи вне Git; отчёт не содержит tokens.
|
||||
- [x] README задания сохранён; REPORT.md описывает именно это решение.
|
||||
@@ -1,13 +1,23 @@
|
||||
PYTHON ?= python3
|
||||
GO ?= go
|
||||
BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
COMPOSE ?= ./scripts/compose.sh
|
||||
IMAGE ?= mtusi-messenger-lab2-melnikov:1.0.0
|
||||
COMPOSE_ARGS = --env-file .env
|
||||
|
||||
.PHONY: help check validate test load test-persistence
|
||||
.PHONY: help check validate test load test-persistence env up wait build-image docker-config stop down purge logs \
|
||||
test-student test-student-race test-expiry test-failure test-container test-db track5
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "env: create ignored .env with random local credentials; up: build+start stack; wait: wait for /health/ready"
|
||||
@echo "stop: stop containers (data kept); down: remove containers (volumes kept); purge: DELETE volumes and data"
|
||||
@echo "test-student: Go unit tests + black-box suite; test-student-race: Go race detector"
|
||||
@echo "test-expiry: short-TTL session + API-restart scenario; test-failure: DB/Valkey outage scenarios"
|
||||
@echo "test-container: container/volume/health checks; test-db: SQL constraints, migrations and EXPLAIN; track5: level-5 track 2"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -24,3 +34,58 @@ load:
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
env:
|
||||
./scripts/init-env.sh
|
||||
|
||||
up:
|
||||
$(COMPOSE) $(COMPOSE_ARGS) up -d --build
|
||||
./scripts/wait-ready.sh
|
||||
|
||||
wait:
|
||||
./scripts/wait-ready.sh
|
||||
|
||||
build-image:
|
||||
$(COMPOSE) $(COMPOSE_ARGS) build api
|
||||
|
||||
docker-config:
|
||||
$(COMPOSE) $(COMPOSE_ARGS) config --quiet
|
||||
|
||||
stop:
|
||||
$(COMPOSE) $(COMPOSE_ARGS) stop
|
||||
|
||||
down:
|
||||
$(COMPOSE) $(COMPOSE_ARGS) down
|
||||
|
||||
purge:
|
||||
@echo "PURGE removes containers AND named volumes mtusi-lab2-melnikov-*: all synthetic data is lost."
|
||||
$(COMPOSE) $(COMPOSE_ARGS) down -v
|
||||
|
||||
logs:
|
||||
$(COMPOSE) $(COMPOSE_ARGS) logs --tail=100 api
|
||||
|
||||
test-student:
|
||||
$(GO) test -count=1 ./...
|
||||
$(PYTHON) student-tests/blackbox.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-student-race:
|
||||
$(GO) test -race -count=1 ./...
|
||||
|
||||
test-expiry:
|
||||
SESSION_TTL_SECONDS=15 $(COMPOSE) $(COMPOSE_ARGS) up -d --no-deps --force-recreate api
|
||||
./scripts/wait-ready.sh
|
||||
$(PYTHON) scripts/expiry-check.py --base-url "$(BASE_URL)" $(TLS_ARGS) --restart-api
|
||||
$(COMPOSE) $(COMPOSE_ARGS) up -d --no-deps --force-recreate api
|
||||
./scripts/wait-ready.sh
|
||||
|
||||
test-failure:
|
||||
$(PYTHON) scripts/failure-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-container:
|
||||
$(PYTHON) scripts/container-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS) --image "$(IMAGE)"
|
||||
|
||||
test-db:
|
||||
$(PYTHON) scripts/db-checks.py
|
||||
|
||||
track5:
|
||||
$(PYTHON) scripts/track5.py
|
||||
|
||||
@@ -1,37 +1,375 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- **Автор, группа:** Мельников Иван Дмитриевич, БВТ2301.
|
||||
- **Целевая оценка:** 5. **Трек 5:** трек 2 «План запроса и восстановление».
|
||||
- **Исходный репозиторий:** `mtusi2026lab2`, revision
|
||||
`65003b61195361aac238f19c9bff0027ca58e09e` (ветка skeleton `master`).
|
||||
- **Ветка решения:** `solution/bvt2301-melnikov`.
|
||||
- **Ревизия реализации и доказательств:** `6ea767732e2cf43dbadba6be36186c9ab1bd0a19`.
|
||||
REPORT.md, MR.md и `evidence/` добавлены отдельным commit поверх неё; этот
|
||||
commit меняет только документацию и доказательства, дерево приложения
|
||||
остаётся тем же. Точный финальный HEAD показывает `git log -1`.
|
||||
- **Образ:** `mtusi-messenger-lab2-melnikov:1.0.0`,
|
||||
`sha256:888fc6451aded79beaabfd2bc2f6578f25324facc84d3798d8b4d074272270bb`,
|
||||
19 580 930 байт. Эксперименты и проверки ниже сняты на этой ревизии и образе.
|
||||
- **Источники, библиотеки, помощь ИИ:** README/COURSE/CONTRIBUTING,
|
||||
`contracts/openapi.json` 1.2.0 и `contracts/README.md` lab2; Go 1.25.1;
|
||||
`github.com/jackc/pgx/v5 v5.7.2`, `github.com/redis/go-redis/v9 v9.7.0`,
|
||||
`golang.org/x/crypto v0.31.0` (Argon2id), зависимости завендорены. Базовые
|
||||
образы закреплены digest: `golang:1.25.1-alpine3.22`,
|
||||
`alpine:3.22.1`, `postgres:16.4-alpine3.20`,
|
||||
`valkey/valkey:8.0.2-alpine`. Сторонний код приложения не копировался.
|
||||
Реализация, тесты, эксперимент и текст отчёта подготовлены DeepSeek-агентом
|
||||
Orca; решения проверены публичными и собственными тестами.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Проверено на macOS 15.5 (arm64), Colima 0.8.1, Docker Engine 27.4.0,
|
||||
Docker Compose 2.37.0 (standalone; wrapper поддерживает и plugin
|
||||
`docker compose`), Python 3.9.6 и 3.14.4, Go 1.25.1 на хосте. В контейнере
|
||||
приложение собирается закреплённым `golang:1.25.1-alpine3.22`, runtime —
|
||||
`alpine:3.22.1`; Go на машине проверяющего нужен только для `go test`.
|
||||
Python 3.9+ нужен для `make check`, `make test`, black-box и скриптов.
|
||||
Внешние пакеты Python не нужны, кроме необязательного `make validate`
|
||||
(`requirements-dev.txt`). Модули Go завендорены: сборка образа не ходит в
|
||||
module proxy, но Docker должен один раз скачать закреплённые базовые образы.
|
||||
|
||||
Удалённый fork и ветка **пока не опубликованы**, поэтому реального URL форка
|
||||
нет; ниже честный placeholder. Локально готовый результат уже находится в
|
||||
`/Users/ivanmuller/Desktop/oh_my_life/highload/lab2` на ветке
|
||||
`solution/bvt2301-melnikov`.
|
||||
|
||||
После публикации собственного fork (URL подставить свой):
|
||||
|
||||
```sh
|
||||
git clone --branch solution/bvt2301-melnikov <URL_ВАШЕГО_ФОРКА> mtusi2026lab2
|
||||
cd mtusi2026lab2
|
||||
make env # создать .env с локальными синтетическими паролями
|
||||
make up # собрать образ и поднять postgres + valkey + api
|
||||
make test # публичный smoke, BASE_URL по умолчанию localhost:8080
|
||||
```
|
||||
|
||||
Команды ниже работают и в текущей локальной папке (без clone):
|
||||
|
||||
```sh
|
||||
cd /Users/ivanmuller/Desktop/oh_my_life/highload/lab2
|
||||
make env # .env создаётся один раз; повторно не перезаписывается
|
||||
make up # docker compose up -d --build + ожидание /health/ready
|
||||
make test # публичный контрактный smoke
|
||||
make test-student # Go-тесты + собственный black-box (78 проверок)
|
||||
make test-student-race # go test -race
|
||||
make test-expiry # короткий TTL: перезапуск только API, затем истечение
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failure # stop/start Valkey и PostgreSQL, volumes сохраняются
|
||||
make test-container # реальные контейнеры, volumes, non-root, graceful, логи
|
||||
make test-db # SQL-ограничения, rollback, миграции, EXPLAIN
|
||||
make track5 # трек 2: 100k сообщений, индексы, backup/restore
|
||||
```
|
||||
|
||||
Остановка и удаление данных — это разные команды:
|
||||
|
||||
```sh
|
||||
make stop # остановить процессы; named volumes и данные сохраняются
|
||||
make down # удалить контейнеры и сеть; named volumes и данные сохраняются
|
||||
make purge # ЯВНО удалить контейнеры И named volumes mtusi-lab2-melnikov-*
|
||||
# (все синтетические данные будут потеряны)
|
||||
```
|
||||
|
||||
Временные ресурсы эксперимента трека 2 (`mtusi-lab2-melnikov-pgrestore`,
|
||||
volume `mtusi-lab2-melnikov-restoredata`) скрипт создаёт и удаляет сам в
|
||||
`finally`; основной стенд и его volumes не затрагиваются. Чистый clone для
|
||||
проверки сборки поднимался с временным override имён/портов
|
||||
(`mtusi-lab2-melnikov-clean-*`), после чего его контейнеры, network и volumes
|
||||
удалены; основной стенд восстановлен с прежними данными.
|
||||
|
||||
### Переменные окружения
|
||||
|
||||
| Переменная | Значение по умолчанию | Смысл |
|
||||
| --- | --- | --- |
|
||||
| `HOST_PORT` | `8080` | published port; только `127.0.0.1` |
|
||||
| `APP_HOST`, `APP_PORT` | `0.0.0.0`, `8080` | адрес процесса внутри контейнера |
|
||||
| `APP_ENV`, `LOG_LEVEL` | `lab`, `info` | метки логов |
|
||||
| `POSTGRES_USER`, `POSTGRES_DB` | `messenger`, `messenger` | локальная БД |
|
||||
| `POSTGRES_PASSWORD` | создаёт `make env` | синтетический пароль; `.env` не коммитится |
|
||||
| `VALKEY_PASSWORD` | создаёт `make env` | пароль Valkey; `.env` не коммитится |
|
||||
| `DATABASE_URL`, `CACHE_URL` | собираются compose | app-конфигурация; также поддерживаются `DATABASE_URL_FILE`/`CACHE_URL_FILE` |
|
||||
| `SESSION_TTL_SECONDS` | `3600` | абсолютный TTL серверной сессии; тест expiry — 15 |
|
||||
| `DB_MAX_CONNS`, `DB_MIN_CONNS` | `8`, `1` | границы pgx pool |
|
||||
| `DB_CONNECT_TIMEOUT_SECONDS` | `3` | таймаут установки соединения |
|
||||
| `DB_STATEMENT_TIMEOUT_SECONDS` | `3` | `statement_timeout` серверной сессии |
|
||||
| `DB_QUERY_TIMEOUT_SECONDS` | `3` | context timeout каждой операции |
|
||||
| `CACHE_POOL_SIZE`, `CACHE_TIMEOUT_SECONDS` | `8`, `2` | pool и таймауты Valkey |
|
||||
| `SHUTDOWN_TIMEOUT_SECONDS` | `8` | graceful shutdown ≤ 9 с |
|
||||
| `STARTUP_TIMEOUT_SECONDS` | `30` | ожидание PostgreSQL при старте |
|
||||
|
||||
`.env.example` содержит пустые пароли: `make env` (`scripts/init-env.sh`)
|
||||
генерирует 32 случайных alphanumeric символа, пишет `.env` с mode 600 и не
|
||||
печатает значения. `.env`, `secrets/`, volumes и ключи исключены `.gitignore`;
|
||||
`docker compose config` использует только локальный `.env`.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
Клиент (curl / smoke / blackbox / psql-эксперимент)
|
||||
|
|
||||
v
|
||||
HTTP API :8080 (Go, один процесс; stateless относительно данных)
|
||||
X-Request-Id + X-Instance-Id + recover + request log
|
||||
Basic только на POST /auth/sessions
|
||||
Bearer (opaque token) на всех остальных защищённых endpoint
|
||||
строгая валидация JSON/UUID/limit/cursor
|
||||
| |
|
||||
v v
|
||||
PostgreSQL 16.4 (source of truth) Valkey 8.0.2 (source of truth сессий)
|
||||
users, chats, chat_members, key = SHA-256(token), value = user_id
|
||||
messages, schema_migrations + absolute expires_at; TTL = SESSION_TTL
|
||||
named volume pgdata AOF appendfsync everysec
|
||||
named volume valkeydata
|
||||
```
|
||||
|
||||
- **Что перенесено из lab1.** Go HTTP-роутер, структура JSON-ответов, строгий
|
||||
top-level JSON-декодер, Unicode/`username`-валидация, keyset-курсоры,
|
||||
обработка членства как 404, request-id/ошибки, graceful shutdown,
|
||||
Dockerfile-подход и собственные тесты. Внутренний in-memory store заменён
|
||||
PostgreSQL-репозиторием; `X-User-Id` заменён Bearer-сессией.
|
||||
- **Что изменено по контракту lab2.** `POST /users` требует `password`;
|
||||
`POST /auth/sessions` принимает только Basic; `DELETE /auth/sessions/current`;
|
||||
все бизнес-endpoint требуют Bearer. `sender_id` никогда не читается из body.
|
||||
- **PostgreSQL — источник истины** для пользователей, чатов, членства и
|
||||
сообщений. `chat_members` имеет составной PK `(chat_id, user_id)` и FK на
|
||||
`users`/`chats`; `messages` имеет FK на `chats` и составной FK
|
||||
`(chat_id, sender_id) → chat_members(chat_id, user_id)`, поэтому СУБД сама
|
||||
не даст записать сообщение от не-участника.
|
||||
- **Транзакционные границы.** Регистрация — один `INSERT` с уникальным
|
||||
индексом (гонка двух одинаковых username даёт ровно один успех, остальные
|
||||
получают 409). Создание чата — одна транзакция: проверка существования всех
|
||||
участников, `INSERT` чата, пакетная вставка членства, commit. Ошибка на любом
|
||||
шаге откатывает и чат, и членство; проверено инъекцией ошибки в trigger на
|
||||
`chat_members`. Отправка сообщения — один `INSERT` с FK-проверкой. Сессия —
|
||||
один `SET`/`DEL` в Valkey.
|
||||
- **Сессии — Valkey, а не кэш поверх PostgreSQL.** Это единственное хранилище
|
||||
сессий, поэтому включён AOF (`appendonly yes`, `appendfsync everysec`) и
|
||||
named volume. TTL задаётся Valkey и является абсолютным: рестарт API не
|
||||
продлевает жизнь токена; logout делает `DEL`; истёкший/отозванный токен —
|
||||
401. При недоступности Valkey API отдаёт ограниченный 503 и не считает
|
||||
анонимный запрос доверенным. Потеря при жёстком падении хоста — до одной
|
||||
секунды подтверждённых записей AOF; graceful restart сохраняет всё.
|
||||
- **Пароли.** Argon2id PHC-строка: `m=19456 KiB, t=2, p=1`, salt 16 байт,
|
||||
key 32 байта (минимум OWASP для Argon2id). Сравнение — constant time.
|
||||
Пароль и hash никогда не сериализуются в User/Session и не пишутся в логи;
|
||||
для неизвестного username выполняется проверка dummy-hash, чтобы не
|
||||
раскрывать существование аккаунта по времени.
|
||||
- **Токены.** 32 байта `crypto/rand` → 43 символа base64url (256 бит). В
|
||||
Valkey лежит только SHA-256 токена, поэтому дамп кэша не содержит
|
||||
пригодных Bearer-токенов. `X-User-Id` нигде не читается.
|
||||
- **Индексы.** `messages_chat_created_id_idx (chat_id, created_at, id)` —
|
||||
ровно под keyset-запрос истории; `chat_members_user_chat_idx` — под список
|
||||
чатов пользователя; `chats_created_id_idx` — под порядок `(created_at,id)`;
|
||||
`users_username_key` — уникальность. Пагинация — `WHERE chat_id=$1 AND
|
||||
(created_at,id) > ($2,$3) ORDER BY created_at,messages.id LIMIT $4` с
|
||||
`LIMIT+1` для честного `next_cursor`, без `OFFSET`.
|
||||
- **Ограниченный pool и таймауты.** pgx pool 8/1 соединений, connect timeout
|
||||
3 с, `statement_timeout=3s`, context timeout 3 с на операцию; Valkey pool 8,
|
||||
dial/read/write 2 с, один retry; HTTP read/write timeouts. При недоступности
|
||||
БД ошибка классифицируется как 503 `unavailable`, а не 500/401.
|
||||
- **Миграции.** Две версионируемые SQL-миграции (`0001_init.sql`,
|
||||
`0002_query_indexes.sql`) встроены через `go:embed`; `schema_migrations`
|
||||
хранит версию, имя и SHA-256 содержимого; применяются в транзакции под
|
||||
`pg_advisory_lock`, повторный запуск — no-op, изменение уже применённого
|
||||
файла — ошибка старта. Повторные рестарты API не дублируют данные.
|
||||
- **Соответствие `.env.example`.** В skeleton поля `DATABASE_URL_FILE`/
|
||||
`CACHE_URL_FILE` были логической подсказкой; приложение поддерживает и
|
||||
`_FILE`-варианты, а локальный compose передаёт `DATABASE_URL`/`CACHE_URL`,
|
||||
собранные из локальных `POSTGRES_*`/`VALKEY_*`. Секреты в Git не попадают.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Все команды выполнялись из корня репозитория на ревизии
|
||||
`6ea767732e2cf43dbadba6be36186c9ab1bd0a19` и образе
|
||||
`sha256:888fc6451aded79beaabfd2bc2f6578f25324facc84d3798d8b4d074272270bb`;
|
||||
все файлы — внутри репозитория и переживают clone.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Публичный smoke | `make test` (Python 3.9.6) | `PASS: lab2 public API scenario` | `evidence/public-and-student-tests.txt` |
|
||||
| Структура/OpenAPI | `make check`; `make validate` | `PASS` offline; `PASS` OpenAPI 3.1 + JSON Schema | `evidence/check-validate-tests.txt` |
|
||||
| Level 3: PostgreSQL users/chats/members/messages, PK/FK/unique | `make test-db` | 14 constraint-имён, 4 индекса, 134 пользователя, все пароли Argon2id | `evidence/db-checks.json`, `evidence/db-checks.txt` |
|
||||
| Level 3: транзакционное создание чата | trigger `lab2_rollback_probe` + `POST /chats` | API 500 без внутренних деталей; `chats=0` и `chat_members=0` после rollback | `evidence/db-checks.json` |
|
||||
| Level 3: Basic только на login, Bearer, X-User-Id игнорируется | `make test`; `make test-student` | Basic на `/users/me` → 401; `X-User-Id` alone → 401; с Bearer не меняет owner | `evidence/public-and-student-tests.txt` |
|
||||
| Level 3: срок жизни и отзыв сессии | `make test-expiry`; `make test` | TTL 15.05 с; тот же токен пережил restart API 0.717 с; после дедлайна 401; logout 204, повтор 401 | `evidence/expiry.txt`, `evidence/public-and-student-tests.txt` |
|
||||
| Level 3: пароли password KDF | `make test-db`; Go tests | все `password_hash` начинаются с `$argon2id$`; plaintext не хранится | `evidence/db-checks.json` |
|
||||
| Level 3: `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS; до/после изменены `StartedAt` всех трёх контейнеров, volumes те же, `migrations=2` | `evidence/persistence-restart.txt` |
|
||||
| Level 3: миграции повторяются без дублей | `make test-db` (рестарт API) | counts до/после равны, `schema_migrations=2` | `evidence/db-checks.json` |
|
||||
| Level 3: secrets/volumes вне Git | `make test-container` | `.env` ignored; tracked secret-like файлов 0; volumes named `mtusi-lab2-melnikov-*` | `evidence/container-checks.json`, `evidence/container-checks.txt` |
|
||||
| Level 4: Valkey реально хранит сессии с TTL | `make test-container`; `make test-expiry` | `appendonly=yes`, `appendfsync=everysec`, `/data`, `aof_last_write_status=ok`, TTL сессии в ответе и 401 после | `evidence/container-checks.json`, `evidence/expiry.txt` |
|
||||
| Level 4: persistence единственного session store | `make test-persistence`; `make test-failure` | сессия жива после restart API+PostgreSQL+Valkey и после stop/start Valkey | `evidence/persistence-restart.txt`, `evidence/failure-checks.json` |
|
||||
| Level 4: параметризованные запросы, pool, timeouts | код + `make test-db` | все SQL с `$n`; pool 8/1; connect/statement/query 3 с; Valkey pool 8/2 с | `internal/store/store.go`, `internal/config/config.go`, `evidence/db-checks.json` |
|
||||
| Level 4: гонка одинакового username | black-box 8 параллельных POST; `make test-db` | ровно один 201, семь 409; 0 duplicate username в БД | `evidence/public-and-student-tests.txt`, `evidence/db-checks.json` |
|
||||
| Level 4: rollback составной операции | trigger + `POST /chats` | чат и членство не остались после ошибки | `evidence/db-checks.json` |
|
||||
| Level 4: индекс истории + EXPLAIN на ≥10 000 | `make test-db`; `make track5` | 60 000-сообщений чат: keyset 50 строк, OFFSET 30 050 строк; `Index Scan using messages_chat_created_id_idx` | `evidence/explain-level4.txt`, `evidence/db-checks.json`, `evidence/track5/explain-composite-index.txt` |
|
||||
| Level 4: пагинация без полного scan | `make test-db`; `make test-student` | keyset 50 строк/0.076 мс против OFFSET 30 050 строк/11.542 мс; cursor другого чата 400 | `evidence/explain-level4.txt`, `evidence/public-and-student-tests.txt` |
|
||||
| Level 4: expiry, logout, неверный пароль, недоступность Valkey/БД | `make test-expiry`; `make test-failure`; blackbox | 401/204/503; при Valkey/PostgreSQL down `/health/live` 200, `/health/ready` 503, защищённый запрос 503, анонимный 401 | `evidence/expiry.txt`, `evidence/failure-checks.txt` |
|
||||
| Level 4: bounded error при потере зависимости | `make test-failure` | recovery 0.303 с (Valkey), 0.686 с (PostgreSQL); volumes не удалены; данные/сессия живы | `evidence/failure-checks.json` |
|
||||
| Level 5 track 2: ≥100 000 сообщений, неравномерные чаты | `make track5` | 100 000 в 6 чатах: 60 000/25 000/10 000/4 000/900/100; всего в БД 112 283 | `evidence/track5/summary.json` |
|
||||
| Level 5 track 2: ≥2 индекса/запроса и стоимость записи | `make track5` | composite 50 строк/0.076 мс vs chat_id-only 29 999 heap-строк/60 000 bitmap/14.859 мс; запись 20k строк: 46.601 мс vs 45.997 мс (медианы 3 прогонов) | `evidence/track5/summary.json`, `evidence/track5/explain-*.txt`, `evidence/track5/write-cost.json` |
|
||||
| Level 5 track 2: backup → новое хранилище → сверка | `make track5` | counts 136/55/90/112283/2 совпали; per-chat counts и md5 истории совпали; выбранное сообщение совпало | `evidence/track5/backup-restore.json` |
|
||||
| Level 5 track 2: RTO/потеря данных | `make track5` | dump 0.272 с/3 362 659 B; restore 0.361 с; полное восстановление с запуском нового контейнера 1.616 с; RPO = возраст последнего dump (WAL archiving нет) | `evidence/track5/summary.json` |
|
||||
| Сборка/запуск из чистого clone, миграции с нуля | `git clone` + `make env` + `make up` + тесты | revision A2; fresh DB `migrations=2, users=0` до тестов; `make check`, `go test`, `make test`, 78 black-box checks — PASS | `evidence/clean-clone.txt` |
|
||||
| Собственные тесты | `make test-student`; `make test-student-race`; `go vet` | 78 black-box проверок; все Go-пакеты PASS; race PASS; vet без замечаний | `evidence/public-and-student-tests.txt`, `evidence/check-validate-tests.txt` |
|
||||
| Реальные контейнеры/volumes/не-root/graceful/логи | `make test-container` | 3 контейнера healthy; API uid 10001, read-only rootfs, cap drop ALL; volumes named; graceful shutdown 0.078 с, exit 0; токен/пароль/текст в логах не найдены | `evidence/container-checks.json`, `evidence/container-checks.txt` |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
### Чеклист уровня 3/4 и трека 2
|
||||
|
||||
- [x] PostgreSQL содержит пользователей, чаты, участников и сообщения; PK,
|
||||
FK, unique username, CHECK-ограничения; миграции с нуля.
|
||||
- [x] Создание чата атомарно; sender выводится из сессии; чужой чат — 404.
|
||||
- [x] Basic только на `POST /auth/sessions`; остальные endpoint — Bearer;
|
||||
TTL, logout, `X-User-Id` не даёт доступ.
|
||||
- [x] Argon2id (библиотечный KDF), а не SHA-256/plaintext.
|
||||
- [x] `make test` и `make test-persistence` проходят; миграции не дублируют
|
||||
данные; секреты/volumes вне Git.
|
||||
- [x] Valkey реально используется для сессий с TTL; AOF everysec + volume;
|
||||
источник истины, expiry и инвалидация описаны.
|
||||
- [x] Параметризованные SQL, ограниченный pool, таймауты; гонка username и
|
||||
rollback проверены.
|
||||
- [x] Индекс истории (chat_id, created_at, id) с EXPLAIN (ANALYZE, BUFFERS)
|
||||
на ≥10 000 сообщениях; keyset не сканирует всю историю.
|
||||
- [x] Автопроверки expiry, logout, неверного пароля, недоступности
|
||||
Valkey/PostgreSQL; ограниченный 503 и отказ от доверия анониму.
|
||||
- [x] Трек 2: 100k неравномерных сообщений, два индекса/запроса, стоимость
|
||||
записи, backup → новое хранилище → сверка, RTO и границы потерь.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
### Трек 2. Гипотеза
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
Составной индекс `(chat_id, created_at, id)` позволяет keyset-странице
|
||||
истории читать примерно `limit` строк независимо от глубины, тогда как
|
||||
индекс только по `chat_id` или `OFFSET` вынуждены читать префикс чата и
|
||||
сортировать его. Цена — небольшая надбавка на запись из-за третьего поля
|
||||
индекса. Backup `pg_dump -Fc` в новое хранилище должен восстановить точные
|
||||
количества и выбранные сообщения; RTO измеряется от запуска нового контейнера
|
||||
до готовности восстановленной БД, RPO ограничен моментом снимка (WAL
|
||||
archiving не настроен).
|
||||
|
||||
**Стенд.** Colima VM: 2 vCPU, 2 054 631 424 B RAM (2.05 GB как видит Docker),
|
||||
macOS 15.5 arm64. Compose limits: API 1 CPU/256 MiB, PostgreSQL 1 CPU/512 MiB,
|
||||
Valkey 1 CPU/256 MiB. PostgreSQL 16.4, Valkey 8.0.2, образ API
|
||||
`sha256:888fc645…`. Все данные синтетические; ключи/токены в отчёт не попали.
|
||||
|
||||
**Данные.** 100 000 сообщений в шести чатах разного размера
|
||||
(60 000 / 25 000 / 10 000 / 4 000 / 900 / 100), плюс данные предыдущих
|
||||
проверок (итого 112 283). Timestamps назначены детерминированно с шагом 1 мс
|
||||
в каждом чате; сортировка — `(created_at, id)`.
|
||||
|
||||
**Метрики и источник.** `EXPLAIN (ANALYZE, BUFFERS)` — PostgreSQL Execution
|
||||
Time и фактические `rows`/buffers из плана; `EXPLAIN (ANALYZE) INSERT` —
|
||||
Execution Time записи 20 000 строк, по 3 прогона, медиана; dump/restore —
|
||||
wall-clock `time.monotonic` вокруг `pg_dump`/`pg_restore`; размер — байты
|
||||
файла; counts/checksum — SQL `count(*)` и `md5(string_agg(...))`. Сырые
|
||||
планы и JSON лежат в `evidence/track5/`; sample timestamps и интервалы фаз —
|
||||
в `summary.json` (`started_at`, `finished_at`, `seed_interval`,
|
||||
`indexes.interval`, `write_cost.interval`, `backup_restore.interval`).
|
||||
|
||||
| Сценарий | Строк прочитано | Execution Time | Buffers/план |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| first page, composite index | 50 | 0.060 мс | 4 shared hit |
|
||||
| deep keyset (offset 30 000), composite | 50 | 0.076 мс | 4 shared hit, Index Scan |
|
||||
| deep OFFSET 30 000, composite | 30 050 | 11.542 мс | 618 shared hit, Index Scan + Limit |
|
||||
| deep keyset, chat_id-only index | 29 999 heap + 60 000 bitmap | 14.859 мс | Bitmap Heap Scan + top-N Sort |
|
||||
| запись 20 000 строк, composite | — | 46.601 мс (медиана) | 3 прогона: 46.601/47.027/46.409 |
|
||||
| запись 20 000 строк, chat_id-only | — | 45.997 мс (медиана) | 3 прогона: 45.882/47.201/45.997 |
|
||||
|
||||
Вывод: keyset-страница на глубине 30 000 читает 50 строк вместо ~30 000–60 000;
|
||||
цена записи composite-индекса в этом микротесте ≈ +1.3% (46.601 против
|
||||
45.997 мс), что несопоставимо с выигрышем на чтении. Индекс только по
|
||||
`chat_id` не покрывает порядок и требует bitmap+sort.
|
||||
|
||||
**Backup/restore.** `pg_dump -Fc` (0.272 с, 3 362 659 байт, SHA-256
|
||||
`499413a6…`) → новый контейнер PostgreSQL с новым volume
|
||||
`mtusi-lab2-melnikov-restoredata` → `pg_restore --no-owner --no-privileges`
|
||||
(0.361 с). Сверка: 136 users / 55 chats / 90 chat_members / 112 283 messages /
|
||||
2 migrations совпали; per-chat counts совпали; md5 упорядоченной истории
|
||||
`d7788d6e93c0eca463069665fb99e6e4` совпал; выбранное сообщение
|
||||
`e77ba05c-13b1-46a4-ba9f-6f630e60f623` совпало. Полное восстановление с
|
||||
запуском нового контейнера — 1.616 с. RPO: снимок один, WAL archiving нет,
|
||||
поэтому потеря — всё, что записано после начала dump; в эксперименте запись
|
||||
не велась, потерь нет. RTO 1.6 с — только локальный стенд, не production SLA.
|
||||
|
||||
**Ограничения трека.** Один Docker-host, нет реплик/HA; `pg_dump` даёт
|
||||
согласованный снимок, но не PITR; при конкурентной записи во время dump часть
|
||||
подтверждённых строк не попадёт в backup (RPO = интервал между backup);
|
||||
измерения включают локальный Docker/Colima и warm cache; write-cost мерил
|
||||
только поддержание индекса на scratch-таблицах, без WAL fsync и FK; абсолютные
|
||||
миллисекунды не переносятся на другое железо.
|
||||
|
||||
### Отказы зависимостей
|
||||
|
||||
| Воздействие | Что ожидали | Что наблюдали | Восстановление |
|
||||
| --- | --- | --- | --- |
|
||||
| `docker stop valkey` | `/health/live` 200; `/health/ready` 503; Bearer → bounded 503; аноним → 401; login 503; регистрация (только БД) 201 | именно так | `docker start valkey`, ready 200, старый токен 200, 0.303 с |
|
||||
| `docker stop postgres` | live 200; ready 503; Bearer → 503; регистрация/login 503; аноним 401 | именно так | `docker start postgres`, ready 200, данные/сессия/сообщение на месте, 0.686 с |
|
||||
| Рестарт API+БД+Valkey (persistence hook) | прежний токен и подтверждённые данные живы, volumes сохранены | `PASS`; StartedAt всех трёх контейнеров изменился; counts не потеряны | автоматически |
|
||||
| `make purge` | намеренное удаление volumes | описано отдельной destructive-командой; в проверках не выполнялось | `make env && make up` с нуля |
|
||||
|
||||
### Исправленные дефекты по ходу проверок
|
||||
|
||||
- Go `time.Time` по умолчанию обрезает дробную часть до 3–9 цифр; Python 3.9
|
||||
`fromisoformat` понимает только 3/6 цифр. Введён `model.Time` с ровно шестью
|
||||
микросекундными цифрами и `Z`; публичный smoke перестал падать
|
||||
недетерминированно.
|
||||
- В `ORDER BY` для сообщений неквалифицированный `id` резолвился в выходной
|
||||
alias `id::text`, из-за чего PostgreSQL добавлял Incremental Sort. Запрос
|
||||
переведён на `ORDER BY created_at, messages.id`; EXPLAIN показывает чистый
|
||||
`Index Scan` и 50 фактических строк.
|
||||
- В black-box фиксированный 32-символьный username конфликтовал при повторном
|
||||
запуске; заменён на случайный. Это тестовый дефект, не API.
|
||||
|
||||
## Защита: короткие ответы
|
||||
|
||||
- **COMMIT и durability.** PostgreSQL `synchronous_commit=on` (по умолчанию) —
|
||||
COMMIT подтверждён после WAL fsync; потеря может затронуть только
|
||||
незакоммиченные/неподтверждённые данные. Docker/Kubernetes не дают HA
|
||||
PostgreSQL на одном host.
|
||||
- **Где сессии и что после flush/restart Valkey.** В Valkey, key =
|
||||
SHA-256(token), TTL и абсолютный `expires_at`; AOF everysec + named volume.
|
||||
Graceful restart сохраняет подтверждённые сессии; `FLUSHALL`/жёсткая потеря
|
||||
volume разлогинит всех — это осознанная граница, PostgreSQL-сессий нет.
|
||||
- **Аутентификация vs доступ к чату.** Bearer подтверждает пользователя;
|
||||
членство в `chat_members` отдельно проверяется для каждого чата/истории,
|
||||
чужой объект — 404. Basic — только вход, не доступ к API.
|
||||
- **Hash пароля vs checksum.** Argon2id медленный и с salt, чтобы перебор
|
||||
украденного дампа был дорогим и одинаковые пароли не совпадали; SHA-256
|
||||
быстрый и не годится для паролей (используется только для ключа сессии,
|
||||
где секрет уже имеет 256 бит энтропии).
|
||||
- **Почему Valkey не кэш поверх БД.** Иначе logout/revocation и outage
|
||||
потребовали бы согласования кэша и источника истины; сессии выбраны
|
||||
единственным хранилищем с AOF, а PostgreSQL остаётся источником истины
|
||||
пользователей/чатов/сообщений.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Один Docker-host и один API-процесс; нет LB/реплик/HA (это lab3+). Падение
|
||||
хоста или потеря Docker volume означает потерю данных и сессий.
|
||||
- Valkey AOF everysec: при жёстком убийстве контейнера возможна потеря до 1 с
|
||||
подтверждённых сессионных записей; graceful stop/restart сохраняет всё.
|
||||
- Backup трека — offline `pg_dump`, не PITR; WAL archiving, реплика и
|
||||
регулярное расписание не входят в lab2 и не заявляются.
|
||||
- Rate limiting, TLS, вложения, WebSocket/UI, Argon2id-переход lab7 не входят
|
||||
в обязательный минимум lab2; 429/415-коды контракта не выдаются без причины.
|
||||
- `X-Instance-Id` добавлен как forward-compatible observability для lab3; на
|
||||
lab2 он не обязателен и контракт не расширяет.
|
||||
- Измерения сделаны на Colima 2 vCPU/2 GB; абсолютные RPS/мс на другом
|
||||
железе будут другими. Нагрузочный closed-loop `tests/load.py` не
|
||||
использовался как доказательство трека: трек 2 измеряет план и
|
||||
восстановление, а не максимальную пропускную способность.
|
||||
- Fork/push/MR/сообщения преподавателю не выполнялись. Для сдачи нужен fork
|
||||
текущего репозитория lab2, ветка `solution/bvt2301-melnikov` и PR с
|
||||
заголовком `ЛР 2 — БВТ2301 — Мельников — на 5`; черновик — в `MR.md`.
|
||||
|
||||
## Использование ИИ
|
||||
|
||||
Код, миграции, compose, тесты, эксперимент и текст отчёта подготовлены
|
||||
DeepSeek-агентом Orca в одном проходе; внешний ревьюер и другие модели не
|
||||
привлекались. Все утверждения проверены командами из таблицы; сырые
|
||||
результаты, ревизия и image id зафиксированы в `evidence/`.
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
// Command messenger runs the lab2 HTTP API and the container healthcheck
|
||||
// helper. PostgreSQL holds users, chats, membership and messages; Valkey holds
|
||||
// server-side sessions with an absolute TTL.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/api"
|
||||
"mtusi.ru/messenger-lab2/internal/config"
|
||||
"mtusi.ru/messenger-lab2/internal/session"
|
||||
"mtusi.ru/messenger-lab2/internal/store"
|
||||
)
|
||||
|
||||
// version is overridden at build time with -X main.version=...
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
healthcheck := flag.Bool("healthcheck", false, "probe the local liveness endpoint and exit 0/1")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
if *healthcheck {
|
||||
os.Exit(runHealthcheck(cfg))
|
||||
}
|
||||
|
||||
logger := newLogger(cfg)
|
||||
ctx := context.Background()
|
||||
|
||||
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
|
||||
MaxConns: cfg.DBMaxConns,
|
||||
MinConns: cfg.DBMinConns,
|
||||
ConnectTimeout: cfg.DBConnectTimeout,
|
||||
StatementTimeout: cfg.DBStatementTimeout,
|
||||
QueryTimeout: cfg.QueryTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("database configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer repository.Close()
|
||||
|
||||
if err := waitForDatabase(ctx, repository, cfg.StartupTimeout, logger); err != nil {
|
||||
logger.Error("postgres did not become ready", "timeout_seconds", int(cfg.StartupTimeout.Seconds()), "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
migrateCtx, migrateCancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
err = repository.Migrate(migrateCtx)
|
||||
migrateCancel()
|
||||
if err != nil {
|
||||
logger.Error("database migrations failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
logger.Info("database ready", "migrations", "up-to-date")
|
||||
|
||||
sessions, err := session.Open(cfg.CacheURL, session.Options{
|
||||
PoolSize: cfg.CachePoolSize,
|
||||
DialTimeout: cfg.CacheTimeout,
|
||||
IOTimeout: cfg.CacheTimeout,
|
||||
TTL: cfg.SessionTTL,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("session store configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer func() { _ = sessions.Close() }()
|
||||
|
||||
app, err := api.New(repository, sessions, logger)
|
||||
if err != nil {
|
||||
logger.Error("application initialization failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Handler: app.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 20 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
}
|
||||
|
||||
address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
|
||||
listener, err := net.Listen("tcp", address)
|
||||
if err != nil {
|
||||
logger.Error("listen failed", "address", address, "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
logger.Info("server listening",
|
||||
"address", listener.Addr().String(),
|
||||
"env", cfg.Env,
|
||||
"session_ttl_seconds", int(cfg.SessionTTL.Seconds()),
|
||||
"graceful_shutdown_seconds", int(cfg.ShutdownTimeout.Seconds()),
|
||||
"version", version,
|
||||
)
|
||||
|
||||
serveErrors := make(chan error, 1)
|
||||
go func() {
|
||||
serveErrors <- server.Serve(listener)
|
||||
}()
|
||||
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
select {
|
||||
case received := <-signals:
|
||||
logger.Info("shutdown initiated", "signal", received.String())
|
||||
// Clear readiness first: a request that races with Shutdown must not
|
||||
// see a successful readiness probe.
|
||||
app.SetReady(false)
|
||||
started := time.Now()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("graceful shutdown failed", "error", err)
|
||||
_ = server.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
logger.Info("shutdown complete",
|
||||
"elapsed_ms", float64(time.Since(started).Microseconds())/1000.0,
|
||||
)
|
||||
os.Exit(0)
|
||||
case err := <-serveErrors:
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
logger.Error("server stopped unexpectedly", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newLogger(cfg config.Config) *slog.Logger {
|
||||
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel})
|
||||
return slog.New(handler).With("service", "messenger-lab2", "app_env", cfg.Env)
|
||||
}
|
||||
|
||||
func waitForDatabase(ctx context.Context, repository *store.Store, timeout time.Duration, logger *slog.Logger) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
attempt := 0
|
||||
for {
|
||||
attempt++
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err := repository.Ping(pingCtx)
|
||||
cancel()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return err
|
||||
}
|
||||
logger.Debug("waiting for postgres", "attempt", attempt, "error", err)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// runHealthcheck is compiled into the same binary as the server, so the
|
||||
// runtime image needs no curl, wget or shell. It always talks to loopback
|
||||
// inside the container, independently of APP_HOST.
|
||||
func runHealthcheck(cfg config.Config) int {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
url := "http://127.0.0.1:" + strconv.Itoa(cfg.Port) + "/health/live"
|
||||
response, err := client.Get(url) //nolint:gosec // fixed loopback URL built from a validated port
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "healthcheck request failed:", err)
|
||||
return 1
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, response.Body)
|
||||
if response.StatusCode != http.StatusOK {
|
||||
fmt.Fprintln(os.Stderr, "healthcheck status:", response.StatusCode)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# Lab2 local teaching stand. Every runtime component is built or pinned from
|
||||
# this repository; PostgreSQL and Valkey keep named volumes, the API is
|
||||
# stateless. Secrets come from the ignored .env file created by
|
||||
# `make env` (scripts/init-env.sh) and are never committed.
|
||||
#
|
||||
# Start: make env && make up
|
||||
# Stop: make stop (processes stopped, volumes and data preserved)
|
||||
# Remove: make down (containers removed, volumes preserved)
|
||||
# Purge: make purge (containers AND volumes removed; explicit data loss)
|
||||
name: mtusi-lab2-melnikov
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c
|
||||
container_name: mtusi-lab2-melnikov-postgres
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env via make env}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
PGDATA: /var/lib/postgresql/data/pgdata
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
networks:
|
||||
- backend
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
stop_grace_period: 20s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 512M
|
||||
|
||||
valkey:
|
||||
image: valkey/valkey:8.0.2-alpine@sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d
|
||||
container_name: mtusi-lab2-melnikov-valkey
|
||||
environment:
|
||||
VALKEY_PASSWORD: ${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}
|
||||
# AOF everysec is the durability boundary: a graceful restart keeps every
|
||||
# acknowledged session; a hard crash can lose up to one second of writes.
|
||||
# The session TTL is stored as an absolute deadline by Valkey, so replaying
|
||||
# the AOF neither revives expired sessions nor extends live ones.
|
||||
command:
|
||||
- valkey-server
|
||||
- --appendonly
|
||||
- "yes"
|
||||
- --appendfsync
|
||||
- everysec
|
||||
- --requirepass
|
||||
- ${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}
|
||||
- --protected-mode
|
||||
- "no"
|
||||
volumes:
|
||||
- valkeydata:/data
|
||||
networks:
|
||||
- backend
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "valkey-cli --no-auth-warning -a \"$$VALKEY_PASSWORD\" ping | grep -q PONG"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
stop_grace_period: 20s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 256M
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
VERSION: ${APP_VERSION:-1.0.0}
|
||||
image: mtusi-messenger-lab2-melnikov:${APP_VERSION:-1.0.0}
|
||||
container_name: mtusi-lab2-melnikov-api
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env via make env}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable
|
||||
CACHE_URL: redis://:${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}@valkey:6379/0
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DB_MAX_CONNS: ${DB_MAX_CONNS:-8}
|
||||
DB_MIN_CONNS: ${DB_MIN_CONNS:-1}
|
||||
DB_CONNECT_TIMEOUT_SECONDS: ${DB_CONNECT_TIMEOUT_SECONDS:-3}
|
||||
DB_STATEMENT_TIMEOUT_SECONDS: ${DB_STATEMENT_TIMEOUT_SECONDS:-3}
|
||||
DB_QUERY_TIMEOUT_SECONDS: ${DB_QUERY_TIMEOUT_SECONDS:-3}
|
||||
CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-8}
|
||||
CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-2}
|
||||
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-8}
|
||||
STARTUP_TIMEOUT_SECONDS: ${STARTUP_TIMEOUT_SECONDS:-30}
|
||||
GOMEMLIMIT: 200MiB
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
valkey:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:-8080}:8080"
|
||||
networks:
|
||||
- backend
|
||||
healthcheck:
|
||||
test: ["CMD", "/app/messenger", "-healthcheck"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
stop_grace_period: 15s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 256M
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
name: mtusi-lab2-melnikov-pgdata
|
||||
valkeydata:
|
||||
name: mtusi-lab2-melnikov-valkeydata
|
||||
|
||||
networks:
|
||||
backend:
|
||||
name: mtusi-lab2-melnikov-net
|
||||
@@ -0,0 +1,31 @@
|
||||
# check + validate + unit tests on 6ea767732e2cf43dbadba6be36186c9ab1bd0a19
|
||||
## make check (Python 3.9.6)
|
||||
Python 3.9.6
|
||||
/usr/bin/python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
## make validate (Python 3.9 venv)
|
||||
.venv/bin/python scripts/validate_openapi.py
|
||||
/Users/ivanmuller/Desktop/oh_my_life/highload/lab2/.venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
|
||||
warnings.warn(
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
## go test
|
||||
? mtusi.ru/messenger-lab2/cmd/messenger [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/api 0.532s
|
||||
ok mtusi.ru/messenger-lab2/internal/auth 0.398s
|
||||
ok mtusi.ru/messenger-lab2/internal/config 0.393s
|
||||
ok mtusi.ru/messenger-lab2/internal/cursor 0.274s
|
||||
ok mtusi.ru/messenger-lab2/internal/model 0.657s
|
||||
? mtusi.ru/messenger-lab2/internal/session [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/store 0.791s
|
||||
ok mtusi.ru/messenger-lab2/internal/uuid 0.912s
|
||||
## go vet
|
||||
## go test -race
|
||||
? mtusi.ru/messenger-lab2/cmd/messenger [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/api 1.307s
|
||||
ok mtusi.ru/messenger-lab2/internal/auth 3.999s
|
||||
ok mtusi.ru/messenger-lab2/internal/config 1.451s
|
||||
ok mtusi.ru/messenger-lab2/internal/cursor 1.874s
|
||||
ok mtusi.ru/messenger-lab2/internal/model 1.591s
|
||||
? mtusi.ru/messenger-lab2/internal/session [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/store 1.726s
|
||||
ok mtusi.ru/messenger-lab2/internal/uuid 2.017s
|
||||
@@ -0,0 +1,66 @@
|
||||
# clean-clone verification
|
||||
clone_at=2026-11-30T20:53:12Z
|
||||
revision=6ea767732e2cf43dbadba6be36186c9ab1bd0a19
|
||||
branch=solution/bvt2301-melnikov
|
||||
worktree_before=0 modified/untracked paths (only ignored .env expected)
|
||||
./scripts/init-env.sh
|
||||
wrote .env with generated local synthetic credentials (mode 600); values not printed
|
||||
Container mtusi-lab2-melnikov-clean-valkey Started
|
||||
Container mtusi-lab2-melnikov-clean-postgres Started
|
||||
Container mtusi-lab2-melnikov-clean-valkey Waiting
|
||||
Container mtusi-lab2-melnikov-clean-postgres Waiting
|
||||
Container mtusi-lab2-melnikov-clean-postgres Healthy
|
||||
Container mtusi-lab2-melnikov-clean-valkey Healthy
|
||||
Container mtusi-lab2-melnikov-clean-api Starting
|
||||
Container mtusi-lab2-melnikov-clean-api Started
|
||||
ready: http://127.0.0.1:8080/health/ready
|
||||
## fresh database before tests
|
||||
migrations=2
|
||||
users=0
|
||||
chats=0
|
||||
messages=0
|
||||
## make check (Python 3.9.6)
|
||||
Python 3.9.6
|
||||
/usr/bin/python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
## go test
|
||||
? mtusi.ru/messenger-lab2/cmd/messenger [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/api 0.448s
|
||||
ok mtusi.ru/messenger-lab2/internal/auth 0.380s
|
||||
ok mtusi.ru/messenger-lab2/internal/config 0.299s
|
||||
ok mtusi.ru/messenger-lab2/internal/cursor 0.871s
|
||||
ok mtusi.ru/messenger-lab2/internal/model 0.582s
|
||||
? mtusi.ru/messenger-lab2/internal/session [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/store 1.011s
|
||||
ok mtusi.ru/messenger-lab2/internal/uuid 0.726s
|
||||
## make test (public smoke against clean stack)
|
||||
/usr/bin/python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
## student black-box suite against clean stack
|
||||
PASS health
|
||||
PASS registration/auth
|
||||
PASS registration validation
|
||||
PASS chats/membership
|
||||
PASS messages
|
||||
PASS pagination
|
||||
PASS concurrent registration
|
||||
PASS concurrent messages
|
||||
PASS logout
|
||||
PASS: lab2 student black-box suite, 78 checks
|
||||
## clean stack after tests
|
||||
migrations=2
|
||||
users=12
|
||||
chats=6
|
||||
messages=52
|
||||
chat_members,chats,messages,schema_migrations,users
|
||||
api_image_id=sha256:95cde144ae938177c164cc84a63261610f483ce676c32a0e829ba46e7c8014bc
|
||||
postgres_image=postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c
|
||||
valkey_image=valkey/valkey:8.0.2-alpine@sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d
|
||||
## cleanup of temporary clean-clone resources at 2026-11-30T20:53:29Z
|
||||
## clean resources remaining (expect none)
|
||||
## main stack restored after clean-clone test at 2026-11-30T20:53:31Z
|
||||
main_api=/mtusi-lab2-melnikov-api image=sha256:888fc6451aded79beaabfd2bc2f6578f25324facc84d3798d8b4d074272270bb started=2026-11-30T20:53:30.030730946Z health=starting
|
||||
users=136
|
||||
chats=55
|
||||
messages=112283
|
||||
migrations=2
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"containers": {
|
||||
"mtusi-lab2-melnikov-api": {
|
||||
"image": "mtusi-messenger-lab2-melnikov:1.0.0",
|
||||
"image_id": "sha256:888fc6451aded79beaabfd2bc2f6578f25324facc84d3798d8b4d074272270bb",
|
||||
"started_at": "2026-11-30T20:52:15.263533308Z",
|
||||
"restart_policy": "unless-stopped"
|
||||
},
|
||||
"mtusi-lab2-melnikov-postgres": {
|
||||
"image": "postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c",
|
||||
"image_id": "sha256:a710cb729803496a1c36335b6b519899fc3b0f332bbe16387a4d35c3e69cb5b1",
|
||||
"started_at": "2026-11-30T20:52:21.398677135Z",
|
||||
"restart_policy": "unless-stopped"
|
||||
},
|
||||
"mtusi-lab2-melnikov-valkey": {
|
||||
"image": "valkey/valkey:8.0.2-alpine@sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d",
|
||||
"image_id": "sha256:7b2072cf1b86d58fee110f4da8dc3b0e1444b22ab64f58d7f61e822e0761f866",
|
||||
"started_at": "2026-11-30T20:52:21.181106821Z",
|
||||
"restart_policy": "unless-stopped"
|
||||
}
|
||||
},
|
||||
"volumes": {
|
||||
"mtusi-lab2-melnikov-pgdata": "/var/lib/docker/volumes/mtusi-lab2-melnikov-pgdata/_data",
|
||||
"mtusi-lab2-melnikov-valkeydata": "/var/lib/docker/volumes/mtusi-lab2-melnikov-valkeydata/_data"
|
||||
},
|
||||
"api_user": "10001:10001",
|
||||
"api_read_only": true,
|
||||
"api_ports": [
|
||||
{
|
||||
"HostIp": "127.0.0.1",
|
||||
"HostPort": "8080"
|
||||
}
|
||||
],
|
||||
"image": {
|
||||
"reference": "mtusi-messenger-lab2-melnikov:1.0.0",
|
||||
"id": "sha256:888fc6451aded79beaabfd2bc2f6578f25324facc84d3798d8b4d074272270bb",
|
||||
"size_bytes": 19580930,
|
||||
"user": "10001:10001",
|
||||
"healthcheck": [
|
||||
"CMD",
|
||||
"/app/messenger",
|
||||
"-healthcheck"
|
||||
],
|
||||
"created": "2026-11-30T23:44:18.694178956+03:00"
|
||||
},
|
||||
"valkey": {
|
||||
"appendonly": "yes",
|
||||
"appendfsync": "everysec",
|
||||
"dir": "/data",
|
||||
"aof_enabled": true,
|
||||
"aof_last_write_status": "ok",
|
||||
"session_keys": 106
|
||||
},
|
||||
"instance_id": "26f785bd3f5188f1",
|
||||
"log_checks": {
|
||||
"token_absent": true,
|
||||
"password_absent": true,
|
||||
"message_body_absent": true,
|
||||
"authorization_header_absent": true
|
||||
},
|
||||
"graceful_shutdown": {
|
||||
"boot_seconds": 5.397,
|
||||
"shutdown_seconds": 0.073,
|
||||
"exit_code": 0
|
||||
},
|
||||
"git": {
|
||||
"tracked_files": 497,
|
||||
"env_ignored": true,
|
||||
"secret_like_tracked": []
|
||||
},
|
||||
"finished_at": "2026-11-30T20:52:32Z"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# container/infrastructure checks on 6ea767732e2cf43dbadba6be36186c9ab1bd0a19 at 2026-11-30T20:52:22Z
|
||||
{"graceful_shutdown_seconds": 0.073, "image_id": "sha256:888fc6451aded79beaabfd2bc2f6578f25324facc84d3798d8b4d074272270bb", "image_size_bytes": 19580930, "logs_clean": true, "secret_like_tracked_files": [], "volumes": ["mtusi-lab2-melnikov-pgdata", "mtusi-lab2-melnikov-valkeydata"]}
|
||||
PASS: real containers, pinned images, named volumes, non-root read-only API, graceful shutdown, clean logs
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"checked_at": "2026-11-30T20:52:32.996878Z",
|
||||
"schema": {
|
||||
"migration_versions": "1,2",
|
||||
"constraints_present": [
|
||||
"chat_members_chat_id_fkey",
|
||||
"chat_members_pkey",
|
||||
"chat_members_position_nonnegative",
|
||||
"chat_members_user_id_fkey",
|
||||
"chats_pkey",
|
||||
"chats_title_length",
|
||||
"messages_chat_fk",
|
||||
"messages_pkey",
|
||||
"messages_sender_membership_fk",
|
||||
"messages_text_length",
|
||||
"users_display_name_length",
|
||||
"users_password_hash_present",
|
||||
"users_pkey",
|
||||
"users_username_format"
|
||||
],
|
||||
"indexes_present": [
|
||||
"chat_members_user_chat_idx",
|
||||
"chats_created_id_idx",
|
||||
"messages_chat_created_id_idx",
|
||||
"users_username_key"
|
||||
],
|
||||
"users": 134,
|
||||
"argon2id_hashes": 134,
|
||||
"duplicate_usernames": 0,
|
||||
"race_duplicates": 0
|
||||
},
|
||||
"sender_membership_fk": {
|
||||
"rejected": true,
|
||||
"messages_before": 112283,
|
||||
"messages_after": 112283
|
||||
},
|
||||
"composite_rollback": {
|
||||
"chats_left": 0,
|
||||
"api_status": 500
|
||||
},
|
||||
"migrations_idempotent": {
|
||||
"counts_before": "136,55,90,112283",
|
||||
"counts_after": "136,55,90,112283",
|
||||
"migrations_after": 2,
|
||||
"api_restarted": true
|
||||
},
|
||||
"explain": {
|
||||
"chat_id": "d64fec89-08a6-4948-acc3-4ca99ac54f5a",
|
||||
"history_messages": 60000,
|
||||
"total_messages": 112283,
|
||||
"first_page_index_rows": 50,
|
||||
"keyset_page_index_rows": 50,
|
||||
"offset_page_index_rows": 30050,
|
||||
"deep_offset": 30000,
|
||||
"index_used": "messages_chat_created_id_idx"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# SQL constraints/rollback/migrations/EXPLAIN on 6ea767732e2cf43dbadba6be36186c9ab1bd0a19 at 2026-11-30T20:52:32Z
|
||||
{"argon2id_hashes": 134, "composite_rollback_left_chats": 0, "constraints": 14, "explain_history_messages": 60000, "indexes": 4, "keyset_rows_read": 50, "migration_counts_stable": true, "migrations": "1,2", "offset_rows_read": 30050}
|
||||
PASS: SQL constraints, FK, rollback, idempotent migrations and index-backed EXPLAIN
|
||||
@@ -0,0 +1,20 @@
|
||||
# expiry scenario on 6ea767732e2cf43dbadba6be36186c9ab1bd0a19 at 2026-11-30T20:51:46Z
|
||||
## make test-expiry (SESSION_TTL_SECONDS=15, API-only restart)
|
||||
SESSION_TTL_SECONDS=15 ./scripts/compose.sh --env-file .env up -d --no-deps --force-recreate api
|
||||
Container mtusi-lab2-melnikov-api Recreate
|
||||
Container mtusi-lab2-melnikov-api Recreated
|
||||
Container mtusi-lab2-melnikov-api Starting
|
||||
Container mtusi-lab2-melnikov-api Started
|
||||
./scripts/wait-ready.sh
|
||||
ready: http://127.0.0.1:8080/health/ready
|
||||
/usr/bin/python3 scripts/expiry-check.py --base-url "http://localhost:8080" --restart-api
|
||||
PASS: token survived an API-only restart in 0.71s; instance 24dba34a034db04b -> 6cdb90f2247d2bb6
|
||||
{"api_restart": true, "api_restart_seconds": 0.709, "checked_at": "2026-11-30T20:52:03.596044Z", "configured_ttl_seconds": 15, "expired_status": 401, "instance_after": "6cdb90f2247d2bb6", "instance_before": "24dba34a034db04b", "observed_ttl_seconds": 15.041}
|
||||
PASS: short-TTL expiry, absolute deadline, and API-restart session survival
|
||||
./scripts/compose.sh --env-file .env up -d --no-deps --force-recreate api
|
||||
Container mtusi-lab2-melnikov-api Recreate
|
||||
Container mtusi-lab2-melnikov-api Recreated
|
||||
Container mtusi-lab2-melnikov-api Starting
|
||||
Container mtusi-lab2-melnikov-api Started
|
||||
./scripts/wait-ready.sh
|
||||
ready: http://127.0.0.1:8080/health/ready
|
||||
@@ -0,0 +1,35 @@
|
||||
LAB2 LEVEL 4 EXPLAIN EVIDENCE
|
||||
messages in history: 60000, total messages: 112283, deep offset: 30000
|
||||
|
||||
=== first page ===
|
||||
Limit (cost=0.42..8.42 rows=50 width=141) (actual time=0.021..0.041 rows=50 loops=1)
|
||||
Buffers: shared hit=5
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.42..9617.70 rows=60079 width=141) (actual time=0.021..0.038 rows=50 loops=1)
|
||||
Index Cond: (chat_id = 'd64fec89-08a6-4948-acc3-4ca99ac54f5a'::uuid)
|
||||
Buffers: shared hit=5
|
||||
Planning:
|
||||
Buffers: shared hit=114
|
||||
Planning Time: 0.270 ms
|
||||
Execution Time: 0.059 ms
|
||||
|
||||
=== keyset page after offset 30000 ===
|
||||
Limit (cost=0.42..16.75 rows=50 width=141) (actual time=0.030..0.047 rows=50 loops=1)
|
||||
Buffers: shared hit=3 read=1
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.42..7361.33 rows=22536 width=141) (actual time=0.029..0.044 rows=50 loops=1)
|
||||
Index Cond: ((chat_id = 'd64fec89-08a6-4948-acc3-4ca99ac54f5a'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:30.001+00'::timestamp with time zone, 'e77ba05c-13b1-46a4-ba9f-6f630e60f623'::uuid)))
|
||||
Buffers: shared hit=3 read=1
|
||||
Planning:
|
||||
Buffers: shared hit=113
|
||||
Planning Time: 0.262 ms
|
||||
Execution Time: 0.075 ms
|
||||
|
||||
=== naive OFFSET 30000 ===
|
||||
Limit (cost=4802.74..4810.74 rows=50 width=141) (actual time=11.206..11.225 rows=50 loops=1)
|
||||
Buffers: shared hit=619
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.42..9617.70 rows=60079 width=141) (actual time=0.020..10.570 rows=30050 loops=1)
|
||||
Index Cond: (chat_id = 'd64fec89-08a6-4948-acc3-4ca99ac54f5a'::uuid)
|
||||
Buffers: shared hit=619
|
||||
Planning:
|
||||
Buffers: shared hit=114
|
||||
Planning Time: 0.278 ms
|
||||
Execution Time: 11.241 ms
|
||||
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"probe_message_id": "96a0fcde-73d4-4599-a619-d9f3e2a51539",
|
||||
"volumes_before": {
|
||||
"mtusi-lab2-melnikov-pgdata": "/var/lib/docker/volumes/mtusi-lab2-melnikov-pgdata/_data",
|
||||
"mtusi-lab2-melnikov-valkeydata": "/var/lib/docker/volumes/mtusi-lab2-melnikov-valkeydata/_data"
|
||||
},
|
||||
"containers_started_before": {
|
||||
"mtusi-lab2-melnikov-postgres": "2026-11-30T20:52:09.879834802Z",
|
||||
"mtusi-lab2-melnikov-valkey": "2026-11-30T20:52:09.891634364Z"
|
||||
},
|
||||
"valkey_outage": {
|
||||
"liveness": {
|
||||
"status": 200,
|
||||
"body": {
|
||||
"status": "ok"
|
||||
}
|
||||
},
|
||||
"readiness": {
|
||||
"status": 503
|
||||
},
|
||||
"authenticated_request": {
|
||||
"path": "/api/v1/users/me",
|
||||
"status": 503,
|
||||
"code": "unavailable"
|
||||
},
|
||||
"anonymous_request": {
|
||||
"status": 401,
|
||||
"code": "unauthorized"
|
||||
},
|
||||
"login": {
|
||||
"status": 503,
|
||||
"code": "unavailable"
|
||||
},
|
||||
"registration_while_down": {
|
||||
"status": 201
|
||||
},
|
||||
"recovery_seconds": 0.302,
|
||||
"session_after_recovery": {
|
||||
"status": 200
|
||||
}
|
||||
},
|
||||
"postgres_outage": {
|
||||
"liveness": {
|
||||
"status": 200,
|
||||
"body": {
|
||||
"status": "ok"
|
||||
}
|
||||
},
|
||||
"readiness": {
|
||||
"status": 503
|
||||
},
|
||||
"authenticated_request": {
|
||||
"path": "/api/v1/users/me",
|
||||
"status": 503,
|
||||
"code": "unavailable"
|
||||
},
|
||||
"anonymous_request": {
|
||||
"status": 401,
|
||||
"code": "unauthorized"
|
||||
},
|
||||
"registration": {
|
||||
"status": 503,
|
||||
"code": "unavailable"
|
||||
},
|
||||
"recovery_seconds": 0.656,
|
||||
"session_after_recovery": {
|
||||
"status": 200
|
||||
},
|
||||
"message_after_recovery": {
|
||||
"status": 200,
|
||||
"found": true
|
||||
}
|
||||
},
|
||||
"volumes_after": {
|
||||
"mtusi-lab2-melnikov-pgdata": "/var/lib/docker/volumes/mtusi-lab2-melnikov-pgdata/_data",
|
||||
"mtusi-lab2-melnikov-valkeydata": "/var/lib/docker/volumes/mtusi-lab2-melnikov-valkeydata/_data"
|
||||
},
|
||||
"containers_started_after": {
|
||||
"mtusi-lab2-melnikov-postgres": "2026-11-30T20:52:21.398677135Z",
|
||||
"mtusi-lab2-melnikov-valkey": "2026-11-30T20:52:21.181106821Z"
|
||||
},
|
||||
"finished_at": "2026-11-30T20:52:22.064084Z"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# dependency outage checks on 6ea767732e2cf43dbadba6be36186c9ab1bd0a19 at 2026-11-30T20:52:20Z
|
||||
{"postgres_recovery_seconds": 0.656, "valkey_recovery_seconds": 0.302, "volumes_kept": ["mtusi-lab2-melnikov-pgdata", "mtusi-lab2-melnikov-valkeydata"], "workers_really_restarted": true}
|
||||
PASS: bounded 503 on Valkey/PostgreSQL outage; session and data survive recovery; volumes kept
|
||||
@@ -0,0 +1,67 @@
|
||||
# final verification at 6ea767732e2cf43dbadba6be36186c9ab1bd0a19 (2026-11-30T20:53:41Z)
|
||||
## make check
|
||||
/usr/bin/python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
## make test
|
||||
/usr/bin/python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
## make test-student
|
||||
go test -count=1 ./...
|
||||
? mtusi.ru/messenger-lab2/cmd/messenger [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/api 0.716s
|
||||
ok mtusi.ru/messenger-lab2/internal/auth 0.598s
|
||||
ok mtusi.ru/messenger-lab2/internal/config 0.244s
|
||||
ok mtusi.ru/messenger-lab2/internal/cursor 0.131s
|
||||
ok mtusi.ru/messenger-lab2/internal/model 0.588s
|
||||
? mtusi.ru/messenger-lab2/internal/session [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/store 0.474s
|
||||
ok mtusi.ru/messenger-lab2/internal/uuid 0.826s
|
||||
/usr/bin/python3 student-tests/blackbox.py --base-url "http://localhost:8080"
|
||||
PASS health
|
||||
PASS registration/auth
|
||||
PASS registration validation
|
||||
PASS chats/membership
|
||||
PASS messages
|
||||
PASS pagination
|
||||
PASS concurrent registration
|
||||
PASS concurrent messages
|
||||
PASS logout
|
||||
PASS: lab2 student black-box suite, 78 checks
|
||||
## health/readiness
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
X-Instance-Id: 768a17472e327f41
|
||||
X-Request-Id: 912efd83aa8c9d8f0d5b394368f30687
|
||||
Date: Mon, 30 Nov 2026 20:53:44 GMT
|
||||
Content-Length: 15
|
||||
|
||||
{"status":"ok"}
|
||||
## image
|
||||
id=sha256:888fc6451aded79beaabfd2bc2f6578f25324facc84d3798d8b4d074272270bb size=19580930 created=2026-11-30T23:44:18.694178956+03:00
|
||||
## data
|
||||
users=148
|
||||
chats=61
|
||||
messages=112335
|
||||
migrations=2
|
||||
## volumes
|
||||
mtusi-lab2-melnikov-pgdata
|
||||
mtusi-lab2-melnikov-valkeydata
|
||||
## git
|
||||
M REPORT.md
|
||||
?? MR.md
|
||||
?? evidence/.gitkeep
|
||||
?? evidence/check-validate-tests.txt
|
||||
?? evidence/clean-clone.txt
|
||||
?? evidence/container-checks.json
|
||||
?? evidence/container-checks.txt
|
||||
?? evidence/db-checks.json
|
||||
?? evidence/db-checks.txt
|
||||
?? evidence/expiry.txt
|
||||
?? evidence/explain-level4.txt
|
||||
?? evidence/failure-checks.json
|
||||
?? evidence/failure-checks.txt
|
||||
?? evidence/final-verification.txt
|
||||
?? evidence/persistence-restart.txt
|
||||
?? evidence/public-and-student-tests.txt
|
||||
?? evidence/track5-run.txt
|
||||
?? evidence/track5/
|
||||
@@ -0,0 +1,30 @@
|
||||
# persistence/restart on 6ea767732e2cf43dbadba6be36186c9ab1bd0a19 at 2026-11-30T20:52:09Z
|
||||
## BEFORE
|
||||
/mtusi-lab2-melnikov-api started=2026-11-30T20:52:03.836569575Z health=healthy id=9415b8bf5d52c13e33097fa2156d3a258c1bc0b93b1ff59de3617920f8416a31
|
||||
/mtusi-lab2-melnikov-postgres started=2026-11-30T20:47:13.060213789Z health=healthy id=1c1b0711b1816f01564eadd6f17e73303f7548ccec11c8313cf69a5f6e9b0e1b
|
||||
/mtusi-lab2-melnikov-valkey started=2026-11-30T20:47:12.806011357Z health=healthy id=ed811b1f592afff7937405fb9593d2ffe963ad7ee7212efd3418ac758a4aeef8
|
||||
mtusi-lab2-melnikov-pgdata /var/lib/docker/volumes/mtusi-lab2-melnikov-pgdata/_data
|
||||
mtusi-lab2-melnikov-valkeydata /var/lib/docker/volumes/mtusi-lab2-melnikov-valkeydata/_data
|
||||
users=127
|
||||
chats=52
|
||||
messages=112280
|
||||
migrations=2
|
||||
## make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
/usr/bin/python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
## AFTER
|
||||
/mtusi-lab2-melnikov-api started=2026-11-30T20:52:15.263533308Z health=healthy id=9415b8bf5d52c13e33097fa2156d3a258c1bc0b93b1ff59de3617920f8416a31
|
||||
/mtusi-lab2-melnikov-postgres started=2026-11-30T20:52:09.879834802Z health=healthy id=1c1b0711b1816f01564eadd6f17e73303f7548ccec11c8313cf69a5f6e9b0e1b
|
||||
/mtusi-lab2-melnikov-valkey started=2026-11-30T20:52:09.891634364Z health=healthy id=ed811b1f592afff7937405fb9593d2ffe963ad7ee7212efd3418ac758a4aeef8
|
||||
mtusi-lab2-melnikov-pgdata /var/lib/docker/volumes/mtusi-lab2-melnikov-pgdata/_data
|
||||
mtusi-lab2-melnikov-valkeydata /var/lib/docker/volumes/mtusi-lab2-melnikov-valkeydata/_data
|
||||
users=130
|
||||
chats=53
|
||||
messages=112281
|
||||
migrations=2
|
||||
## API migration logs after restart
|
||||
time=2026-11-30T20:52:03.895Z level=INFO msg="database ready" service=messenger-lab2 app_env=lab migrations=up-to-date
|
||||
time=2026-11-30T20:52:03.922Z level=INFO msg="server listening" service=messenger-lab2 app_env=lab address=[::]:8080 env=lab session_ttl_seconds=3600 graceful_shutdown_seconds=8 version=1.0.0
|
||||
time=2026-11-30T20:52:15.334Z level=INFO msg="database ready" service=messenger-lab2 app_env=lab migrations=up-to-date
|
||||
time=2026-11-30T20:52:15.362Z level=INFO msg="server listening" service=messenger-lab2 app_env=lab address=[::]:8080 env=lab session_ttl_seconds=3600 graceful_shutdown_seconds=8 version=1.0.0
|
||||
@@ -0,0 +1,26 @@
|
||||
# public smoke and student blackbox on 6ea767732e2cf43dbadba6be36186c9ab1bd0a19 at 2026-11-30T20:51:43Z
|
||||
## make test (Python 3.9.6)
|
||||
/usr/bin/python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
## make test-student (Python 3.9.6)
|
||||
go test -count=1 ./...
|
||||
? mtusi.ru/messenger-lab2/cmd/messenger [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/api 0.414s
|
||||
ok mtusi.ru/messenger-lab2/internal/auth 0.805s
|
||||
ok mtusi.ru/messenger-lab2/internal/config 0.144s
|
||||
ok mtusi.ru/messenger-lab2/internal/cursor 0.269s
|
||||
ok mtusi.ru/messenger-lab2/internal/model 0.663s
|
||||
? mtusi.ru/messenger-lab2/internal/session [no test files]
|
||||
ok mtusi.ru/messenger-lab2/internal/store 0.796s
|
||||
ok mtusi.ru/messenger-lab2/internal/uuid 0.919s
|
||||
/usr/bin/python3 student-tests/blackbox.py --base-url "http://localhost:8080"
|
||||
PASS health
|
||||
PASS registration/auth
|
||||
PASS registration validation
|
||||
PASS chats/membership
|
||||
PASS messages
|
||||
PASS pagination
|
||||
PASS concurrent registration
|
||||
PASS concurrent messages
|
||||
PASS logout
|
||||
PASS: lab2 student black-box suite, 78 checks
|
||||
@@ -0,0 +1,3 @@
|
||||
# track 2 experiment on 6ea767732e2cf43dbadba6be36186c9ab1bd0a19 at 2026-11-30T20:52:37Z
|
||||
{"checksum_equal": true, "composite_deep_rows": 50, "counts_equal": true, "dump_bytes": 3362659, "dump_seconds": 0.272, "largest_chat_messages": 60000, "offset_rows": 30050, "restore_seconds": 0.361, "total_messages": 112283, "total_recovery_seconds": 1.616, "write_median_ms": {"chat_only": 45.997, "composite": 46.601}}
|
||||
PASS: track 2 completed; summary in evidence/track5/summary.json
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"source_counts_users_chats_members_messages_migrations": "136|55|90|112283|2",
|
||||
"restored_counts": "136|55|90|112283|2",
|
||||
"counts_equal": true,
|
||||
"per_chat_counts_equal": true,
|
||||
"history_checksum_md5": "d7788d6e93c0eca463069665fb99e6e4",
|
||||
"checksum_equal": true,
|
||||
"selected_message_id": "e77ba05c-13b1-46a4-ba9f-6f630e60f623",
|
||||
"selected_message_equal": true,
|
||||
"dump_seconds": 0.272,
|
||||
"dump_bytes": 3362659,
|
||||
"dump_sha256": "499413a6ee9afccc6daf8d542f29da5ed3bba059b4d44f08285736ae8d0fd9cd",
|
||||
"restore_seconds": 0.361,
|
||||
"total_recovery_seconds_including_container_start": 1.616,
|
||||
"restore_target": {
|
||||
"container": "mtusi-lab2-melnikov-pgrestore",
|
||||
"volume": "mtusi-lab2-melnikov-restoredata",
|
||||
"image": "postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c"
|
||||
},
|
||||
"cleanup": "restore container and volume removed in finally; dump file deleted"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
NAIVE INDEX (chat_id) ONLY
|
||||
|
||||
=== deep keyset page, offset 30000 ===
|
||||
Limit (cost=4289.63..4289.75 rows=50 width=141) (actual time=14.808..14.812 rows=50 loops=1)
|
||||
Buffers: shared hit=807 read=53
|
||||
-> Sort (cost=4289.63..4345.67 rows=22419 width=141) (actual time=14.807..14.809 rows=50 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: top-N heapsort Memory: 37kB
|
||||
Buffers: shared hit=807 read=53
|
||||
-> Bitmap Heap Scan on messages (cost=667.51..3544.88 rows=22419 width=141) (actual time=2.133..12.038 rows=29999 loops=1)
|
||||
Recheck Cond: (chat_id = 'd64fec89-08a6-4948-acc3-4ca99ac54f5a'::uuid)
|
||||
Filter: (ROW(created_at, id) > ROW('2026-01-01 00:00:30.001+00'::timestamp with time zone, 'e77ba05c-13b1-46a4-ba9f-6f630e60f623'::uuid))
|
||||
Rows Removed by Filter: 30001
|
||||
Heap Blocks: exact=801
|
||||
Buffers: shared hit=801 read=53
|
||||
-> Bitmap Index Scan on messages_chat_only_idx (cost=0.00..661.90 rows=59948 width=0) (actual time=0.749..0.750 rows=60000 loops=1)
|
||||
Index Cond: (chat_id = 'd64fec89-08a6-4948-acc3-4ca99ac54f5a'::uuid)
|
||||
Buffers: shared read=53
|
||||
Planning:
|
||||
Buffers: shared hit=101 read=1
|
||||
Planning Time: 0.268 ms
|
||||
Execution Time: 14.859 ms
|
||||
@@ -0,0 +1,34 @@
|
||||
COMPOSITE INDEX (chat_id, created_at, id)
|
||||
|
||||
=== first page ===
|
||||
Limit (cost=0.42..8.43 rows=50 width=141) (actual time=0.021..0.043 rows=50 loops=1)
|
||||
Buffers: shared hit=5
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.42..9618.01 rows=60049 width=141) (actual time=0.020..0.040 rows=50 loops=1)
|
||||
Index Cond: (chat_id = 'd64fec89-08a6-4948-acc3-4ca99ac54f5a'::uuid)
|
||||
Buffers: shared hit=5
|
||||
Planning:
|
||||
Buffers: shared hit=114
|
||||
Planning Time: 0.268 ms
|
||||
Execution Time: 0.060 ms
|
||||
|
||||
=== deep keyset page, offset 30000 ===
|
||||
Limit (cost=0.42..16.77 rows=50 width=141) (actual time=0.018..0.036 rows=50 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.42..7361.87 rows=22511 width=141) (actual time=0.017..0.033 rows=50 loops=1)
|
||||
Index Cond: ((chat_id = 'd64fec89-08a6-4948-acc3-4ca99ac54f5a'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:30.001+00'::timestamp with time zone, 'e77ba05c-13b1-46a4-ba9f-6f630e60f623'::uuid)))
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=113
|
||||
Planning Time: 0.259 ms
|
||||
Execution Time: 0.076 ms
|
||||
|
||||
=== naive OFFSET 30000 ===
|
||||
Limit (cost=4805.29..4813.30 rows=50 width=141) (actual time=11.507..11.525 rows=50 loops=1)
|
||||
Buffers: shared hit=619
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.42..9618.01 rows=60049 width=141) (actual time=0.019..10.880 rows=30050 loops=1)
|
||||
Index Cond: (chat_id = 'd64fec89-08a6-4948-acc3-4ca99ac54f5a'::uuid)
|
||||
Buffers: shared hit=619
|
||||
Planning:
|
||||
Buffers: shared hit=114
|
||||
Planning Time: 0.271 ms
|
||||
Execution Time: 11.542 ms
|
||||
@@ -0,0 +1,180 @@
|
||||
{
|
||||
"track": "track 2: query plan and recovery",
|
||||
"started_at": "2026-11-30T20:52:37.582728Z",
|
||||
"finished_at": "2026-11-30T20:52:42.265423Z",
|
||||
"duration_seconds": 4.683,
|
||||
"code_revision": "6ea767732e2cf43dbadba6be36186c9ab1bd0a19",
|
||||
"git_status": "M REPORT.md\n?? MR.md\n?? evidence/.gitkeep\n?? evidence/check-validate-tests.txt\n?? evidence/clean-clone.txt\n?? evidence/container-checks.json\n?? evidence/container-checks.txt\n?? evidence/db-checks.json\n?? evidence/db-checks.txt\n?? evidence/expiry.txt\n?? evidence/explain-level4.txt\n?? evidence/failure-checks.json\n?? evidence/failure-checks.txt\n?? evidence/final-verification.txt\n?? evidence/persistence-restart.txt\n?? evidence/public-and-student-tests.txt\n?? evidence/track5-run.txt\n?? evidence/track5/",
|
||||
"image": {
|
||||
"reference": "mtusi-messenger-lab2-melnikov:1.0.0",
|
||||
"id": "sha256:888fc6451aded79beaabfd2bc2f6578f25324facc84d3798d8b4d074272270bb",
|
||||
"created": "2026-11-30T23:44:18.694178956+03:00"
|
||||
},
|
||||
"postgres_image": "postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c",
|
||||
"host": {
|
||||
"docker_server_version": "27.4.0",
|
||||
"cpus": 2,
|
||||
"memory_bytes": 2054631424,
|
||||
"architecture": "aarch64"
|
||||
},
|
||||
"declared_limits": {
|
||||
"api": "1 CPU / 256 MiB",
|
||||
"postgres": "1 CPU / 512 MiB",
|
||||
"valkey": "1 CPU / 256 MiB"
|
||||
},
|
||||
"dataset": {
|
||||
"chat_sizes": [
|
||||
[
|
||||
"track5 uneven 60000",
|
||||
60000
|
||||
],
|
||||
[
|
||||
"track5 uneven 25000",
|
||||
25000
|
||||
],
|
||||
[
|
||||
"track5 uneven 10000",
|
||||
10000
|
||||
],
|
||||
[
|
||||
"track5 uneven 4000",
|
||||
4000
|
||||
],
|
||||
[
|
||||
"track5 uneven 900",
|
||||
900
|
||||
],
|
||||
[
|
||||
"track5 uneven 100",
|
||||
100
|
||||
]
|
||||
],
|
||||
"per_chat": [
|
||||
{
|
||||
"title": "track5 uneven 60000",
|
||||
"chat_id": "d64fec89-08a6-4948-acc3-4ca99ac54f5a",
|
||||
"messages": 60000
|
||||
},
|
||||
{
|
||||
"title": "track5 uneven 25000",
|
||||
"chat_id": "979398cd-2134-4956-81fd-ffcb8eb1186a",
|
||||
"messages": 25000
|
||||
},
|
||||
{
|
||||
"title": "track5 uneven 10000",
|
||||
"chat_id": "85769d60-6523-48a5-8225-9674cbb787d4",
|
||||
"messages": 10000
|
||||
},
|
||||
{
|
||||
"title": "track5 uneven 4000",
|
||||
"chat_id": "4d085ff1-c220-47a6-bc56-67af41932543",
|
||||
"messages": 4000
|
||||
},
|
||||
{
|
||||
"title": "track5 uneven 900",
|
||||
"chat_id": "8f800807-2d71-4343-92de-a8268d72494b",
|
||||
"messages": 900
|
||||
},
|
||||
{
|
||||
"title": "track5 uneven 100",
|
||||
"chat_id": "e52a1d35-df52-44e9-9649-099e269b5543",
|
||||
"messages": 100
|
||||
}
|
||||
],
|
||||
"total_messages": 112283,
|
||||
"seed_and_verify_seconds": 0.821,
|
||||
"seed_interval": {
|
||||
"started_at": "2026-11-30T20:52:37.582827Z",
|
||||
"finished_at": "2026-11-30T20:52:38.404018Z"
|
||||
},
|
||||
"sample_timestamps": "research chats sorted by (created_at,id), one-millisecond steps from 2026-01-01T00:00:00Z per chat"
|
||||
},
|
||||
"indexes": {
|
||||
"largest_chat_id": "d64fec89-08a6-4948-acc3-4ca99ac54f5a",
|
||||
"largest_chat_messages": 60000,
|
||||
"deep_offset": 30000,
|
||||
"cursor": {
|
||||
"created_at": "2026-01-01 00:00:30.001+00",
|
||||
"id": "e77ba05c-13b1-46a4-ba9f-6f630e60f623"
|
||||
},
|
||||
"composite_index": {
|
||||
"deep_page_rows_read": 50,
|
||||
"offset_page_rows_read": 30050,
|
||||
"first_page_execution_ms": 0.06,
|
||||
"deep_page_execution_ms": 0.076,
|
||||
"offset_page_execution_ms": 11.542,
|
||||
"planning_and_execution_seconds_for_three_queries": 0.117
|
||||
},
|
||||
"chat_only_index": {
|
||||
"deep_page_execution_ms": 14.859,
|
||||
"plan_uses_chat_only_index": true,
|
||||
"plan_uses_seq_scan": false,
|
||||
"plan_wall_seconds": 0.047
|
||||
},
|
||||
"interval": {
|
||||
"started_at": "2026-11-30T20:52:38.441003Z",
|
||||
"finished_at": "2026-11-30T20:52:38.931837Z",
|
||||
"seconds": 0.491
|
||||
}
|
||||
},
|
||||
"write_cost": {
|
||||
"rows_per_run": 20000,
|
||||
"runs": 3,
|
||||
"metric": "PostgreSQL EXPLAIN ANALYZE Execution Time, ms",
|
||||
"composite": {
|
||||
"runs_ms": [
|
||||
46.601,
|
||||
47.027,
|
||||
46.409
|
||||
],
|
||||
"median_ms": 46.601
|
||||
},
|
||||
"chat_only": {
|
||||
"runs_ms": [
|
||||
45.882,
|
||||
47.201,
|
||||
45.997
|
||||
],
|
||||
"median_ms": 45.997
|
||||
},
|
||||
"interval": {
|
||||
"started_at": "2026-11-30T20:52:38.931857Z",
|
||||
"finished_at": "2026-11-30T20:52:39.725932Z",
|
||||
"seconds": 0.794
|
||||
}
|
||||
},
|
||||
"backup_restore": {
|
||||
"source_counts_users_chats_members_messages_migrations": "136|55|90|112283|2",
|
||||
"restored_counts": "136|55|90|112283|2",
|
||||
"counts_equal": true,
|
||||
"per_chat_counts_equal": true,
|
||||
"history_checksum_md5": "d7788d6e93c0eca463069665fb99e6e4",
|
||||
"checksum_equal": true,
|
||||
"selected_message_id": "e77ba05c-13b1-46a4-ba9f-6f630e60f623",
|
||||
"selected_message_equal": true,
|
||||
"dump_seconds": 0.272,
|
||||
"dump_bytes": 3362659,
|
||||
"dump_sha256": "499413a6ee9afccc6daf8d542f29da5ed3bba059b4d44f08285736ae8d0fd9cd",
|
||||
"restore_seconds": 0.361,
|
||||
"total_recovery_seconds_including_container_start": 1.616,
|
||||
"restore_target": {
|
||||
"container": "mtusi-lab2-melnikov-pgrestore",
|
||||
"volume": "mtusi-lab2-melnikov-restoredata",
|
||||
"image": "postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c"
|
||||
},
|
||||
"cleanup": "restore container and volume removed in finally; dump file deleted",
|
||||
"interval": {
|
||||
"started_at": "2026-11-30T20:52:39.725958Z",
|
||||
"finished_at": "2026-11-30T20:52:42.208769Z",
|
||||
"seconds": 2.483
|
||||
}
|
||||
},
|
||||
"artifacts_dir_removed_after_run": "temporary directory",
|
||||
"measurement_notes": [
|
||||
"EXPLAIN elapsed values are PostgreSQL Execution Time on the local container; wall times include psql/docker exec overhead.",
|
||||
"deep page cursor is a real (created_at, id) row at the recorded OFFSET; the OFFSET comparison scans the same prefix.",
|
||||
"write cost measures INSERT plus index maintenance for 20 000 synthetic rows, 3 runs per index, median reported.",
|
||||
"backup is a single pg_dump custom-format snapshot; no WAL archiving, so RPO is the age of the last dump.",
|
||||
"restore target is a new PostgreSQL container with a new named volume, removed after reconciliation."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"rows_per_run": 20000,
|
||||
"runs": 3,
|
||||
"metric": "PostgreSQL EXPLAIN ANALYZE Execution Time, ms",
|
||||
"composite": {
|
||||
"runs_ms": [
|
||||
46.601,
|
||||
47.027,
|
||||
46.409
|
||||
],
|
||||
"median_ms": 46.601
|
||||
},
|
||||
"chat_only": {
|
||||
"runs_ms": [
|
||||
45.882,
|
||||
47.201,
|
||||
45.997
|
||||
],
|
||||
"median_ms": 45.997
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
module mtusi.ru/messenger-lab2
|
||||
|
||||
go 1.25.1
|
||||
|
||||
require (
|
||||
github.com/jackc/pgx/v5 v5.7.2
|
||||
github.com/redis/go-redis/v9 v9.7.0
|
||||
golang.org/x/crypto v0.31.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
|
||||
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
|
||||
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,229 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/auth"
|
||||
"mtusi.ru/messenger-lab2/internal/model"
|
||||
"mtusi.ru/messenger-lab2/internal/session"
|
||||
"mtusi.ru/messenger-lab2/internal/store"
|
||||
"mtusi.ru/messenger-lab2/internal/uuid"
|
||||
)
|
||||
|
||||
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// identity is the authenticated principal derived only from the Bearer
|
||||
// session. X-User-Id is not consulted anywhere in this package.
|
||||
type identity struct {
|
||||
user model.User
|
||||
token string
|
||||
}
|
||||
|
||||
// App is the HTTP layer. PostgreSQL is the source of truth for users, chats
|
||||
// and messages; Valkey is the source of truth for sessions. App adds request
|
||||
// validation, authentication and contract mapping.
|
||||
type App struct {
|
||||
store *store.Store
|
||||
sessions *session.Store
|
||||
log *slog.Logger
|
||||
ready atomic.Bool
|
||||
maxBody int64
|
||||
instanceID string
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
// New creates the HTTP application. The dummy Argon2id hash is generated once
|
||||
// so login can spend the same work for an unknown username as for a known one.
|
||||
func New(repository *store.Store, sessions *session.Store, logger *slog.Logger) (*App, error) {
|
||||
dummy, err := auth.Hash("dummy-password-never-used-for-login")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
app := &App{
|
||||
store: repository,
|
||||
sessions: sessions,
|
||||
log: logger,
|
||||
maxBody: maxBodyBytes,
|
||||
instanceID: uuid.NewRandom(8),
|
||||
dummyHash: dummy,
|
||||
}
|
||||
app.ready.Store(true)
|
||||
return app, nil
|
||||
}
|
||||
|
||||
// SetReady flips readiness. The main process clears it as soon as SIGTERM is
|
||||
// received and before http.Server.Shutdown stops accepting connections.
|
||||
func (a *App) SetReady(ready bool) { a.ready.Store(ready) }
|
||||
|
||||
// Handler returns the fully instrumented handler.
|
||||
func (a *App) Handler() http.Handler {
|
||||
return a.withObservability(a)
|
||||
}
|
||||
|
||||
// ServeHTTP routes the lab2 API. Method mismatches become 404 in the contract
|
||||
// error shape because the public error enum has no method_not_allowed code.
|
||||
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/health/live":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
case "/health/ready":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.readiness(w, r)
|
||||
case "/api/v1/users":
|
||||
if r.Method != http.MethodPost {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.createUser(w, r)
|
||||
case "/api/v1/auth/sessions":
|
||||
if r.Method != http.MethodPost {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.createSession(w, r)
|
||||
case "/api/v1/auth/sessions/current":
|
||||
if r.Method != http.MethodDelete {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.withAuth(a.logout).ServeHTTP(w, r)
|
||||
case "/api/v1/users/me":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.withAuth(a.currentUser).ServeHTTP(w, r)
|
||||
case "/api/v1/chats":
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
a.withAuth(a.listChats).ServeHTTP(w, r)
|
||||
case http.MethodPost:
|
||||
a.withAuth(a.createChat).ServeHTTP(w, r)
|
||||
default:
|
||||
a.notFound(w, r)
|
||||
}
|
||||
default:
|
||||
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/chats/"); ok {
|
||||
// Authentication runs before resource resolution: an anonymous
|
||||
// request must not learn whether a chat id exists.
|
||||
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
a.chatRoutes(w, r, rest, actor)
|
||||
}).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
a.notFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) chatRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
|
||||
parts := splitPath(rest)
|
||||
if len(parts) == 1 {
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.getChat(w, r, parts[0], actor)
|
||||
return
|
||||
}
|
||||
if len(parts) == 2 && parts[1] == "messages" {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
a.listMessages(w, r, parts[0], actor)
|
||||
case http.MethodPost:
|
||||
a.createMessage(w, r, parts[0], actor)
|
||||
default:
|
||||
a.notFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
a.notFound(w, r)
|
||||
}
|
||||
|
||||
// withAuth resolves the Bearer session before the wrapped handler runs.
|
||||
func (a *App) withAuth(next func(http.ResponseWriter, *http.Request, identity)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
actor, problem := a.authenticate(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
next(w, r, actor)
|
||||
}
|
||||
}
|
||||
|
||||
// readiness reports whether the mandatory synchronous path can be served.
|
||||
// Both PostgreSQL and Valkey are critical: without PostgreSQL the API cannot
|
||||
// answer, and without Valkey it cannot authenticate a single protected call.
|
||||
func (a *App) readiness(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.ready.Load() {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
dbCtx, dbCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
|
||||
dbErr := a.store.Ping(dbCtx)
|
||||
dbCancel()
|
||||
if dbErr != nil {
|
||||
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "postgres", "error", dbErr)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
cacheCtx, cacheCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
|
||||
cacheErr := a.sessions.Ping(cacheCtx)
|
||||
cacheCancel()
|
||||
if cacheErr != nil {
|
||||
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "valkey", "error", cacheErr)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
// writeJSON encodes a success response. X-Request-Id is set by middleware
|
||||
// before the handler runs, so even a marshal-time 500 keeps the header.
|
||||
func (a *App) writeJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
a.log.Error("response encoding failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if _, err := w.Write(data); err != nil {
|
||||
a.log.Debug("response write failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func trimPathPrefix(value, prefix string) (string, bool) {
|
||||
if !strings.HasPrefix(value, prefix) || len(value) == len(prefix) {
|
||||
return "", false
|
||||
}
|
||||
return value[len(prefix):], true
|
||||
}
|
||||
|
||||
func splitPath(value string) []string {
|
||||
parts := strings.Split(value, "/")
|
||||
for _, part := range parts {
|
||||
if part == "" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return parts
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/cursor"
|
||||
"mtusi.ru/messenger-lab2/internal/store"
|
||||
"mtusi.ru/messenger-lab2/internal/uuid"
|
||||
)
|
||||
|
||||
type createChatRequest struct {
|
||||
Title *string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (a *App) createChat(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
var request createChatRequest
|
||||
if problem := a.decodeJSON(r, &request, "title", "member_ids"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Title == nil {
|
||||
a.writeError(w, r, invalidRequest("title is required"))
|
||||
return
|
||||
}
|
||||
if problem := validateTitle(*request.Title); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if len(request.MemberIDs) < 1 || len(request.MemberIDs) > 100 {
|
||||
a.writeError(w, r, invalidRequest("member_ids must contain 1 to 100 members"))
|
||||
return
|
||||
}
|
||||
|
||||
members := make([]string, 0, len(request.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(request.MemberIDs))
|
||||
callerIncluded := false
|
||||
for _, rawID := range request.MemberIDs {
|
||||
id, ok := uuid.Normalize(rawID)
|
||||
if !ok {
|
||||
a.writeError(w, r, invalidRequest("every member_ids entry must be a UUID"))
|
||||
return
|
||||
}
|
||||
if _, duplicate := seen[id]; duplicate {
|
||||
a.writeError(w, r, invalidRequest("member_ids must not contain duplicates"))
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
members = append(members, id)
|
||||
if id == actor.user.ID {
|
||||
callerIncluded = true
|
||||
}
|
||||
}
|
||||
if !callerIncluded {
|
||||
a.writeError(w, r, invalidRequest("caller must be present in member_ids"))
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := a.store.CreateChat(r.Context(), *request.Title, members, actor.user.ID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnknownMember):
|
||||
a.writeError(w, r, invalidRequest("every member_ids entry must reference an existing user"))
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (a *App) listChats(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
limit, rawCursor, problem := a.pageParams(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
var position *cursor.Cursor
|
||||
if rawCursor != "" {
|
||||
decoded, err := cursor.Decode(rawCursor, cursor.ScopeChats, "")
|
||||
if err != nil {
|
||||
a.writeError(w, r, invalidRequest("cursor is invalid for this request"))
|
||||
return
|
||||
}
|
||||
position = &decoded
|
||||
}
|
||||
|
||||
page, err := a.store.Chats(r.Context(), actor.user.ID, position, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (a *App) getChat(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
chat, err := a.store.ChatForUser(r.Context(), chatID, actor.user.ID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
// normalizePathUUID validates a path identifier before any database access.
|
||||
func normalizePathUUID(raw, field string) (string, *apiError) {
|
||||
id, ok := uuid.Normalize(raw)
|
||||
if !ok {
|
||||
return "", invalidRequest(field + " must be a UUID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/uuid"
|
||||
)
|
||||
|
||||
// apiError is a contract-shaped error: HTTP status, machine-readable code, a
|
||||
// safe human-readable message and an optional authentication challenge. The
|
||||
// request id is filled from the request context at write time.
|
||||
type apiError struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
challenge string
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.code + ": " + e.message }
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
var (
|
||||
statusInvalidRequest = &apiError{status: http.StatusBadRequest, code: "invalid_request", message: "request validation failed"}
|
||||
statusNotFound = &apiError{status: http.StatusNotFound, code: "not_found", message: "object not found"}
|
||||
statusConflict = &apiError{status: http.StatusConflict, code: "conflict", message: "object already exists"}
|
||||
statusPayloadTooLarge = &apiError{status: http.StatusRequestEntityTooLarge, code: "payload_too_large", message: "request body is too large"}
|
||||
statusUnsupportedMediaType = &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: "Content-Type must be application/json"}
|
||||
statusUnavailable = &apiError{status: http.StatusServiceUnavailable, code: "unavailable", message: "a required dependency is unavailable"}
|
||||
statusInternal = &apiError{status: http.StatusInternalServerError, code: "internal_error", message: "internal server error"}
|
||||
)
|
||||
|
||||
func invalidRequest(message string) *apiError {
|
||||
return &apiError{status: http.StatusBadRequest, code: "invalid_request", message: message}
|
||||
}
|
||||
|
||||
func unauthorizedBasic() *apiError {
|
||||
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "invalid username or password", challenge: basicChallenge}
|
||||
}
|
||||
|
||||
func unauthorizedBearer() *apiError {
|
||||
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "a valid bearer session is required", challenge: bearerChallenge}
|
||||
}
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
|
||||
type errorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// writeError writes a JSON error whose request_id matches X-Request-Id. The
|
||||
// message never contains SQL, stack traces, credentials or object existence
|
||||
// details for foreign resources.
|
||||
func (a *App) writeError(w http.ResponseWriter, r *http.Request, problem *apiError) {
|
||||
requestID := requestIDFromContext(r.Context())
|
||||
if requestID == "" {
|
||||
requestID = w.Header().Get("X-Request-Id")
|
||||
}
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewRandom(16)
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
if problem.challenge != "" {
|
||||
w.Header().Set("WWW-Authenticate", problem.challenge)
|
||||
}
|
||||
a.writeJSON(w, r, problem.status, errorEnvelope{Error: errorBody{
|
||||
Code: problem.code,
|
||||
Message: problem.message,
|
||||
RequestID: requestID,
|
||||
}})
|
||||
}
|
||||
|
||||
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
}
|
||||
|
||||
type requestIDContextKey struct{}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
value, _ := ctx.Value(requestIDContextKey{}).(string)
|
||||
return value
|
||||
}
|
||||
|
||||
// statusWriter records the status code and byte count for logs and for the
|
||||
// panic path, so a partially written response is not written twice.
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(code int) {
|
||||
if w.wrote {
|
||||
return
|
||||
}
|
||||
w.wrote = true
|
||||
w.status = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(data []byte) (int, error) {
|
||||
if !w.wrote {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
written, err := w.ResponseWriter.Write(data)
|
||||
w.bytes += written
|
||||
return written, err
|
||||
}
|
||||
|
||||
func (a *App) withObservability(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
requestID := uuid.NewRandom(16)
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
// Stable for the life of the process. lab2 does not require it, but it
|
||||
// is the same identifier the next lab uses and it makes log correlation
|
||||
// unambiguous during restart experiments.
|
||||
w.Header().Set("X-Instance-Id", a.instanceID)
|
||||
r = r.WithContext(context.WithValue(r.Context(), requestIDContextKey{}, requestID))
|
||||
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
a.log.Error("panic while handling request",
|
||||
"request_id", requestID,
|
||||
"instance_id", a.instanceID,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"panic", recovered,
|
||||
)
|
||||
if !writer.wrote {
|
||||
a.writeError(writer, r, statusInternal)
|
||||
}
|
||||
}
|
||||
level := slog.LevelInfo
|
||||
if r.URL.Path == "/health/live" || r.URL.Path == "/health/ready" {
|
||||
level = slog.LevelDebug
|
||||
}
|
||||
a.log.Log(r.Context(), level, "http request",
|
||||
"request_id", requestID,
|
||||
"instance_id", a.instanceID,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", writer.status,
|
||||
"duration_ms", float64(time.Since(start).Microseconds())/1000.0,
|
||||
"bytes", writer.bytes,
|
||||
)
|
||||
}()
|
||||
|
||||
next.ServeHTTP(writer, r)
|
||||
})
|
||||
}
|
||||
|
||||
// atomicBool keeps the readiness flag readable from the signal goroutine
|
||||
// without importing sync/atomic into every handler file.
|
||||
type atomicBool struct{ value atomic.Bool }
|
||||
|
||||
func (b *atomicBool) Store(value bool) { b.value.Store(value) }
|
||||
func (b *atomicBool) Load() bool { return b.value.Load() }
|
||||
@@ -0,0 +1,121 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/cursor"
|
||||
"mtusi.ru/messenger-lab2/internal/store"
|
||||
)
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text *string `json:"text"`
|
||||
}
|
||||
|
||||
func (a *App) createMessage(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
// Resource access is checked before the body is decoded so a foreign chat
|
||||
// always looks like a missing chat, independent of the submitted payload.
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var request createMessageRequest
|
||||
if problem := a.decodeJSON(r, &request, "text"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Text == nil {
|
||||
a.writeError(w, r, invalidRequest("text is required"))
|
||||
return
|
||||
}
|
||||
if problem := validateMessageText(*request.Text); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
|
||||
message, err := a.store.CreateMessage(r.Context(), chatID, actor.user.ID, *request.Text)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, message)
|
||||
}
|
||||
|
||||
func (a *App) listMessages(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
// A foreign/nonexistent chat is always 404, even if the query itself is
|
||||
// malformed; this avoids making object existence observable.
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
limit, rawCursor, problem := a.pageParams(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
var position *cursor.Cursor
|
||||
if rawCursor != "" {
|
||||
decoded, err := cursor.Decode(rawCursor, cursor.ScopeMessages, chatID)
|
||||
if err != nil {
|
||||
a.writeError(w, r, invalidRequest("cursor is invalid for this chat"))
|
||||
return
|
||||
}
|
||||
position = &decoded
|
||||
}
|
||||
|
||||
page, err := a.store.Messages(r.Context(), chatID, position, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/auth"
|
||||
"mtusi.ru/messenger-lab2/internal/model"
|
||||
"mtusi.ru/messenger-lab2/internal/session"
|
||||
"mtusi.ru/messenger-lab2/internal/store"
|
||||
)
|
||||
|
||||
// createSession is the only endpoint that accepts Basic credentials. It never
|
||||
// accepts a JSON body and never reveals whether the username exists.
|
||||
func (a *App) createSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, err := auth.ParseBasic(r.Header.Get("Authorization"))
|
||||
if err != nil {
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
// Reject values that could never have been registered before touching the
|
||||
// database (invalid UTF-8 would otherwise become a 500 from PostgreSQL).
|
||||
if !usernameAllowed(username) || !validLoginPassword(password) {
|
||||
_, _ = auth.Verify(password, a.dummyHash)
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := a.store.UserByUsername(r.Context(), username)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
// Spend the same KDF work for an unknown username so response timing
|
||||
// does not disclose account existence.
|
||||
_, _ = auth.Verify(password, a.dummyHash)
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("login database unavailable", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("login lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
|
||||
match, err := auth.Verify(password, passwordHash)
|
||||
if err != nil {
|
||||
// A corrupt stored hash is an internal data problem, not a wrong
|
||||
// password; do not silently lock the account out with a 401 log line.
|
||||
a.log.Error("stored password hash is invalid", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !match {
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
|
||||
token, expiresAt, err := a.sessions.Create(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
a.log.Error("session creation failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
if errors.Is(err, session.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, model.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: model.Time{Time: expiresAt},
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
// authenticate accepts only "Authorization: Bearer <opaque token>". A Basic
|
||||
// header on a business endpoint, a missing header and an X-User-Id header all
|
||||
// produce the same 401 challenge.
|
||||
func (a *App) authenticate(r *http.Request) (identity, *apiError) {
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok || !auth.ValidTokenShape(token) {
|
||||
return identity{}, unauthorizedBearer()
|
||||
}
|
||||
|
||||
userID, err := a.sessions.Get(r.Context(), token)
|
||||
switch {
|
||||
case errors.Is(err, session.ErrInvalid):
|
||||
return identity{}, unauthorizedBearer()
|
||||
case errors.Is(err, session.ErrUnavailable):
|
||||
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusUnavailable
|
||||
case err != nil:
|
||||
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusInternal
|
||||
}
|
||||
|
||||
user, err := a.store.UserByID(r.Context(), userID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
// A session pointing at a missing user is not usable. Deleting it is
|
||||
// best effort; the response is the normal 401 either way.
|
||||
_ = a.sessions.Delete(r.Context(), token)
|
||||
return identity{}, unauthorizedBearer()
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusUnavailable
|
||||
case err != nil:
|
||||
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusInternal
|
||||
}
|
||||
return identity{user: user, token: token}, nil
|
||||
}
|
||||
|
||||
// logout revokes the current server-side session. The response has no body.
|
||||
func (a *App) logout(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
if err := a.sessions.Delete(r.Context(), actor.token); err != nil {
|
||||
a.log.Error("logout failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
if errors.Is(err, session.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func bearerToken(header string) (string, bool) {
|
||||
trimmed := strings.TrimSpace(header)
|
||||
space := strings.IndexByte(trimmed, ' ')
|
||||
if space <= 0 {
|
||||
return "", false
|
||||
}
|
||||
if !strings.EqualFold(trimmed[:space], "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
token := trimmed[space+1:]
|
||||
if token == "" || strings.ContainsAny(token, " \t") {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
// validLoginPassword mirrors the registration policy. A login with an
|
||||
// out-of-range password cannot match any stored hash and must still look like
|
||||
// an ordinary 401.
|
||||
func validLoginPassword(password string) bool {
|
||||
if !utf8.ValidString(password) || isBlank(password) {
|
||||
return false
|
||||
}
|
||||
count := utf8.RuneCountInString(password)
|
||||
return count >= 12 && count <= 128
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/auth"
|
||||
"mtusi.ru/messenger-lab2/internal/store"
|
||||
)
|
||||
|
||||
type createUserRequest struct {
|
||||
Username *string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
|
||||
func (a *App) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var request createUserRequest
|
||||
if problem := a.decodeJSON(r, &request, "username", "display_name", "password"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Username == nil {
|
||||
a.writeError(w, r, invalidRequest("username is required"))
|
||||
return
|
||||
}
|
||||
if request.DisplayName == nil {
|
||||
a.writeError(w, r, invalidRequest("display_name is required"))
|
||||
return
|
||||
}
|
||||
if request.Password == nil {
|
||||
a.writeError(w, r, invalidRequest("password is required"))
|
||||
return
|
||||
}
|
||||
if problem := validateUsername(*request.Username); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if problem := validateDisplayName(*request.DisplayName); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if problem := validatePassword(*request.Password); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := auth.Hash(*request.Password)
|
||||
if err != nil {
|
||||
a.log.Error("password hashing failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := a.store.CreateUser(r.Context(), *request.Username, *request.DisplayName, passwordHash)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUsernameTaken):
|
||||
a.writeError(w, r, statusConflict)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (a *App) currentUser(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
a.writeJSON(w, r, http.StatusOK, actor.user)
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// decodeJSON enforces the contract's JSON rules: application/json, strict
|
||||
// UTF-8, exactly one object with exactly the documented top-level keys, no
|
||||
// unknown/duplicate fields and a bounded body size.
|
||||
//
|
||||
// encoding/json matches struct fields case-insensitively even with
|
||||
// DisallowUnknownFields, so the exact key set is checked separately on the
|
||||
// token stream. That also rejects Unicode case-folding aliases and duplicates.
|
||||
func (a *App) decodeJSON(r *http.Request, destination any, allowedKeys ...string) *apiError {
|
||||
if raw := r.Header.Get("Content-Type"); raw != "" {
|
||||
mediaType, _, err := mime.ParseMediaType(raw)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return statusUnsupportedMediaType
|
||||
}
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, a.maxBody+1))
|
||||
if err != nil {
|
||||
return invalidRequest("could not read request body")
|
||||
}
|
||||
if int64(len(body)) > a.maxBody {
|
||||
return statusPayloadTooLarge
|
||||
}
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return invalidRequest("request body must not be empty")
|
||||
}
|
||||
if !utf8.Valid(body) {
|
||||
return invalidRequest("request body must be valid UTF-8")
|
||||
}
|
||||
if problem := validateTopLevelKeys(body, allowedKeys); problem != nil {
|
||||
return problem
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return invalidRequest("request body does not match the documented schema")
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return invalidRequest("request body must contain exactly one JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateTopLevelKeys(body []byte, allowedKeys []string) *apiError {
|
||||
allowed := make(map[string]struct{}, len(allowedKeys))
|
||||
for _, key := range allowedKeys {
|
||||
allowed[key] = struct{}{}
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
token, err := decoder.Token()
|
||||
if err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
opening, ok := token.(json.Delim)
|
||||
if !ok || opening != '{' {
|
||||
return invalidRequest("request body must be a JSON object")
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(allowedKeys))
|
||||
for decoder.More() {
|
||||
token, err := decoder.Token()
|
||||
if err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
key, ok := token.(string)
|
||||
if !ok {
|
||||
return invalidRequest("request body must contain string field names")
|
||||
}
|
||||
if _, duplicate := seen[key]; duplicate {
|
||||
return invalidRequest("request body must not contain duplicate fields")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
if _, ok := allowed[key]; !ok {
|
||||
return invalidRequest("request body contains an unknown field")
|
||||
}
|
||||
var value json.RawMessage
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
}
|
||||
if _, err := decoder.Token(); err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return invalidRequest("request body must contain exactly one JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pageParams parses limit/cursor. Cursor decoding happens after membership is
|
||||
// verified so a foreign chat cannot be probed with a malformed cursor.
|
||||
func (a *App) pageParams(r *http.Request) (int, string, *apiError) {
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
return 0, "", invalidRequest("query string is not valid")
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if values, present := query["limit"]; present {
|
||||
if len(values) != 1 {
|
||||
return 0, "", invalidRequest("limit must be specified once")
|
||||
}
|
||||
parsed, err := strconv.Atoi(values[0])
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
return 0, "", invalidRequest("limit must be an integer between 1 and 100")
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
|
||||
cursor := ""
|
||||
if values, present := query["cursor"]; present {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return 0, "", invalidRequest("cursor must be a non-empty string")
|
||||
}
|
||||
cursor = values[0]
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
|
||||
func validateUsername(value string) *apiError {
|
||||
if !usernameAllowed(value) {
|
||||
return invalidRequest("username must match [a-z0-9_]{3,32}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDisplayName(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("display_name must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
|
||||
return invalidRequest("display_name must contain 1 to 100 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateTitle(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("title must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
|
||||
return invalidRequest("title must contain 1 to 100 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateMessageText(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("text must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 4000 {
|
||||
return invalidRequest("text must contain 1 to 4000 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validatePassword implements the registration rule: 12 to 128 Unicode code
|
||||
// points, not only whitespace. The exact bytes are handed to Argon2id, so
|
||||
// Unicode passwords are neither truncated nor normalized by the server.
|
||||
func validatePassword(value string) *apiError {
|
||||
if !utf8.ValidString(value) {
|
||||
return invalidRequest("password must be valid UTF-8")
|
||||
}
|
||||
if isBlank(value) {
|
||||
return invalidRequest("password must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 12 || count > 128 {
|
||||
return invalidRequest("password must contain 12 to 128 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isBlank(value string) bool {
|
||||
return strings.TrimSpace(value) == ""
|
||||
}
|
||||
|
||||
// usernameAllowed is a byte-wise equivalent of the contract pattern
|
||||
// ^[a-z0-9_]{3,32}$; non-ASCII bytes can never match.
|
||||
func usernameAllowed(value string) bool {
|
||||
if len(value) < 3 || len(value) > 32 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type sampleRequest struct {
|
||||
Username *string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
|
||||
func decodeTestApp() *App { return &App{maxBody: maxBodyBytes} }
|
||||
|
||||
func TestDecodeJSONAcceptsDocumentedObject(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
body := `{"username":"alice","display_name":"Алиса","password":"long-enough-secret"}`
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem != nil {
|
||||
t.Fatalf("decodeJSON rejected a valid body: %v", problem)
|
||||
}
|
||||
if destination.Username == nil || *destination.Username != "alice" {
|
||||
t.Fatalf("decoded value = %+v", destination)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsContractViolations(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
contentType string
|
||||
status int
|
||||
}{
|
||||
{"empty", "", "application/json", http.StatusBadRequest},
|
||||
{"whitespace only", " \n", "application/json", http.StatusBadRequest},
|
||||
{"malformed", `{"username":`, "application/json", http.StatusBadRequest},
|
||||
{"array instead of object", `[]`, "application/json", http.StatusBadRequest},
|
||||
{"string instead of object", `"x"`, "application/json", http.StatusBadRequest},
|
||||
{"unknown field", `{"username":"a","display_name":"b","password":"c","extra":1}`, "application/json", http.StatusBadRequest},
|
||||
{"duplicate field", `{"username":"a","username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
|
||||
{"uppercase alias", `{"Username":"a","display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
|
||||
{"alias beside correct key", `{"username":"a","Username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
|
||||
{"wrong type", `{"username":1,"display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
|
||||
{"two values", `{"username":"a","display_name":"b","password":"c"}{}`, "application/json", http.StatusBadRequest},
|
||||
{"wrong content type", `{"username":"a","display_name":"b","password":"c"}`, "text/plain", http.StatusUnsupportedMediaType},
|
||||
{"malformed content type", `{"username":"a","display_name":"b","password":"c"}`, "application/json; charset", http.StatusUnsupportedMediaType},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(tc.body))
|
||||
request.Header.Set("Content-Type", tc.contentType)
|
||||
var destination sampleRequest
|
||||
problem := app.decodeJSON(request, &destination, "username", "display_name", "password")
|
||||
if problem == nil {
|
||||
t.Fatal("decodeJSON accepted an invalid body")
|
||||
}
|
||||
if problem.status != tc.status {
|
||||
t.Fatalf("status = %d, want %d", problem.status, tc.status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsInvalidUTF8(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
body := append([]byte(`{"username":"`), 0xff, 0xfe)
|
||||
body = append(body, []byte(`","display_name":"b","password":"c"}`)...)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", bytes.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem == nil || problem.status != http.StatusBadRequest {
|
||||
t.Fatalf("invalid UTF-8 was not rejected with 400: %v", problem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsOversizedBody(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
app.maxBody = 16
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":"`+strings.Repeat("x", 64)+`"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username"); problem == nil || problem.status != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("oversized body = %v, want 413", problem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsernameValidation(t *testing.T) {
|
||||
valid := []string{"abc", "a_b9", strings.Repeat("a", 32)}
|
||||
for _, value := range valid {
|
||||
if problem := validateUsername(value); problem != nil {
|
||||
t.Fatalf("validateUsername(%q) = %v", value, problem)
|
||||
}
|
||||
}
|
||||
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "a-b", "a b", "aбв", "abc\n"}
|
||||
for _, value := range invalid {
|
||||
if problem := validateUsername(value); problem == nil {
|
||||
t.Fatalf("validateUsername accepted %q", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLengthValidationCountsCodePoints(t *testing.T) {
|
||||
if problem := validateDisplayName(strings.Repeat("😀", 100)); problem != nil {
|
||||
t.Fatalf("100 code points rejected: %v", problem)
|
||||
}
|
||||
if problem := validateDisplayName(strings.Repeat("😀", 101)); problem == nil {
|
||||
t.Fatal("101 code points accepted")
|
||||
}
|
||||
if problem := validateDisplayName(" "); problem == nil {
|
||||
t.Fatal("blank display_name accepted")
|
||||
}
|
||||
|
||||
if problem := validateMessageText(strings.Repeat("я", 4000)); problem != nil {
|
||||
t.Fatalf("4000 code points rejected: %v", problem)
|
||||
}
|
||||
if problem := validateMessageText(strings.Repeat("я", 4001)); problem == nil {
|
||||
t.Fatal("4001 code points accepted")
|
||||
}
|
||||
if problem := validateMessageText(" \t\n"); problem == nil {
|
||||
t.Fatal("blank message accepted")
|
||||
}
|
||||
|
||||
if problem := validatePassword(strings.Repeat("p", 12)); problem != nil {
|
||||
t.Fatalf("12-character password rejected: %v", problem)
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 11)); problem == nil {
|
||||
t.Fatal("11-character password accepted")
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 128)); problem != nil {
|
||||
t.Fatalf("128-character password rejected: %v", problem)
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 129)); problem == nil {
|
||||
t.Fatal("129-character password accepted")
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat(" ", 12)); problem == nil {
|
||||
t.Fatal("whitespace password accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageParams(t *testing.T) {
|
||||
valid := map[string][2]any{
|
||||
"": {50, ""},
|
||||
"?limit=1": {1, ""},
|
||||
"?limit=100": {100, ""},
|
||||
"?limit=7&cursor=x": {7, "x"},
|
||||
}
|
||||
for query, want := range valid {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
|
||||
limit, cursor, problem := decodeTestApp().pageParams(request)
|
||||
if problem != nil {
|
||||
t.Fatalf("pageParams(%q) = %v", query, problem)
|
||||
}
|
||||
if limit != want[0].(int) || cursor != want[1].(string) {
|
||||
t.Fatalf("pageParams(%q) = %d,%q", query, limit, cursor)
|
||||
}
|
||||
}
|
||||
invalid := []string{"?limit=0", "?limit=101", "?limit=abc", "?limit=", "?limit=1&limit=2", "?cursor=", "?cursor=a&cursor=b", "?limit=1;cursor=x"}
|
||||
for _, query := range invalid {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
|
||||
if _, _, problem := decodeTestApp().pageParams(request); problem == nil {
|
||||
t.Fatalf("pageParams accepted %q", query)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerTokenParsing(t *testing.T) {
|
||||
token := strings.Repeat("a", 43)
|
||||
cases := map[string]string{
|
||||
"Bearer " + token: token,
|
||||
"bearer " + token: token,
|
||||
"BEARER " + token: token,
|
||||
}
|
||||
for header, want := range cases {
|
||||
got, ok := bearerToken(header)
|
||||
if !ok || got != want {
|
||||
t.Fatalf("bearerToken(%q) = %q,%v", header, got, ok)
|
||||
}
|
||||
}
|
||||
for _, header := range []string{"", "Bearer", "Bearer ", "Basic abc", "Bearer a b", "Token " + token} {
|
||||
if _, ok := bearerToken(header); ok {
|
||||
t.Fatalf("bearerToken accepted %q", header)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorEnvelopeShape(t *testing.T) {
|
||||
envelope := errorEnvelope{Error: errorBody{Code: "invalid_request", Message: "x", RequestID: "id"}}
|
||||
data, err := json.Marshal(envelope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(data) != `{"error":{"code":"invalid_request","message":"x","request_id":"id"}}` {
|
||||
t.Fatalf("unexpected error JSON: %s", data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashAndVerify(t *testing.T) {
|
||||
password := "correct horse battery staple"
|
||||
encoded, err := Hash(password)
|
||||
if err != nil {
|
||||
t.Fatalf("Hash: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(encoded, "$argon2id$v=19$m=19456,t=2,p=1$") {
|
||||
t.Fatalf("unexpected PHC prefix: %q", encoded)
|
||||
}
|
||||
match, err := Verify(password, encoded)
|
||||
if err != nil || !match {
|
||||
t.Fatalf("Verify(correct) = %v, %v", match, err)
|
||||
}
|
||||
match, err = Verify(password+"x", encoded)
|
||||
if err != nil || match {
|
||||
t.Fatalf("Verify(wrong) = %v, %v", match, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashUnicodeAndMaximumLength(t *testing.T) {
|
||||
for _, password := range []string{
|
||||
"pässwörd:12✓",
|
||||
strings.Repeat("界", 128),
|
||||
" leading and trailing spaces ",
|
||||
} {
|
||||
encoded, err := Hash(password)
|
||||
if err != nil {
|
||||
t.Fatalf("Hash(%q): %v", password, err)
|
||||
}
|
||||
if match, err := Verify(password, encoded); err != nil || !match {
|
||||
t.Fatalf("Verify(%q) = %v, %v", password, match, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashUsesRandomSalt(t *testing.T) {
|
||||
first, err := Hash("same-password-twice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := Hash("same-password-twice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("two hashes of the same password are identical")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedHashes(t *testing.T) {
|
||||
for _, encoded := range []string{
|
||||
"",
|
||||
"plaintext",
|
||||
"$2a$10$abcdefghijklmnopqrstuv",
|
||||
"$argon2id$v=19$m=19456,t=2,p=1$not-base64$hash",
|
||||
"$argon2id$v=19$m=1,t=3,p=2$c2FsdHNhbHQ$aGFzaGhhc2hoYXNoaGFzaA",
|
||||
"$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA",
|
||||
} {
|
||||
if _, err := Verify("password", encoded); err == nil {
|
||||
t.Fatalf("Verify accepted malformed hash %q", encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseBasic(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
username string
|
||||
password string
|
||||
ok bool
|
||||
}{
|
||||
{
|
||||
name: "ordinary",
|
||||
raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:secret")),
|
||||
username: "alice",
|
||||
password: "secret",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "password contains colon and UTF-8",
|
||||
raw: "bAsIc " + base64.StdEncoding.EncodeToString([]byte("alice:pässwörd:with:colons")),
|
||||
username: "alice",
|
||||
password: "pässwörd:with:colons",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "unpadded base64",
|
||||
raw: "Basic " + base64.RawStdEncoding.EncodeToString([]byte("alice:secret")),
|
||||
username: "alice",
|
||||
password: "secret",
|
||||
ok: true,
|
||||
},
|
||||
{name: "no scheme", raw: "alice:secret"},
|
||||
{name: "wrong scheme", raw: "Bearer abc"},
|
||||
{name: "no space", raw: "Basic" + base64.StdEncoding.EncodeToString([]byte("alice:secret"))},
|
||||
{name: "bad base64", raw: "Basic !!!"},
|
||||
{name: "no separator", raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice"))},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
username, password, err := ParseBasic(tc.raw)
|
||||
if !tc.ok {
|
||||
if err == nil {
|
||||
t.Fatalf("ParseBasic accepted %q", tc.raw)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBasic: %v", err)
|
||||
}
|
||||
if username != tc.username || password != tc.password {
|
||||
t.Fatalf("got %q/%q, want %q/%q", username, password, tc.username, tc.password)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenProperties(t *testing.T) {
|
||||
first, err := NewToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := NewToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("tokens are not unique")
|
||||
}
|
||||
if len(first) != 43 {
|
||||
t.Fatalf("token length = %d, want 43 (256 bits)", len(first))
|
||||
}
|
||||
if !ValidTokenShape(first) {
|
||||
t.Fatal("issued token fails its own shape check")
|
||||
}
|
||||
if TokenHash(first) == TokenHash(second) {
|
||||
t.Fatal("token hashes collide")
|
||||
}
|
||||
if len(TokenHash(first)) != 64 {
|
||||
t.Fatalf("token hash length = %d", len(TokenHash(first)))
|
||||
}
|
||||
for _, bad := range []string{"", "short", "has space in it", strings.Repeat("a", 129), "abc+/="} {
|
||||
if ValidTokenShape(bad) {
|
||||
t.Fatalf("ValidTokenShape accepted %q", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Package auth implements the lab2 credential primitives: a library password
|
||||
// KDF (Argon2id), opaque session tokens and RFC 7617 Basic parsing. None of
|
||||
// these helpers log or serialise the secret material they receive.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// Argon2id parameters. 19 MiB / 2 passes / 1 lane is the OWASP password
|
||||
// storage minimum for Argon2id, chosen so eight concurrent registrations fit
|
||||
// inside the 256 MiB API container limit. The parameters are stored in every
|
||||
// PHC string, so a future change remains backward compatible.
|
||||
const (
|
||||
argonMemory uint32 = 19 * 1024 // KiB
|
||||
argonIterations uint32 = 2
|
||||
argonParallelism uint8 = 1
|
||||
argonSaltLength = 16
|
||||
argonKeyLength uint32 = 32
|
||||
)
|
||||
|
||||
// ErrInvalidHash means a stored PHC string is malformed or uses unsupported
|
||||
// parameters. It is an internal error, never shown to a client.
|
||||
var ErrInvalidHash = errors.New("invalid password hash")
|
||||
|
||||
// Hash derives an Argon2id PHC string for password. Callers must validate the
|
||||
// password policy before calling; the KDF itself accepts arbitrary UTF-8.
|
||||
func Hash(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonIterations, argonParallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(key),
|
||||
), nil
|
||||
}
|
||||
|
||||
// Verify checks password against a PHC string in constant time and reports
|
||||
// whether the encoded hash was structurally valid. A malformed hash is not a
|
||||
// password mismatch and should be treated as an internal error by the caller.
|
||||
func Verify(password, encoded string) (match bool, err error) {
|
||||
params, salt, key, err := parse(encoded)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
candidate := argon2.IDKey([]byte(password), salt, params.iterations, params.memory, params.parallelism, uint32(len(key)))
|
||||
return subtle.ConstantTimeCompare(candidate, key) == 1, nil
|
||||
}
|
||||
|
||||
type params struct {
|
||||
memory uint32
|
||||
iterations uint32
|
||||
parallelism uint8
|
||||
}
|
||||
|
||||
func parse(encoded string) (params, []byte, []byte, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
var p params
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism); err != nil {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
if p.memory < 8*1024 || p.memory > 256*1024 || p.iterations < 1 || p.iterations > 10 || p.parallelism < 1 || p.parallelism > 16 {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) < 8 || len(salt) > 64 {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
key, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(key) < 16 || len(key) > 64 {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
return p, salt, key, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// tokenBytes gives 256 bits of entropy, the contract minimum. The token is an
|
||||
// opaque value: it is not a username, a UUID or a JWT.
|
||||
const tokenBytes = 32
|
||||
|
||||
// NewToken returns a URL-safe opaque session token.
|
||||
func NewToken() (string, error) {
|
||||
raw := make([]byte, tokenBytes)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
// TokenHash is the only representation of a token that is persisted. A cache
|
||||
// dump therefore does not contain bearer credentials usable against the API.
|
||||
func TokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// ValidTokenShape rejects absurd header values before hashing. The check is a
|
||||
// superset of the 43-character tokens this server issues, so token rotation
|
||||
// remains possible without rejecting old values early.
|
||||
func ValidTokenShape(token string) bool {
|
||||
if len(token) < 16 || len(token) > 128 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(token); i++ {
|
||||
c := token[i]
|
||||
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ErrMalformedBasic is returned for anything that is not a well-formed
|
||||
// RFC 7617 Basic credential. Callers must answer with the same 401 as a
|
||||
// wrong password.
|
||||
var ErrMalformedBasic = errors.New("malformed basic credentials")
|
||||
|
||||
// ParseBasic decodes an Authorization header of the form "Basic base64(user:pass)".
|
||||
// The password may contain colons and arbitrary UTF-8; only the first colon
|
||||
// separates the username.
|
||||
func ParseBasic(header string) (username, password string, err error) {
|
||||
const scheme = "basic"
|
||||
trimmed := header
|
||||
if len(trimmed) < len(scheme)+1 || !equalFoldASCII(trimmed[:len(scheme)], scheme) || trimmed[len(scheme)] != ' ' {
|
||||
return "", "", ErrMalformedBasic
|
||||
}
|
||||
encoded := trimmed[len(scheme)+1:]
|
||||
if encoded == "" || len(encoded) > 1024 {
|
||||
return "", "", ErrMalformedBasic
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
// Some clients omit the RFC 4648 padding. Accept the unpadded form as
|
||||
// well, but never fall back to a different alphabet.
|
||||
decoded, err = base64.RawStdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return "", "", ErrMalformedBasic
|
||||
}
|
||||
}
|
||||
separator := -1
|
||||
for i := 0; i < len(decoded); i++ {
|
||||
if decoded[i] == ':' {
|
||||
separator = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if separator < 0 {
|
||||
return "", "", ErrMalformedBasic
|
||||
}
|
||||
return string(decoded[:separator]), string(decoded[separator+1:]), nil
|
||||
}
|
||||
|
||||
func equalFoldASCII(value, lower string) bool {
|
||||
if len(value) != len(lower) {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
if c != lower[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// Package config loads the explicit runtime configuration of the lab2
|
||||
// messenger. The container image stays immutable: the same image is configured
|
||||
// through environment variables (or files referenced by *_FILE variables for
|
||||
// operators that do not want secrets in the environment).
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultSessionTTL is the contract default of contracts/README.md.
|
||||
DefaultSessionTTL = time.Hour
|
||||
// MaxShutdownTimeout leaves headroom below the 10 second termination
|
||||
// window promised by the previous lab and expected by the container
|
||||
// checks, even if an operator overrides the environment variable.
|
||||
MaxShutdownTimeout = 9 * time.Second
|
||||
// MaxStartupTimeout bounds the initial PostgreSQL connectivity wait.
|
||||
MaxStartupTimeout = 120 * time.Second
|
||||
)
|
||||
|
||||
// Config is validated at startup. The process refuses to start with an
|
||||
// invalid value instead of silently falling back to a different security or
|
||||
// durability posture.
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
LogLevel slog.Level
|
||||
ShutdownTimeout time.Duration
|
||||
StartupTimeout time.Duration
|
||||
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
|
||||
SessionTTL time.Duration
|
||||
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBConnectTimeout time.Duration
|
||||
DBStatementTimeout time.Duration
|
||||
QueryTimeout time.Duration
|
||||
|
||||
CachePoolSize int
|
||||
CacheTimeout time.Duration
|
||||
}
|
||||
|
||||
// Load reads and validates the runtime configuration.
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
Host: envString("APP_HOST", "0.0.0.0"),
|
||||
Env: envString("APP_ENV", "lab"),
|
||||
ShutdownTimeout: 8 * time.Second,
|
||||
StartupTimeout: 30 * time.Second,
|
||||
QueryTimeout: 3 * time.Second,
|
||||
}
|
||||
|
||||
port, err := envInt("APP_PORT", 8080)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("APP_PORT: %w", err)
|
||||
}
|
||||
if port < 1 || port > 65535 {
|
||||
return Config{}, fmt.Errorf("APP_PORT: must be between 1 and 65535")
|
||||
}
|
||||
cfg.Port = port
|
||||
|
||||
level, err := parseLogLevel(envString("LOG_LEVEL", "info"))
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("LOG_LEVEL: %w", err)
|
||||
}
|
||||
cfg.LogLevel = level
|
||||
|
||||
if strings.TrimSpace(cfg.Host) == "" {
|
||||
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
|
||||
}
|
||||
|
||||
databaseURL, err := secret("DATABASE_URL")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cfg.DatabaseURL = databaseURL
|
||||
|
||||
cacheURL, err := secret("CACHE_URL")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cfg.CacheURL = cacheURL
|
||||
|
||||
seconds, err := envInt("SESSION_TTL_SECONDS", int(DefaultSessionTTL/time.Second))
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
|
||||
}
|
||||
if seconds < 1 || seconds > 30*24*60*60 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: must be between 1 and 2592000")
|
||||
}
|
||||
cfg.SessionTTL = time.Duration(seconds) * time.Second
|
||||
|
||||
maxConns, err := envInt("DB_MAX_CONNS", 8)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("DB_MAX_CONNS: %w", err)
|
||||
}
|
||||
if maxConns < 1 || maxConns > 100 {
|
||||
return Config{}, fmt.Errorf("DB_MAX_CONNS: must be between 1 and 100")
|
||||
}
|
||||
cfg.DBMaxConns = int32(maxConns)
|
||||
|
||||
minConns, err := envInt("DB_MIN_CONNS", 1)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("DB_MIN_CONNS: %w", err)
|
||||
}
|
||||
if minConns < 0 || minConns > maxConns {
|
||||
return Config{}, fmt.Errorf("DB_MIN_CONNS: must be between 0 and DB_MAX_CONNS")
|
||||
}
|
||||
cfg.DBMinConns = int32(minConns)
|
||||
|
||||
if cfg.DBConnectTimeout, err = envDurationSeconds("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 30); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if cfg.DBStatementTimeout, err = envDurationSeconds("DB_STATEMENT_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if cfg.QueryTimeout, err = envDurationSeconds("DB_QUERY_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
cachePool, err := envInt("CACHE_POOL_SIZE", 8)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: %w", err)
|
||||
}
|
||||
if cachePool < 1 || cachePool > 100 {
|
||||
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: must be between 1 and 100")
|
||||
}
|
||||
cfg.CachePoolSize = cachePool
|
||||
|
||||
if cfg.CacheTimeout, err = envDurationSeconds("CACHE_TIMEOUT_SECONDS", 2, 1, 30); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
shutdown, err := envDurationSeconds("SHUTDOWN_TIMEOUT_SECONDS", 8, 1, 60)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if shutdown > MaxShutdownTimeout {
|
||||
shutdown = MaxShutdownTimeout
|
||||
}
|
||||
cfg.ShutdownTimeout = shutdown
|
||||
|
||||
startup, err := envDurationSeconds("STARTUP_TIMEOUT_SECONDS", 30, 1, 120)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cfg.StartupTimeout = startup
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// secret resolves NAME or NAME_FILE. A file is preferred when both are set so
|
||||
// compose-style file secrets win over inherited environment values. Values are
|
||||
// never echoed in error messages.
|
||||
func secret(name string) (string, error) {
|
||||
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s_FILE: cannot read referenced file", name)
|
||||
}
|
||||
value := strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s_FILE: referenced file is empty", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||
return value, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
|
||||
}
|
||||
|
||||
func envString(key, fallback string) string {
|
||||
// An environment variable set to an empty string is treated as unset; this
|
||||
// keeps container defaults working when compose passes "" for an optional
|
||||
// setting.
|
||||
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt(key string, fallback int) (int, error) {
|
||||
raw, ok := os.LookupEnv(key)
|
||||
if !ok || strings.TrimSpace(raw) == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
value, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("expected an integer, got %q", raw)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func envDurationSeconds(key string, fallback, minimum, maximum int) (time.Duration, error) {
|
||||
value, err := envInt(key, fallback)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s: %w", key, err)
|
||||
}
|
||||
if value < minimum || value > maximum {
|
||||
return 0, fmt.Errorf("%s: must be between %d and %d", key, minimum, maximum)
|
||||
}
|
||||
return time.Duration(value) * time.Second, nil
|
||||
}
|
||||
|
||||
func parseLogLevel(raw string) (slog.Level, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "debug":
|
||||
return slog.LevelDebug, nil
|
||||
case "info":
|
||||
return slog.LevelInfo, nil
|
||||
case "warn", "warning":
|
||||
return slog.LevelWarn, nil
|
||||
case "error":
|
||||
return slog.LevelError, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("expected debug, info, warn or error, got %q", raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var allKeys = []string{
|
||||
"APP_HOST", "APP_PORT", "APP_ENV", "LOG_LEVEL", "SESSION_TTL_SECONDS",
|
||||
"DB_MAX_CONNS", "DB_MIN_CONNS", "DB_CONNECT_TIMEOUT_SECONDS",
|
||||
"DB_STATEMENT_TIMEOUT_SECONDS", "DB_QUERY_TIMEOUT_SECONDS",
|
||||
"CACHE_POOL_SIZE", "CACHE_TIMEOUT_SECONDS", "SHUTDOWN_TIMEOUT_SECONDS",
|
||||
"STARTUP_TIMEOUT_SECONDS", "DATABASE_URL", "DATABASE_URL_FILE",
|
||||
"CACHE_URL", "CACHE_URL_FILE",
|
||||
}
|
||||
|
||||
func clearEnvironment(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, key := range allKeys {
|
||||
t.Setenv(key, "")
|
||||
}
|
||||
}
|
||||
|
||||
func baseEnvironment(t *testing.T) {
|
||||
t.Helper()
|
||||
clearEnvironment(t)
|
||||
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
|
||||
t.Setenv("CACHE_URL", "redis://:pass@valkey:6379/0")
|
||||
}
|
||||
|
||||
func TestLoadDefaults(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.Port != 8080 || cfg.SessionTTL != time.Hour {
|
||||
t.Fatalf("unexpected defaults: %+v", cfg)
|
||||
}
|
||||
if cfg.DBMaxConns != 8 || cfg.DBMinConns != 1 || cfg.QueryTimeout != 3*time.Second {
|
||||
t.Fatalf("unexpected pool defaults: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadReadsSecretsFromFiles(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
directory := t.TempDir()
|
||||
databaseFile := filepath.Join(directory, "database_url")
|
||||
cacheFile := filepath.Join(directory, "cache_url")
|
||||
if err := os.WriteFile(databaseFile, []byte("postgres://file:secret@postgres/db\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(cacheFile, []byte("redis://:file-secret@valkey:6379/0\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", databaseFile)
|
||||
t.Setenv("CACHE_URL_FILE", cacheFile)
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.DatabaseURL != "postgres://file:secret@postgres/db" {
|
||||
t.Fatalf("database URL was not read from file: %q", cfg.DatabaseURL)
|
||||
}
|
||||
if cfg.CacheURL != "redis://:file-secret@valkey:6379/0" {
|
||||
t.Fatalf("cache URL was not read from file: %q", cfg.CacheURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidValues(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
key string
|
||||
value string
|
||||
}{
|
||||
{"zero ttl", "SESSION_TTL_SECONDS", "0"},
|
||||
{"huge ttl", "SESSION_TTL_SECONDS", "99999999"},
|
||||
{"zero port", "APP_PORT", "0"},
|
||||
{"bad log level", "LOG_LEVEL", "verbose"},
|
||||
{"zero max conns", "DB_MAX_CONNS", "0"},
|
||||
{"min above max", "DB_MIN_CONNS", "9"},
|
||||
{"bad timeout", "DB_QUERY_TIMEOUT_SECONDS", "0"},
|
||||
{"bad int", "APP_PORT", "eighty"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
t.Setenv(tc.key, tc.value)
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatalf("Load accepted %s=%q", tc.key, tc.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRequiresDatabaseAndCacheURLs(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load accepted missing DATABASE_URL/CACHE_URL")
|
||||
}
|
||||
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres/db")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load accepted missing CACHE_URL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShutdownTimeoutIsClamped(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
t.Setenv("SHUTDOWN_TIMEOUT_SECONDS", "60")
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.ShutdownTimeout != MaxShutdownTimeout {
|
||||
t.Fatalf("shutdown timeout = %v, want clamp to %v", cfg.ShutdownTimeout, MaxShutdownTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretFileErrorsDoNotLeakThePath(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
t.Setenv("DATABASE_URL_FILE", "/nonexistent/path/database_url")
|
||||
_, err := Load()
|
||||
if err == nil {
|
||||
t.Fatal("Load accepted a missing secret file")
|
||||
}
|
||||
if got := err.Error(); got != "DATABASE_URL_FILE: cannot read referenced file" {
|
||||
t.Fatalf("error leaks path: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Package cursor implements the opaque keyset cursor of the contract. A cursor
|
||||
// carries the last item already returned; the next page asks PostgreSQL for
|
||||
// rows strictly after (created_at, id). Cursors are bound to the endpoint and,
|
||||
// for message history, to the chat that issued them.
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/model"
|
||||
"mtusi.ru/messenger-lab2/internal/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
ScopeChats = "chats"
|
||||
ScopeMessages = "messages"
|
||||
|
||||
version = 1
|
||||
maxCursorSize = 512
|
||||
)
|
||||
|
||||
// ErrInvalid is returned for malformed, tampered or out-of-scope cursors. The
|
||||
// HTTP layer maps it to 400 invalid_request.
|
||||
var ErrInvalid = errors.New("invalid cursor")
|
||||
|
||||
// Cursor is the decoded keyset position.
|
||||
type Cursor struct {
|
||||
At time.Time
|
||||
ID string
|
||||
ChatID string
|
||||
}
|
||||
|
||||
// Encoding of the wire form. Time is an RFC 3339 timestamp with UTC Z and
|
||||
// microsecond precision, matching PostgreSQL timestamptz. It is never used as
|
||||
// an identifier on its own.
|
||||
type wire struct {
|
||||
Version int `json:"v"`
|
||||
Scope string `json:"s"`
|
||||
ChatID string `json:"c,omitempty"`
|
||||
Time string `json:"t"`
|
||||
ID string `json:"i"`
|
||||
}
|
||||
|
||||
// ForChat encodes the position of the last returned chat.
|
||||
func ForChat(chat model.Chat) string {
|
||||
return encode(wire{Scope: ScopeChats, Time: chat.CreatedAt.UTC().Format(time.RFC3339Nano), ID: chat.ID})
|
||||
}
|
||||
|
||||
// ForMessage encodes the position of the last returned message.
|
||||
func ForMessage(message model.Message) string {
|
||||
return encode(wire{
|
||||
Scope: ScopeMessages,
|
||||
ChatID: message.ChatID,
|
||||
Time: message.CreatedAt.UTC().Format(time.RFC3339Nano),
|
||||
ID: message.ID,
|
||||
})
|
||||
}
|
||||
|
||||
// Decode validates a cursor for the expected scope. chatID is required for the
|
||||
// messages scope and must be empty for the chats scope.
|
||||
func Decode(raw, scope, chatID string) (Cursor, error) {
|
||||
if raw == "" || len(raw) > maxCursorSize {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
data, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
var value wire
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
if value.Version != version || value.Scope != scope {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
at, err := time.Parse(time.RFC3339Nano, value.Time)
|
||||
if err != nil || at.IsZero() || at.Location() != time.UTC {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
normalizedID, ok := uuid.Normalize(value.ID)
|
||||
if !ok || normalizedID != value.ID {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
switch scope {
|
||||
case ScopeChats:
|
||||
if value.ChatID != "" {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
return Cursor{At: at, ID: normalizedID}, nil
|
||||
case ScopeMessages:
|
||||
normalizedChat, ok := uuid.Normalize(value.ChatID)
|
||||
if !ok || normalizedChat != value.ChatID || normalizedChat != chatID {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
return Cursor{At: at, ID: normalizedID, ChatID: normalizedChat}, nil
|
||||
default:
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func encode(value wire) string {
|
||||
value.Version = version
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
panic("encode cursor: " + err.Error())
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(data)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/model"
|
||||
)
|
||||
|
||||
func TestChatCursorRoundTrip(t *testing.T) {
|
||||
at := time.Date(2026, 11, 30, 12, 34, 56, 123456000, time.UTC)
|
||||
chat := model.Chat{
|
||||
ID: "11111111-2222-4333-8444-555555555555",
|
||||
Title: "chat",
|
||||
MemberIDs: []string{"11111111-2222-4333-8444-555555555555"},
|
||||
CreatedAt: model.Time{Time: at},
|
||||
}
|
||||
raw := ForChat(chat)
|
||||
decoded, err := Decode(raw, ScopeChats, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Decode: %v", err)
|
||||
}
|
||||
if !decoded.At.Equal(at) || decoded.ID != chat.ID || decoded.ChatID != "" {
|
||||
t.Fatalf("decoded = %+v", decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageCursorIsBoundToChat(t *testing.T) {
|
||||
at := time.Now().UTC().Truncate(time.Microsecond)
|
||||
chatID := "11111111-2222-4333-8444-555555555555"
|
||||
message := model.Message{
|
||||
ID: "99999999-2222-4333-8444-555555555555",
|
||||
ChatID: chatID,
|
||||
SenderID: "11111111-2222-4333-8444-555555555555",
|
||||
Text: "hello",
|
||||
CreatedAt: model.Time{Time: at},
|
||||
}
|
||||
raw := ForMessage(message)
|
||||
if _, err := Decode(raw, ScopeMessages, chatID); err != nil {
|
||||
t.Fatalf("Decode(same chat): %v", err)
|
||||
}
|
||||
if _, err := Decode(raw, ScopeMessages, "22222222-2222-4333-8444-555555555555"); err == nil {
|
||||
t.Fatal("cursor was accepted for another chat")
|
||||
}
|
||||
if _, err := Decode(raw, ScopeChats, ""); err == nil {
|
||||
t.Fatal("message cursor was accepted by the chats scope")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRejectsTamperedCursors(t *testing.T) {
|
||||
at := time.Now().UTC().Truncate(time.Microsecond)
|
||||
valid := wire{
|
||||
Version: version,
|
||||
Scope: ScopeMessages,
|
||||
ChatID: "11111111-2222-4333-8444-555555555555",
|
||||
Time: at.Format(time.RFC3339Nano),
|
||||
ID: "99999999-2222-4333-8444-555555555555",
|
||||
}
|
||||
tampered := []wire{
|
||||
{Version: 2, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
|
||||
{Version: version, Scope: ScopeChats, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: "", Time: valid.Time, ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: "not-a-uuid", Time: valid.Time, ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "2026-11-30T12:00:00+03:00", ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "yesterday", ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: "not-a-uuid"},
|
||||
}
|
||||
for i, value := range tampered {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := base64.RawURLEncoding.EncodeToString(data)
|
||||
if _, err := Decode(raw, ScopeMessages, valid.ChatID); err == nil {
|
||||
t.Fatalf("tampered cursor %d was accepted", i)
|
||||
}
|
||||
}
|
||||
|
||||
withExtra, _ := json.Marshal(map[string]any{
|
||||
"v": version, "s": ScopeMessages, "c": valid.ChatID,
|
||||
"t": valid.Time, "i": valid.ID, "x": 1,
|
||||
})
|
||||
if _, err := Decode(base64.RawURLEncoding.EncodeToString(withExtra), ScopeMessages, valid.ChatID); err == nil {
|
||||
t.Fatal("cursor with an unknown field was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRejectsGarbage(t *testing.T) {
|
||||
for _, raw := range []string{"", "!!!", base64.RawURLEncoding.EncodeToString([]byte("not json")), strings.Repeat("a", 600)} {
|
||||
if _, err := Decode(raw, ScopeChats, ""); err == nil {
|
||||
t.Fatalf("Decode accepted %q", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Package model holds the public JSON shapes of the lab2 contract. They are
|
||||
// deliberately separate from the database scan helpers so an accidental new
|
||||
// column cannot silently become an API field.
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// Time marshals an RFC 3339 UTC timestamp with exactly six fractional digits.
|
||||
// Go's default time.Time JSON encoder trims trailing zeros, which produces
|
||||
// 3-5 digit fractions that some Python 3.9 datetime parsers (used by the
|
||||
// public test client) reject. A fixed microsecond precision matches
|
||||
// PostgreSQL timestamptz and stays valid RFC 3339.
|
||||
type Time struct{ time.Time }
|
||||
|
||||
const timestampLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
// MarshalJSON implements json.Marshaler.
|
||||
func (t Time) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
|
||||
}
|
||||
|
||||
// User is the public user shape. It never contains a password hash or session
|
||||
// data.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Chat is the public chat shape. MemberIDs preserves the order supplied at
|
||||
// creation; membership is immutable in the mandatory lab2 API.
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Message is the public message shape. SenderID always comes from the server
|
||||
// session, never from the request body.
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ChatPage is one keyset page of accessible chats.
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// MessagePage is one keyset page of a chat history.
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// Session is the login response. Token is only ever written to the response
|
||||
// body, never to logs or PostgreSQL.
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt Time `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTimeMarshalUsesFixedMicroseconds(t *testing.T) {
|
||||
value := Time{Time: time.Date(2026, 11, 30, 12, 0, 0, 120000000, time.UTC)}
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(data)
|
||||
// .120000 would be trimmed to .12 by the default encoder; the public
|
||||
// Python 3.9 client requires 3 or 6 fractional digits.
|
||||
if got != `"2026-11-30T12:00:00.120000Z"` {
|
||||
t.Fatalf("marshal = %s", got)
|
||||
}
|
||||
if !strings.HasSuffix(got, "Z\"") {
|
||||
t.Fatal("timestamp does not end in Z")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserJSONHasOnlyPublicFields(t *testing.T) {
|
||||
user := User{
|
||||
ID: "11111111-2222-4333-8444-555555555555",
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
CreatedAt: Time{Time: time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)},
|
||||
}
|
||||
data, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]any
|
||||
if err := json.Unmarshal(data, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fields) != 4 {
|
||||
t.Fatalf("user JSON has unexpected fields: %v", fields)
|
||||
}
|
||||
for _, forbidden := range []string{"password", "password_hash", "token", "token_hash"} {
|
||||
if _, present := fields[forbidden]; present {
|
||||
t.Fatalf("user JSON leaks %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// Package session stores opaque server-side sessions in Valkey. The token is
|
||||
// never persisted: only its SHA-256 hash is used as the cache key, so a cache
|
||||
// dump does not contain credentials that can be replayed against the API.
|
||||
//
|
||||
// Valkey is the source of truth for sessions. It is configured with AOF
|
||||
// persistence and a named volume, so valid sessions survive both the API
|
||||
// process and the Valkey process restarting with volumes kept.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/auth"
|
||||
)
|
||||
|
||||
const keyPrefix = "mtusi:lab2:session:"
|
||||
|
||||
var (
|
||||
// ErrInvalid means the token is unknown, expired or malformed.
|
||||
ErrInvalid = errors.New("invalid session")
|
||||
// ErrUnavailable means Valkey is not answering; the API must return a
|
||||
// bounded 503 instead of trusting the bearer token.
|
||||
ErrUnavailable = errors.New("session store unavailable")
|
||||
)
|
||||
|
||||
type record struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// Options bound every network operation and the connection pool.
|
||||
type Options struct {
|
||||
PoolSize int
|
||||
DialTimeout time.Duration
|
||||
IOTimeout time.Duration
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
// Store is a thin, timeout-aware wrapper around go-redis.
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// Open parses CACHE_URL (redis:// or rediss://) without echoing it in errors.
|
||||
// It does not require Valkey to be reachable at startup: /health/ready and
|
||||
// login report the outage as 503.
|
||||
func Open(rawURL string, options Options) (*Store, error) {
|
||||
parsed, err := redis.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, errors.New("CACHE_URL is not a valid Redis/Valkey URL")
|
||||
}
|
||||
if options.PoolSize <= 0 {
|
||||
options.PoolSize = 8
|
||||
}
|
||||
if options.DialTimeout <= 0 {
|
||||
options.DialTimeout = 2 * time.Second
|
||||
}
|
||||
if options.IOTimeout <= 0 {
|
||||
options.IOTimeout = 2 * time.Second
|
||||
}
|
||||
if options.TTL <= 0 {
|
||||
options.TTL = time.Hour
|
||||
}
|
||||
parsed.PoolSize = options.PoolSize
|
||||
parsed.DialTimeout = options.DialTimeout
|
||||
parsed.ReadTimeout = options.IOTimeout
|
||||
parsed.WriteTimeout = options.IOTimeout
|
||||
// One retry keeps a transient blip invisible while bounding the worst-case
|
||||
// time a handler spends waiting for the cache.
|
||||
parsed.MaxRetries = 1
|
||||
parsed.MinRetryBackoff = 20 * time.Millisecond
|
||||
parsed.MaxRetryBackoff = 100 * time.Millisecond
|
||||
return &Store{client: redis.NewClient(parsed), ttl: options.TTL}, nil
|
||||
}
|
||||
|
||||
// TTL exposes the configured session lifetime (used by tests and startup logs).
|
||||
func (s *Store) TTL() time.Duration { return s.ttl }
|
||||
|
||||
// Create issues a new opaque token and stores the session with a TTL. The
|
||||
// returned expiry is the absolute instant the client must treat as the end of
|
||||
// the session; restarting a process does not extend it.
|
||||
func (s *Store) Create(ctx context.Context, userID string) (token string, expiresAt time.Time, err error) {
|
||||
token, err = auth.NewToken()
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
// A whole number of microseconds keeps the value parseable by the
|
||||
// Python 3.9 public client (its fromisoformat accepts 3 or 6 fractional
|
||||
// digits, not Go's trimmed nanosecond form) while staying RFC 3339.
|
||||
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
||||
payload, err := json.Marshal(record{UserID: userID, ExpiresAt: expiresAt})
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("encode session: %w", err)
|
||||
}
|
||||
if err := s.client.Set(ctx, key(auth.TokenHash(token)), payload, s.ttl).Err(); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
// Get resolves a token to a user id. Unknown, expired and corrupt records are
|
||||
// all ErrInvalid; a transport failure is ErrUnavailable.
|
||||
func (s *Store) Get(ctx context.Context, token string) (string, error) {
|
||||
raw, err := s.client.Get(ctx, key(auth.TokenHash(token))).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var value record
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value.UserID == "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if !value.ExpiresAt.After(time.Now()) {
|
||||
// TTL should already have removed the key; this also covers a clock
|
||||
// adjustment or an externally imported record.
|
||||
_ = s.client.Del(ctx, key(auth.TokenHash(token))).Err()
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return value.UserID, nil
|
||||
}
|
||||
|
||||
// Delete revokes the session. Missing keys are not an error here: the caller
|
||||
// has already authenticated the token, and a concurrent logout is harmless.
|
||||
func (s *Store) Delete(ctx context.Context, token string) error {
|
||||
if err := s.client.Del(ctx, key(auth.TokenHash(token))).Err(); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ping is used by /health/ready and the startup log.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close releases the connection pool.
|
||||
func (s *Store) Close() error { return s.client.Close() }
|
||||
|
||||
func key(tokenHash string) string { return keyPrefix + tokenHash }
|
||||
@@ -0,0 +1,139 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
// advisoryLockKey is a fixed application-wide key. pg_advisory_lock serialises
|
||||
// concurrent API replicas that start at the same time; it is released when the
|
||||
// dedicated connection is returned or the session ends.
|
||||
const advisoryLockKey int64 = 0x6d74756c616232 // "mtulab2"
|
||||
|
||||
type migration struct {
|
||||
version int
|
||||
name string
|
||||
checksum string
|
||||
sql string
|
||||
}
|
||||
|
||||
// Migrate applies every embedded migration exactly once and records its
|
||||
// checksum. Re-running it is a no-op, which is what the restart hook relies on.
|
||||
// A changed migration file is a startup error rather than a silent divergence.
|
||||
func (s *Store) Migrate(ctx context.Context) error {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
defer conn.Release()
|
||||
|
||||
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLockKey); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
defer func() {
|
||||
// Use a background context: the request context may already be
|
||||
// cancelled when a startup timeout fires, but the lock still has to be
|
||||
// released explicitly before the connection is returned to the pool.
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLockKey)
|
||||
}()
|
||||
|
||||
if _, err := conn.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version integer PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
checksum text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range migrations {
|
||||
var existing string
|
||||
err := conn.QueryRow(ctx, `SELECT checksum FROM schema_migrations WHERE version = $1`, item.version).Scan(&existing)
|
||||
switch {
|
||||
case err == nil:
|
||||
if existing != item.checksum {
|
||||
return fmt.Errorf("migration %04d_%s was modified after it was applied", item.version, item.name)
|
||||
}
|
||||
continue
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
tx, err := conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, item.sql); err != nil {
|
||||
_ = tx.Rollback(context.Background())
|
||||
return fmt.Errorf("apply migration %04d_%s: %w", item.version, item.name, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`,
|
||||
item.version, item.name, item.checksum,
|
||||
); err != nil {
|
||||
_ = tx.Rollback(context.Background())
|
||||
return s.classify(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadMigrations() ([]migration, error) {
|
||||
entries, err := fs.ReadDir(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]migration, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
name := entry.Name()
|
||||
if len(name) < 9 {
|
||||
return nil, fmt.Errorf("migration %q has no NNNN_ prefix", name)
|
||||
}
|
||||
version, err := strconv.Atoi(name[:4])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migration %q has no numeric prefix", name)
|
||||
}
|
||||
data, err := migrationFiles.ReadFile("migrations/" + name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
items = append(items, migration{
|
||||
version: version,
|
||||
name: strings.TrimSuffix(name[5:], ".sql"),
|
||||
checksum: hex.EncodeToString(sum[:]),
|
||||
sql: string(data),
|
||||
})
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].version < items[j].version })
|
||||
for i := 1; i < len(items); i++ {
|
||||
if items[i].version == items[i-1].version {
|
||||
return nil, fmt.Errorf("duplicate migration version %d", items[i].version)
|
||||
}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadMigrations(t *testing.T) {
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations: %v", err)
|
||||
}
|
||||
if len(migrations) != 2 {
|
||||
t.Fatalf("loaded %d migrations, want 2", len(migrations))
|
||||
}
|
||||
if migrations[0].version != 1 || migrations[1].version != 2 {
|
||||
t.Fatalf("migration order = %d,%d", migrations[0].version, migrations[1].version)
|
||||
}
|
||||
for _, item := range migrations {
|
||||
if len(item.checksum) != 64 {
|
||||
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(item.sql), "create ") {
|
||||
t.Fatalf("migration %d has no schema statements", item.version)
|
||||
}
|
||||
}
|
||||
// The checksum must be stable across process runs: it is what detects an
|
||||
// edited migration after it has been applied.
|
||||
again, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if migrations[0].checksum != again[0].checksum || migrations[1].checksum != again[1].checksum {
|
||||
t.Fatal("migration checksums are not deterministic")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationsContainRequiredDomainObjects(t *testing.T) {
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all := migrations[0].sql + migrations[1].sql
|
||||
for _, required := range []string{
|
||||
"CREATE TABLE users",
|
||||
"CREATE TABLE chats",
|
||||
"CREATE TABLE chat_members",
|
||||
"CREATE TABLE messages",
|
||||
"CREATE UNIQUE INDEX users_username_key",
|
||||
"messages_sender_membership_fk",
|
||||
"messages_chat_created_id_idx",
|
||||
} {
|
||||
if !strings.Contains(all, required) {
|
||||
t.Fatalf("migrations do not contain %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat
|
||||
-- membership and messages. Sessions intentionally live in Valkey with a TTL.
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
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_password_hash_present
|
||||
CHECK (length(password_hash) > 0)
|
||||
);
|
||||
|
||||
-- Uniqueness is enforced by the database, not by a read-then-insert check, so
|
||||
-- two concurrent registrations of the same username cannot both succeed.
|
||||
CREATE UNIQUE INDEX users_username_key ON users (username);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT chats_title_length
|
||||
CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
|
||||
);
|
||||
|
||||
-- "Chats of the current user" walks chat_members by user_id.
|
||||
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,
|
||||
CONSTRAINT messages_text_length
|
||||
CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
CONSTRAINT messages_chat_fk
|
||||
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
|
||||
-- The sender must be a member of the chat at the database level too, not
|
||||
-- only in the HTTP handler.
|
||||
CONSTRAINT messages_sender_membership_fk
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Indexes justified by the two keyset queries of the contract.
|
||||
--
|
||||
-- Message history:
|
||||
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
-- ORDER BY created_at, id LIMIT $4
|
||||
-- The three-column index lets PostgreSQL start at the cursor position inside
|
||||
-- one chat instead of scanning the whole history for every page.
|
||||
CREATE INDEX messages_chat_created_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
-- Chat list:
|
||||
-- ORDER BY created_at, id LIMIT $1
|
||||
-- after joining chat_members for the current user.
|
||||
CREATE INDEX chats_created_id_idx
|
||||
ON chats (created_at, id);
|
||||
@@ -0,0 +1,472 @@
|
||||
// Package store is the PostgreSQL repository. Every statement uses positional
|
||||
// parameters; identifiers are never interpolated into SQL. The pool is
|
||||
// bounded and every operation carries a context timeout.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/puddle/v2"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/cursor"
|
||||
"mtusi.ru/messenger-lab2/internal/model"
|
||||
"mtusi.ru/messenger-lab2/internal/uuid"
|
||||
)
|
||||
|
||||
// Domain errors. The HTTP layer maps them to the contract's status codes.
|
||||
var (
|
||||
ErrNotFound = errors.New("object not found")
|
||||
ErrUsernameTaken = errors.New("username already taken")
|
||||
ErrUnknownMember = errors.New("unknown chat member")
|
||||
ErrUnavailable = errors.New("database unavailable")
|
||||
)
|
||||
|
||||
// Options bounds the pool and every query. Zero values fall back to safe
|
||||
// defaults so the store is still testable from small programs.
|
||||
type Options struct {
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
ConnectTimeout time.Duration
|
||||
StatementTimeout time.Duration
|
||||
QueryTimeout time.Duration
|
||||
}
|
||||
|
||||
// Store owns a bounded pgx pool.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
queryTimeout time.Duration
|
||||
}
|
||||
|
||||
// Open parses the DSN and creates the pool. Parse errors deliberately do not
|
||||
// echo the DSN: it contains the database password.
|
||||
func Open(ctx context.Context, dsn string, options Options) (*Store, error) {
|
||||
config, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.New("DATABASE_URL is not a valid PostgreSQL URL")
|
||||
}
|
||||
applyDefaults(&options)
|
||||
config.MaxConns = options.MaxConns
|
||||
config.MinConns = options.MinConns
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = 30 * time.Second
|
||||
config.ConnConfig.ConnectTimeout = options.ConnectTimeout
|
||||
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab2"
|
||||
// A statement timeout in the server session is the last line of defence
|
||||
// against a runaway query; the caller's context is the first.
|
||||
config.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(options.StatementTimeout.Milliseconds(), 10)
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
}
|
||||
return &Store{pool: pool, queryTimeout: options.QueryTimeout}, nil
|
||||
}
|
||||
|
||||
func applyDefaults(options *Options) {
|
||||
if options.MaxConns <= 0 {
|
||||
options.MaxConns = 8
|
||||
}
|
||||
if options.MinConns < 0 {
|
||||
options.MinConns = 0
|
||||
}
|
||||
if options.MinConns > options.MaxConns {
|
||||
options.MinConns = options.MaxConns
|
||||
}
|
||||
if options.ConnectTimeout <= 0 {
|
||||
options.ConnectTimeout = 3 * time.Second
|
||||
}
|
||||
if options.StatementTimeout <= 0 {
|
||||
options.StatementTimeout = 3 * time.Second
|
||||
}
|
||||
if options.QueryTimeout <= 0 {
|
||||
options.QueryTimeout = 3 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
// Ping is used by /health/ready and by the startup readiness loop.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
return s.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
// Close waits for in-flight queries and closes the pool.
|
||||
func (s *Store) Close() { s.pool.Close() }
|
||||
|
||||
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if s.queryTimeout <= 0 {
|
||||
return ctx, func() {}
|
||||
}
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
|
||||
// classify separates a dependency outage (contract 503 unavailable) from a
|
||||
// genuine application bug (500 internal_error). Only the error class is mapped;
|
||||
// the original error is logged server-side and never sent to a client.
|
||||
func (s *Store) classify(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch {
|
||||
case strings.HasPrefix(pgErr.Code, "08"), // connection exception
|
||||
pgErr.Code == "57P01", // admin shutdown
|
||||
pgErr.Code == "57P02", // crash shutdown
|
||||
pgErr.Code == "57P03", // cannot connect now
|
||||
pgErr.Code == "57014", // query cancelled (statement_timeout)
|
||||
strings.HasPrefix(pgErr.Code, "53"): // insufficient resources
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, puddle.ErrClosedPool) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key"
|
||||
}
|
||||
|
||||
func isForeignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23503"
|
||||
}
|
||||
|
||||
// CreateUser inserts a user and relies on the unique index for both ordinary
|
||||
// duplicates and concurrent registrations of the same username.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
id := uuid.New()
|
||||
createdAt := time.Now().UTC()
|
||||
var stored time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
RETURNING created_at`,
|
||||
id, username, displayName, passwordHash, createdAt,
|
||||
).Scan(&stored)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, s.classify(err)
|
||||
}
|
||||
return model.User{
|
||||
ID: id,
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: model.Time{Time: stored.UTC()},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UserByUsername returns the public user and the Argon2id hash. The hash is
|
||||
// used only by the login handler and is never serialised.
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user model.User
|
||||
var passwordHash string
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, password_hash, created_at
|
||||
FROM users WHERE username = $1`, username,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &passwordHash, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrNotFound
|
||||
}
|
||||
return model.User{}, "", s.classify(err)
|
||||
}
|
||||
user.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
// UserByID resolves the identity stored in a server-side session.
|
||||
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user model.User
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at
|
||||
FROM users WHERE id = $1::uuid`, id,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrNotFound
|
||||
}
|
||||
return model.User{}, s.classify(err)
|
||||
}
|
||||
user.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// CreateChat inserts the chat and its membership in one transaction. A caller
|
||||
// cannot observe a chat without members: either both are committed or neither.
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (model.Chat, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
|
||||
var existing int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT count(*) FROM users
|
||||
WHERE id IN (SELECT value::uuid FROM unnest($1::text[]) AS value)`, memberIDs,
|
||||
).Scan(&existing); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
if existing != len(memberIDs) {
|
||||
return model.Chat{}, ErrUnknownMember
|
||||
}
|
||||
|
||||
id := uuid.New()
|
||||
createdAt := time.Now().UTC()
|
||||
var stored time.Time
|
||||
if err := tx.QueryRow(ctx, `
|
||||
INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)
|
||||
RETURNING created_at`, id, title, createdAt,
|
||||
).Scan(&stored); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
|
||||
batch := &pgx.Batch{}
|
||||
for position, memberID := range memberIDs {
|
||||
batch.Queue(`INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
|
||||
id, memberID, position)
|
||||
}
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
for range memberIDs {
|
||||
if _, err := results.Exec(); err != nil {
|
||||
_ = results.Close()
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Chat{}, ErrUnknownMember
|
||||
}
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
}
|
||||
if err := results.Close(); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
|
||||
return model.Chat{
|
||||
ID: id,
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: model.Time{Time: stored.UTC()},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// IsChatMember is used before parsing query parameters so a foreign chat is
|
||||
// always 404, independent of the submitted cursor or limit.
|
||||
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var member bool
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
|
||||
)`, chatID, userID).Scan(&member)
|
||||
if err != nil {
|
||||
return false, s.classify(err)
|
||||
}
|
||||
return member, nil
|
||||
}
|
||||
|
||||
// ChatForUser returns a chat only when the user is a member. A missing chat and
|
||||
// a foreign chat are indistinguishable to the caller.
|
||||
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var chat model.Chat
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2::uuid
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1::uuid
|
||||
GROUP BY c.id`, chatID, userID,
|
||||
).Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
const chatsPageSelect = `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1::uuid
|
||||
JOIN chat_members cm ON cm.chat_id = c.id`
|
||||
|
||||
// Chats returns one keyset page of chats visible to the user.
|
||||
func (s *Store) Chats(ctx context.Context, userID string, position *cursor.Cursor, limit int) (model.ChatPage, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
query := chatsPageSelect + `
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2`
|
||||
args := []any{userID, limit + 1}
|
||||
if position != nil {
|
||||
query = chatsPageSelect + `
|
||||
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`
|
||||
args = []any{userID, position.At, position.ID, limit + 1}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]model.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
items = append(items, chat)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
|
||||
page := model.ChatPage{Items: items}
|
||||
if len(items) > limit {
|
||||
page.Items = items[:limit]
|
||||
next := cursor.ForChat(page.Items[len(page.Items)-1])
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// CreateMessage appends a message. The composite foreign key also guarantees
|
||||
// that the sender belongs to the chat at the database level.
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, text string) (model.Message, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
}
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
RETURNING created_at`,
|
||||
message.ID, chatID, senderID, text, time.Now().UTC(),
|
||||
).Scan(&createdAt)
|
||||
if err != nil {
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Message{}, ErrNotFound
|
||||
}
|
||||
return model.Message{}, s.classify(err)
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
const messagesPageSelect = `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid`
|
||||
|
||||
// Messages returns one keyset page of a chat history. The caller has already
|
||||
// verified membership; the query itself never loads the whole history.
|
||||
func (s *Store) Messages(ctx context.Context, chatID string, position *cursor.Cursor, limit int) (model.MessagePage, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
query := messagesPageSelect + `
|
||||
ORDER BY created_at, messages.id
|
||||
LIMIT $2`
|
||||
args := []any{chatID, limit + 1}
|
||||
if position != nil {
|
||||
query = messagesPageSelect + `
|
||||
AND (created_at, messages.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY created_at, messages.id
|
||||
LIMIT $4`
|
||||
args = []any{chatID, position.At, position.ID, limit + 1}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]model.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt); err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
items = append(items, message)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
|
||||
page := model.MessagePage{Items: items}
|
||||
if len(items) > limit {
|
||||
page.Items = items[:limit]
|
||||
next := cursor.ForMessage(page.Items[len(page.Items)-1])
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Package uuid generates and normalizes canonical lowercase UUIDs. The
|
||||
// application, not PostgreSQL, assigns identifiers so every API replica and
|
||||
// the database agree on the exact on-the-wire form.
|
||||
package uuid
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// New returns a canonical lowercase UUIDv4. A failure of crypto/rand means the
|
||||
// process cannot safely create identifiers, so panicking is intentional; the
|
||||
// HTTP layer turns it into a generic 500 response.
|
||||
func New() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic("crypto/rand failed: " + err.Error())
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40 // version 4
|
||||
b[8] = (b[8] & 0x3f) | 0x80 // RFC 4122 variant
|
||||
return format(b)
|
||||
}
|
||||
|
||||
// NewRandom returns a lowercase hex string with n random bytes. It is used for
|
||||
// request ids and stable per-process instance ids, not for resource ids.
|
||||
func NewRandom(n int) string {
|
||||
raw := make([]byte, n)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
panic("crypto/rand failed: " + err.Error())
|
||||
}
|
||||
return hex.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func format(b [16]byte) string {
|
||||
var out [36]byte
|
||||
hex.Encode(out[0:8], b[0:4])
|
||||
out[8] = '-'
|
||||
hex.Encode(out[9:13], b[4:6])
|
||||
out[13] = '-'
|
||||
hex.Encode(out[14:18], b[6:8])
|
||||
out[18] = '-'
|
||||
hex.Encode(out[19:23], b[8:10])
|
||||
out[23] = '-'
|
||||
hex.Encode(out[24:36], b[10:16])
|
||||
return string(out[:])
|
||||
}
|
||||
|
||||
// Normalize accepts only the canonical 8-4-4-4-12 hyphenated form (ASCII hex,
|
||||
// case-insensitive) and returns its lowercase representation. Braces, urn:
|
||||
// prefixes, SQL uuid spellings and other aliases are rejected so resource
|
||||
// identifiers have exactly one wire form.
|
||||
func Normalize(value string) (string, bool) {
|
||||
if len(value) != 36 {
|
||||
return "", false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
switch i {
|
||||
case 8, 13, 18, 23:
|
||||
if c != '-' {
|
||||
return "", false
|
||||
}
|
||||
default:
|
||||
if !isHex(c) {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.ToLower(value), true
|
||||
}
|
||||
|
||||
func isHex(c byte) bool {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package uuid
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewIsCanonicalV4(t *testing.T) {
|
||||
id := New()
|
||||
normalized, ok := Normalize(id)
|
||||
if !ok || normalized != id {
|
||||
t.Fatalf("New() returned non-canonical UUID %q", id)
|
||||
}
|
||||
if id[14] != '4' {
|
||||
t.Fatalf("version nibble = %c, want 4", id[14])
|
||||
}
|
||||
if id[19] != '8' && id[19] != '9' && id[19] != 'a' && id[19] != 'b' {
|
||||
t.Fatalf("variant nibble = %c, want 8/9/a/b", id[19])
|
||||
}
|
||||
if New() == New() {
|
||||
t.Fatal("two generated UUIDs are equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalize(t *testing.T) {
|
||||
valid := "11111111-2222-4333-8444-555555555555"
|
||||
if got, ok := Normalize(valid); !ok || got != valid {
|
||||
t.Fatalf("Normalize(%q) = %q, %v", valid, got, ok)
|
||||
}
|
||||
upper := "AAAAAAAA-BBBB-4CCC-8DDD-EEEEEEEEEEEE"
|
||||
if got, ok := Normalize(upper); !ok || got != "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" {
|
||||
t.Fatalf("uppercase normalization failed: %q, %v", got, ok)
|
||||
}
|
||||
for _, invalid := range []string{
|
||||
"",
|
||||
"{11111111-2222-4333-8444-555555555555}",
|
||||
"urn:uuid:11111111-2222-4333-8444-555555555555",
|
||||
"11111111222243338444555555555555",
|
||||
"11111111-2222-4333-8444-55555555555z",
|
||||
"11111111-2222-4333-8444-5555555555555",
|
||||
" 1111111-2222-4333-8444-555555555555",
|
||||
} {
|
||||
if _, ok := Normalize(invalid); ok {
|
||||
t.Fatalf("Normalize accepted %q", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# Accept both the Compose v2 plugin ("docker compose") and the standalone
|
||||
# binary ("docker-compose"), so the same Makefile works on machines where only
|
||||
# one of them is installed. This wrapper does not change any global setting.
|
||||
set -eu
|
||||
if docker compose version >/dev/null 2>&1; then
|
||||
exec docker compose "$@"
|
||||
fi
|
||||
if command -v docker-compose >/dev/null 2>&1; then
|
||||
exec docker-compose "$@"
|
||||
fi
|
||||
echo "Docker Compose is required (docker compose or docker-compose)" >&2
|
||||
exit 2
|
||||
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Infrastructure checks for lab2: real containers, pinned images, named
|
||||
volumes, network isolation, non-root read-only API, health, graceful shutdown
|
||||
and absence of secrets/tokens in logs and Git.
|
||||
|
||||
This script never stops the main stack; the graceful-shutdown proof uses a
|
||||
separate short-lived container with a unique `mtusi-lab2-melnikov-` prefix.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check # noqa: E402
|
||||
|
||||
API = 'mtusi-lab2-melnikov-api'
|
||||
POSTGRES = 'mtusi-lab2-melnikov-postgres'
|
||||
VALKEY = 'mtusi-lab2-melnikov-valkey'
|
||||
GRACEFUL = 'mtusi-lab2-melnikov-graceful-check'
|
||||
NETWORK = 'mtusi-lab2-melnikov-net'
|
||||
VOLUMES = ['mtusi-lab2-melnikov-pgdata', 'mtusi-lab2-melnikov-valkeydata']
|
||||
|
||||
|
||||
def docker(*args):
|
||||
result = subprocess.run(['docker'] + list(args), capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
raise Failure('docker ' + ' '.join(args) + ' failed: ' + result.stderr.strip()[:300])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def inspect(name):
|
||||
return json.loads(docker('inspect', name))[0]
|
||||
|
||||
|
||||
def read_env():
|
||||
values = {}
|
||||
for line in (ROOT / '.env').read_text().splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
key, value = line.split('=', 1)
|
||||
values[key.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
def api_headers(base):
|
||||
import urllib.request
|
||||
request = urllib.request.Request(base + '/health/live', headers={'Accept': 'application/json'})
|
||||
with urllib.request.urlopen(request, timeout=10) as response:
|
||||
return {'instance': response.headers.get('X-Instance-Id'),
|
||||
'request': response.headers.get('X-Request-Id'),
|
||||
'status': response.status}
|
||||
|
||||
|
||||
def wait_healthy(name, timeout=45):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
state = inspect(name)['State']
|
||||
if state.get('Health', {}).get('Status') == 'healthy':
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise Failure(name + ' did not become healthy')
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--image', default='mtusi-messenger-lab2-melnikov:1.0.0')
|
||||
parser.add_argument('--output', default=None)
|
||||
|
||||
args = arguments('Container, volume, network and log checks', configure)
|
||||
env = read_env()
|
||||
observations = {}
|
||||
|
||||
# --- containers, images, volumes, network ------------------------------
|
||||
for name in (API, POSTGRES, VALKEY):
|
||||
wait_healthy(name)
|
||||
containers = {}
|
||||
for name in (API, POSTGRES, VALKEY):
|
||||
data = inspect(name)
|
||||
check(data['Name'] == '/' + name, 'unexpected container name ' + data['Name'])
|
||||
check(data['State']['Running'], name + ' is not running')
|
||||
check(data['State']['Health']['Status'] == 'healthy', name + ' is not healthy')
|
||||
containers[name] = {
|
||||
'image': data['Config']['Image'],
|
||||
'image_id': data['Image'],
|
||||
'started_at': data['State']['StartedAt'],
|
||||
'restart_policy': data['HostConfig']['RestartPolicy']['Name'],
|
||||
}
|
||||
check(containers[POSTGRES]['image'].startswith('postgres:16.4-alpine3.20@sha256:'),
|
||||
'PostgreSQL image is not pinned by digest')
|
||||
check(containers[VALKEY]['image'].startswith('valkey/valkey:8.0.2-alpine@sha256:'),
|
||||
'Valkey image is not pinned by digest')
|
||||
|
||||
api = inspect(API)
|
||||
check(api['Config']['User'] == '10001:10001', 'API image user is not 10001:10001')
|
||||
check(api['HostConfig']['ReadonlyRootfs'] is True, 'API root filesystem is writable')
|
||||
check('ALL' in (api['HostConfig']['CapDrop'] or []), 'API does not drop all capabilities')
|
||||
check(any('no-new-privileges' in item for item in (api['HostConfig']['SecurityOpt'] or [])),
|
||||
'API lacks no-new-privileges')
|
||||
check(docker('exec', API, 'id', '-u') == '10001', 'API process uid is not 10001')
|
||||
ui = api['HostConfig']['PortBindings'].get('8080/tcp') or []
|
||||
check(len(ui) == 1 and ui[0].get('HostIp') == '127.0.0.1', 'API port is not bound to loopback only')
|
||||
for name in (POSTGRES, VALKEY):
|
||||
data = inspect(name)
|
||||
check(not data['HostConfig']['PortBindings'], name + ' publishes an internal port')
|
||||
check(inspect(NETWORK)['Name'] == NETWORK, 'lab2 network missing')
|
||||
|
||||
volumes = {}
|
||||
for name in VOLUMES:
|
||||
data = inspect(name)
|
||||
volumes[name] = data['Mountpoint']
|
||||
check(data['Labels'].get('com.docker.compose.project') == 'mtusi-lab2-melnikov',
|
||||
name + ' is not owned by the lab2 compose project')
|
||||
observations['containers'] = containers
|
||||
observations['volumes'] = volumes
|
||||
observations['api_user'] = api['Config']['User']
|
||||
observations['api_read_only'] = api['HostConfig']['ReadonlyRootfs']
|
||||
observations['api_ports'] = ui
|
||||
|
||||
image = inspect(args.image)
|
||||
check(image['Id'] == containers[API]['image_id'], 'running API image differs from inspected image')
|
||||
labels = image['Config'].get('Labels') or {}
|
||||
check(labels.get('org.opencontainers.image.title') == 'mtusi-messenger-lab2',
|
||||
'API image label is missing')
|
||||
observations['image'] = {
|
||||
'reference': args.image,
|
||||
'id': image['Id'],
|
||||
'size_bytes': image['Size'],
|
||||
'user': image['Config']['User'],
|
||||
'healthcheck': image['Config'].get('Healthcheck', {}).get('Test'),
|
||||
'created': image['Created'],
|
||||
}
|
||||
|
||||
# --- Valkey is a real, persistent session store ------------------------
|
||||
def valkey_cli(arguments):
|
||||
return docker('exec', VALKEY, 'sh', '-c',
|
||||
'valkey-cli --no-auth-warning -a "$VALKEY_PASSWORD" ' + arguments)
|
||||
|
||||
appendonly = valkey_cli('CONFIG GET appendonly')
|
||||
appendfsync = valkey_cli('CONFIG GET appendfsync')
|
||||
datadir = valkey_cli('CONFIG GET dir')
|
||||
persistence = valkey_cli('INFO persistence')
|
||||
dbsize = int(valkey_cli('DBSIZE'))
|
||||
check('appendonly' in appendonly and 'yes' in appendonly, 'Valkey AOF is disabled')
|
||||
check('appendfsync' in appendfsync and 'everysec' in appendfsync, 'Valkey appendfsync is not everysec')
|
||||
check('/data' in datadir, 'Valkey data directory is not the named volume')
|
||||
check('aof_enabled:1' in persistence, 'Valkey INFO does not report AOF enabled')
|
||||
check('aof_last_write_status:ok' in persistence, 'Valkey AOF last write is not ok')
|
||||
check(dbsize > 0, 'Valkey has no live sessions to persist')
|
||||
observations['valkey'] = {
|
||||
'appendonly': 'yes',
|
||||
'appendfsync': 'everysec',
|
||||
'dir': '/data',
|
||||
'aof_enabled': True,
|
||||
'aof_last_write_status': 'ok',
|
||||
'session_keys': dbsize,
|
||||
}
|
||||
|
||||
# --- health headers and instance stability -----------------------------
|
||||
first = api_headers(args.base_url)
|
||||
second = api_headers(args.base_url)
|
||||
check(first['status'] == 200 and second['status'] == 200, 'liveness is not 200')
|
||||
check(first['instance'] and first['instance'] == second['instance'], 'X-Instance-Id is not stable')
|
||||
check(first['request'] and first['request'] != second['request'], 'X-Request-Id is not per-request')
|
||||
observations['instance_id'] = first['instance']
|
||||
|
||||
# --- logs must not contain credentials or message bodies ---------------
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
user = client.user('logs')
|
||||
registration = user['registration']
|
||||
chat = client.call('POST', '/api/v1/chats', 201, actor=user,
|
||||
body={'title': 'Проверка логов', 'member_ids': [user['id']]}, schema='Chat')['json']
|
||||
marker = 'log-secret-marker-' + registration['username']
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=user,
|
||||
body={'text': marker}, schema='Message')
|
||||
logs = docker('logs', '--tail', '400', API)
|
||||
checks = {
|
||||
'token_absent': user['token'] not in logs,
|
||||
'password_absent': registration['password'] not in logs,
|
||||
'message_body_absent': marker not in logs,
|
||||
'authorization_header_absent': 'Authorization: Bearer' not in logs,
|
||||
}
|
||||
check(all(checks.values()), 'API logs leak a token, password or message body: ' + repr(checks))
|
||||
observations['log_checks'] = checks
|
||||
|
||||
# --- graceful shutdown of a separate identical container ---------------
|
||||
database_url = ('postgres://%s:%s@postgres:5432/%s?sslmode=disable'
|
||||
% (env['POSTGRES_USER'], env['POSTGRES_PASSWORD'], env['POSTGRES_DB']))
|
||||
cache_url = 'redis://:%s@valkey:6379/0' % env['VALKEY_PASSWORD']
|
||||
started = time.monotonic()
|
||||
try:
|
||||
docker('run', '-d', '--name', GRACEFUL, '--network', NETWORK,
|
||||
'--read-only', '--tmpfs', '/tmp', '--cap-drop', 'ALL',
|
||||
'--security-opt', 'no-new-privileges:true', '--user', '10001:10001',
|
||||
'-e', 'APP_HOST=0.0.0.0', '-e', 'APP_PORT=8080', '-e', 'APP_ENV=lab',
|
||||
'-e', 'LOG_LEVEL=info', '-e', 'SESSION_TTL_SECONDS=3600',
|
||||
'-e', 'DATABASE_URL=' + database_url, '-e', 'CACHE_URL=' + cache_url,
|
||||
containers[API]['image_id'])
|
||||
wait_healthy(GRACEFUL, timeout=45)
|
||||
boot_seconds = time.monotonic() - started
|
||||
shutdown_started = time.monotonic()
|
||||
docker('stop', '--time', '15', GRACEFUL)
|
||||
shutdown_seconds = time.monotonic() - shutdown_started
|
||||
state = inspect(GRACEFUL)['State']
|
||||
graceful_logs = docker('logs', GRACEFUL)
|
||||
check(state['ExitCode'] == 0, 'graceful container exited with %r' % (state['ExitCode'],))
|
||||
check('shutdown complete' in graceful_logs, 'graceful shutdown log line is missing')
|
||||
check(shutdown_seconds <= 10, 'graceful shutdown took %.2fs (promised <=10s)' % shutdown_seconds)
|
||||
observations['graceful_shutdown'] = {
|
||||
'boot_seconds': round(boot_seconds, 3),
|
||||
'shutdown_seconds': round(shutdown_seconds, 3),
|
||||
'exit_code': state['ExitCode'],
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
docker('rm', '-f', GRACEFUL)
|
||||
except Failure:
|
||||
pass
|
||||
|
||||
# --- secrets must not be tracked by Git --------------------------------
|
||||
tracked = subprocess.run(['git', '-C', str(ROOT), 'ls-files'],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
tracked_files = [line for line in tracked.splitlines() if line]
|
||||
forbidden = [name for name in tracked_files
|
||||
if name == '.env' or name.startswith('secrets/') or name.endswith(('.pem', '.key', '.p12'))]
|
||||
check(not forbidden, 'tracked secret-like files: ' + repr(forbidden))
|
||||
check('.env.example' in tracked_files, '.env.example is not tracked')
|
||||
check(subprocess.run(['git', '-C', str(ROOT), 'check-ignore', '-q', '.env']).returncode == 0,
|
||||
'.env is not ignored by Git')
|
||||
password = env['POSTGRES_PASSWORD']
|
||||
if password:
|
||||
leaked = subprocess.run(['git', '-C', str(ROOT), 'grep', '-F', '--', password],
|
||||
capture_output=True, text=True).stdout
|
||||
check(not leaked, 'a generated local password is present in tracked files')
|
||||
observations['git'] = {'tracked_files': len(tracked_files), 'env_ignored': True,
|
||||
'secret_like_tracked': forbidden}
|
||||
observations['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
|
||||
if args.output:
|
||||
destination = Path(args.output)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(observations, indent=2, ensure_ascii=False) + '\n')
|
||||
print(json.dumps({
|
||||
'image_id': observations['image']['id'],
|
||||
'image_size_bytes': observations['image']['size_bytes'],
|
||||
'volumes': sorted(observations['volumes']),
|
||||
'graceful_shutdown_seconds': observations['graceful_shutdown']['shutdown_seconds'],
|
||||
'logs_clean': True,
|
||||
'secret_like_tracked_files': forbidden,
|
||||
}, ensure_ascii=False, sort_keys=True))
|
||||
print('PASS: real containers, pinned images, named volumes, non-root read-only API, graceful shutdown, clean logs')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,319 @@
|
||||
#!/usr/bin/env python3
|
||||
"""SQL-level checks for lab2: schema constraints, unique username under
|
||||
concurrency, password hashes, transaction rollback of the composite chat
|
||||
operation, idempotent migrations and EXPLAIN (ANALYZE, BUFFERS) on a history
|
||||
of at least 10 000 messages.
|
||||
|
||||
All database commands run non-interactively inside the lab2 PostgreSQL
|
||||
container with ON_ERROR_STOP=1.
|
||||
"""
|
||||
import datetime as dt
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check # noqa: E402
|
||||
|
||||
POSTGRES = 'mtusi-lab2-melnikov-postgres'
|
||||
API = 'mtusi-lab2-melnikov-api'
|
||||
|
||||
|
||||
def read_env():
|
||||
values = {}
|
||||
for line in (ROOT / '.env').read_text().splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
key, value = line.split('=', 1)
|
||||
values[key.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
ENV = read_env()
|
||||
|
||||
|
||||
def psql(sql, allow_failure=False):
|
||||
result = subprocess.run(
|
||||
['docker', 'exec', '-i', POSTGRES, 'psql', '-X', '-A', '-t', '-F', '|',
|
||||
'-v', 'ON_ERROR_STOP=1', '-U', ENV['POSTGRES_USER'], '-d', ENV['POSTGRES_DB']],
|
||||
input=sql, capture_output=True, text=True)
|
||||
if result.returncode != 0 and not allow_failure:
|
||||
raise Failure('psql failed: ' + result.stderr.strip()[:400])
|
||||
return result
|
||||
|
||||
|
||||
def query(sql):
|
||||
return psql(sql).stdout.strip()
|
||||
|
||||
|
||||
def wait_ready(base_url, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base_url + '/health/ready', timeout=3) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except Exception: # noqa: BLE001 - expected while the API restarts
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise Failure('API did not become ready after restart')
|
||||
|
||||
|
||||
def ensure_large_history(c, output_dir):
|
||||
"""Return (chat_id, message_count). Seeds 12 000 rows only when the
|
||||
database does not already contain a 10 000+ message history."""
|
||||
total = int(query('SELECT count(*) FROM messages;'))
|
||||
if total >= 10000:
|
||||
row = query("""
|
||||
SELECT chat_id::text || '|' || count(*)
|
||||
FROM messages GROUP BY chat_id ORDER BY count(*) DESC, min(created_at) LIMIT 1;
|
||||
""")
|
||||
chat_id, count = row.split('|')
|
||||
return chat_id, int(count), total
|
||||
|
||||
owner = c.user('explain')
|
||||
chat = c.call('POST', '/api/v1/chats', 201, actor=owner,
|
||||
body={'title': 'level4 explain history',
|
||||
'member_ids': [owner['id']]}, schema='Chat')['json']
|
||||
target = 12000
|
||||
psql("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), '%s'::uuid, '%s'::uuid, 'level4 row ' || g,
|
||||
timestamptz '2026-02-01 00:00:00+00' + (g || ' milliseconds')::interval
|
||||
FROM generate_series(1, %d) AS g;
|
||||
ANALYZE messages;
|
||||
""" % (chat['id'], owner['id'], target))
|
||||
count = int(query("SELECT count(*) FROM messages WHERE chat_id='%s';" % chat['id']))
|
||||
check(count == target, 'seeded history has %d rows, want %d' % (count, target))
|
||||
return chat['id'], count, total + target
|
||||
|
||||
|
||||
def explain(sql):
|
||||
result = psql('EXPLAIN (ANALYZE, BUFFERS) ' + sql + ';\n')
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--output-dir', default='evidence')
|
||||
|
||||
args = arguments('SQL constraints, rollback, migrations and EXPLAIN', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
output_dir = ROOT / args.output_dir
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
setup = c.user('dbcheck')
|
||||
evidence = {'checked_at': dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')}
|
||||
|
||||
# --- schema and constraints -------------------------------------------
|
||||
versions = query('SELECT string_agg(version::text, \',\' ORDER BY version) FROM schema_migrations;')
|
||||
check(versions == '1,2', 'schema_migrations versions = %r, want 1,2' % versions)
|
||||
duplicate_users = int(query("""
|
||||
SELECT count(*) FROM (SELECT username FROM users GROUP BY username HAVING count(*) > 1) duplicates;
|
||||
"""))
|
||||
check(duplicate_users == 0, 'duplicate usernames exist despite the unique index')
|
||||
required_constraints = {
|
||||
'users_pkey', 'users_username_format', 'users_display_name_length',
|
||||
'users_password_hash_present', 'chats_pkey', 'chats_title_length',
|
||||
'chat_members_pkey', 'chat_members_chat_id_fkey', 'chat_members_user_id_fkey',
|
||||
'chat_members_position_nonnegative', 'messages_pkey', 'messages_text_length',
|
||||
'messages_chat_fk', 'messages_sender_membership_fk',
|
||||
}
|
||||
present_constraints = set(query("""
|
||||
SELECT conname FROM pg_constraint
|
||||
WHERE conrelid IN ('users'::regclass, 'chats'::regclass, 'chat_members'::regclass, 'messages'::regclass);
|
||||
""").splitlines())
|
||||
missing = required_constraints - present_constraints
|
||||
check(not missing, 'missing database constraints: ' + repr(sorted(missing)))
|
||||
required_indexes = {'users_username_key', 'chat_members_user_chat_idx',
|
||||
'messages_chat_created_id_idx', 'chats_created_id_idx'}
|
||||
present_indexes = set(query("SELECT indexname FROM pg_indexes WHERE schemaname='public';").splitlines())
|
||||
missing_indexes = required_indexes - present_indexes
|
||||
check(not missing_indexes, 'missing indexes: ' + repr(sorted(missing_indexes)))
|
||||
check(query("""
|
||||
SELECT count(*) FROM information_schema.tables
|
||||
WHERE table_schema='public' AND table_name ILIKE '%session%';
|
||||
""") == '0', 'sessions must not be stored in PostgreSQL')
|
||||
|
||||
users = int(query('SELECT count(*) FROM users;'))
|
||||
hashed = int(query("SELECT count(*) FROM users WHERE password_hash LIKE '$argon2id$%';"))
|
||||
check(users >= 1, 'expected at least the setup user, found %d' % users)
|
||||
check(hashed == users, 'not every stored password is an Argon2id PHC string')
|
||||
check(query("SELECT count(*) FROM users WHERE password_hash IN ('', 'password');") == '0',
|
||||
'empty or literal password hash found')
|
||||
race_duplicates = int(query("""
|
||||
SELECT count(*) FROM (SELECT username FROM users WHERE username LIKE 'race_%'
|
||||
GROUP BY username HAVING count(*) > 1) duplicates;
|
||||
"""))
|
||||
check(race_duplicates == 0, 'concurrent registration created duplicate usernames')
|
||||
evidence['schema'] = {
|
||||
'migration_versions': versions,
|
||||
'constraints_present': sorted(required_constraints),
|
||||
'indexes_present': sorted(required_indexes),
|
||||
'users': users,
|
||||
'argon2id_hashes': hashed,
|
||||
'duplicate_usernames': duplicate_users,
|
||||
'race_duplicates': race_duplicates,
|
||||
}
|
||||
|
||||
# --- database-level sender membership FK ------------------------------
|
||||
chat_id = query('SELECT id::text FROM chats ORDER BY created_at LIMIT 1;')
|
||||
outsider = query("""
|
||||
SELECT id::text FROM users
|
||||
WHERE id NOT IN (SELECT user_id FROM chat_members WHERE chat_id='%s')
|
||||
ORDER BY created_at LIMIT 1;
|
||||
""" % chat_id)
|
||||
check(bool(outsider), 'could not find a non-member for the FK probe')
|
||||
before = int(query('SELECT count(*) FROM messages;'))
|
||||
failed = psql("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (gen_random_uuid(), '%s'::uuid, '%s'::uuid, 'fk probe', now());
|
||||
""" % (chat_id, outsider), allow_failure=True)
|
||||
after = int(query('SELECT count(*) FROM messages;'))
|
||||
check(failed.returncode != 0, 'database accepted a message from a non-member sender')
|
||||
check(before == after, 'failed FK insert changed the message count')
|
||||
evidence['sender_membership_fk'] = {'rejected': True, 'messages_before': before, 'messages_after': after}
|
||||
|
||||
# --- rollback of the composite chat operation -------------------------
|
||||
owner = c.user('rollback')
|
||||
other = c.user('rollback')
|
||||
psql("""
|
||||
CREATE OR REPLACE FUNCTION lab2_rollback_probe() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM chats WHERE id = NEW.chat_id AND title = 'rollback-probe') THEN
|
||||
RAISE EXCEPTION 'injected composite failure';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
DROP TRIGGER IF EXISTS lab2_rollback_probe ON chat_members;
|
||||
CREATE TRIGGER lab2_rollback_probe BEFORE INSERT ON chat_members
|
||||
FOR EACH ROW EXECUTE FUNCTION lab2_rollback_probe();
|
||||
""")
|
||||
try:
|
||||
response = c.call('POST', '/api/v1/chats', 500, actor=owner,
|
||||
body={'title': 'rollback-probe', 'member_ids': [owner['id'], other['id']]})
|
||||
check(response['json']['error']['code'] == 'internal_error', 'rollback probe error code')
|
||||
message = response['json']['error']['message'].lower()
|
||||
for leaked in ('injected', 'sql', 'lab2_rollback', 'trigger'):
|
||||
check(leaked not in message, '500 body leaks internal detail %r' % leaked)
|
||||
finally:
|
||||
psql("""
|
||||
DROP TRIGGER IF EXISTS lab2_rollback_probe ON chat_members;
|
||||
DROP FUNCTION IF EXISTS lab2_rollback_probe();
|
||||
""")
|
||||
leftover = query("SELECT count(*) FROM chats WHERE title='rollback-probe';")
|
||||
check(leftover == '0', 'composite chat operation left a chat without members after rollback')
|
||||
evidence['composite_rollback'] = {'chats_left': int(leftover), 'api_status': 500}
|
||||
|
||||
# --- migrations re-run on API restart without duplicating data --------
|
||||
counts_sql = ('SELECT (SELECT count(*) FROM users) || \',\' || (SELECT count(*) FROM chats) || \',\' || '
|
||||
'(SELECT count(*) FROM chat_members) || \',\' || (SELECT count(*) FROM messages);')
|
||||
before_counts = query(counts_sql)
|
||||
started_before = json.loads(subprocess.run(
|
||||
['docker', 'inspect', API], capture_output=True, text=True, check=True).stdout)[0]['State']['StartedAt']
|
||||
subprocess.run(['docker', 'restart', API], check=True, capture_output=True)
|
||||
wait_ready(args.base_url)
|
||||
after_counts = query(counts_sql)
|
||||
migrations_after = query('SELECT count(*) FROM schema_migrations;')
|
||||
started_after = json.loads(subprocess.run(
|
||||
['docker', 'inspect', API], capture_output=True, text=True, check=True).stdout)[0]['State']['StartedAt']
|
||||
check(before_counts == after_counts, 'API restart duplicated or lost rows: %r -> %r'
|
||||
% (before_counts, after_counts))
|
||||
check(migrations_after == '2', 'migrations table changed after restart')
|
||||
check(started_before != started_after, 'API was not actually restarted')
|
||||
evidence['migrations_idempotent'] = {
|
||||
'counts_before': before_counts, 'counts_after': after_counts,
|
||||
'migrations_after': int(migrations_after), 'api_restarted': True,
|
||||
}
|
||||
|
||||
# --- EXPLAIN on a >=10 000 message history ----------------------------
|
||||
chat_id, history_count, total = ensure_large_history(c, output_dir)
|
||||
check(history_count >= 10000, 'EXPLAIN history has only %d messages' % history_count)
|
||||
deep_offset = max(1000, history_count // 2)
|
||||
row = query("""
|
||||
SELECT created_at::text || '|' || id::text FROM messages
|
||||
WHERE chat_id='%s' ORDER BY created_at, messages.id OFFSET %d LIMIT 1;
|
||||
""" % (chat_id, deep_offset)).split('|')
|
||||
cursor_time, cursor_id = row
|
||||
keyset_sql = ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id='%s'::uuid AND (created_at, messages.id) > ('%s'::timestamptz, '%s'::uuid)
|
||||
ORDER BY created_at, messages.id LIMIT 50
|
||||
""" % (chat_id, cursor_time, cursor_id))
|
||||
first_sql = ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE chat_id='%s'::uuid
|
||||
ORDER BY created_at, messages.id LIMIT 50
|
||||
""" % chat_id)
|
||||
offset_sql = ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE chat_id='%s'::uuid
|
||||
ORDER BY created_at, messages.id OFFSET %d LIMIT 50
|
||||
""" % (chat_id, deep_offset))
|
||||
|
||||
first_plan = explain(first_sql)
|
||||
keyset_plan = explain(keyset_sql)
|
||||
offset_plan = explain(offset_sql)
|
||||
for name, plan in (('first page', first_plan), ('deep keyset page', keyset_plan)):
|
||||
check('Index Scan using messages_chat_created_id_idx' in plan,
|
||||
name + ' does not use the history index:\n' + plan)
|
||||
check('Seq Scan on messages' not in plan, name + ' performs a sequential scan')
|
||||
check('Index Scan using messages_chat_created_id_idx' in offset_plan,
|
||||
'naive OFFSET plan unexpectedly avoids the index')
|
||||
|
||||
import re
|
||||
def scanned_rows(plan):
|
||||
match = re.search(
|
||||
r'Index Scan using messages_chat_created_id_idx.*?actual time=[\d.]+\.[\d.]+ rows=(\d+)',
|
||||
plan, re.S)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
first_rows = scanned_rows(first_plan)
|
||||
keyset_rows = scanned_rows(keyset_plan)
|
||||
offset_rows = scanned_rows(offset_plan)
|
||||
check(first_rows == 50, 'first page scanned %r rows, want 50' % (first_rows,))
|
||||
check(keyset_rows == 50, 'deep keyset page scanned %r rows, want 50' % (keyset_rows,))
|
||||
check(offset_rows is not None and offset_rows > deep_offset,
|
||||
'OFFSET comparison did not demonstrate a large scan (%r rows)' % (offset_rows,))
|
||||
plan_text = (
|
||||
'LAB2 LEVEL 4 EXPLAIN EVIDENCE\n'
|
||||
'messages in history: %d, total messages: %d, deep offset: %d\n\n'
|
||||
'=== first page ===\n%s\n\n=== keyset page after offset %d ===\n%s\n\n'
|
||||
'=== naive OFFSET %d ===\n%s\n' % (
|
||||
history_count, total, deep_offset, first_plan, deep_offset, keyset_plan, deep_offset, offset_plan)
|
||||
)
|
||||
(output_dir / 'explain-level4.txt').write_text(plan_text)
|
||||
evidence['explain'] = {
|
||||
'chat_id': chat_id, 'history_messages': history_count, 'total_messages': total,
|
||||
'first_page_index_rows': first_rows, 'keyset_page_index_rows': keyset_rows,
|
||||
'offset_page_index_rows': offset_rows, 'deep_offset': deep_offset,
|
||||
'index_used': 'messages_chat_created_id_idx',
|
||||
}
|
||||
|
||||
(output_dir / 'db-checks.json').write_text(json.dumps(evidence, indent=2, ensure_ascii=False) + '\n')
|
||||
print(json.dumps({
|
||||
'migrations': versions,
|
||||
'constraints': len(required_constraints),
|
||||
'indexes': len(required_indexes),
|
||||
'argon2id_hashes': hashed,
|
||||
'composite_rollback_left_chats': int(leftover),
|
||||
'migration_counts_stable': before_counts == after_counts,
|
||||
'explain_history_messages': history_count,
|
||||
'keyset_rows_read': keyset_rows,
|
||||
'offset_rows_read': offset_rows,
|
||||
}, ensure_ascii=False, sort_keys=True))
|
||||
print('PASS: SQL constraints, FK, rollback, idempotent migrations and index-backed EXPLAIN')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Short-TTL session expiry and API-restart test for lab2.
|
||||
|
||||
Operator contract: the API must be started with a short SESSION_TTL_SECONDS
|
||||
(the Makefile target test-expiry recreates only the API with 15 seconds).
|
||||
The script:
|
||||
1. registers and logs in a synthetic user;
|
||||
2. checks that /users/me works with the token;
|
||||
3. optionally restarts ONLY the API container and checks the same token still
|
||||
works (sessions live in Valkey, not in API memory) while the process
|
||||
instance id changes;
|
||||
4. waits for the original expiry deadline and checks the token now gets 401,
|
||||
so the TTL was not extended by the restart.
|
||||
|
||||
No token is printed or written.
|
||||
"""
|
||||
import base64
|
||||
import datetime as dt
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check, timestamp # noqa: E402
|
||||
|
||||
|
||||
def wait_ready(base_url, timeout=90):
|
||||
import urllib.request
|
||||
deadline = time.monotonic() + timeout
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base_url + '/health/ready', timeout=3) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001 - readiness polling
|
||||
last = exc
|
||||
time.sleep(0.5)
|
||||
raise Failure('API did not become ready after restart (' + type(last).__name__ + ')') from None
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--restart-api', action='store_true',
|
||||
help='restart only the API container through scripts/compose.sh')
|
||||
parser.add_argument('--expected-ttl', type=int, default=15,
|
||||
help='SESSION_TTL_SECONDS the API was started with')
|
||||
|
||||
args = arguments('Short-TTL session expiry and API restart', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
actor = c.user('expiry')
|
||||
registration = actor['registration']
|
||||
credential = base64.b64encode(
|
||||
(registration['username'] + ':' + registration['password']).encode('utf-8')).decode('ascii')
|
||||
session = c.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
actor['token'] = session['token']
|
||||
expires = timestamp(session['expires_at'])
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
remaining = (expires - now).total_seconds()
|
||||
check(remaining > 1, 'session expired before the test started')
|
||||
check(remaining <= args.expected_ttl + 2,
|
||||
'session TTL is %.1fs, expected about %ds; start the API with the short TTL'
|
||||
% (remaining, args.expected_ttl))
|
||||
|
||||
me = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json']
|
||||
check(me['id'] == actor['id'], 'fresh token does not resolve to its user')
|
||||
instance_before = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['headers']['X-Instance-Id']
|
||||
check(bool(instance_before), 'missing X-Instance-Id')
|
||||
|
||||
if args.restart_api:
|
||||
started = time.monotonic()
|
||||
subprocess.run([str(ROOT / 'scripts/compose.sh'), '--env-file', '.env', 'restart', 'api'],
|
||||
cwd=str(ROOT), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
wait_ready(args.base_url)
|
||||
restart_seconds = time.monotonic() - started
|
||||
# The same token must still be valid: the session was not stored in the
|
||||
# API process and was not dropped by recreating it.
|
||||
same = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
check(same['json']['id'] == actor['id'], 'token was lost when the API restarted')
|
||||
instance_after = same['headers']['X-Instance-Id']
|
||||
check(instance_after != instance_before, 'API instance id did not change after restart')
|
||||
print('PASS: token survived an API-only restart in %.2fs; instance %s -> %s'
|
||||
% (restart_seconds, instance_before, instance_after))
|
||||
else:
|
||||
restart_seconds = None
|
||||
instance_after = instance_before
|
||||
|
||||
# Wait for the absolute deadline that was returned at login. Polling also
|
||||
# tolerates small clock differences between host and container.
|
||||
deadline = time.monotonic() + max(0.0, (expires - dt.datetime.now(dt.timezone.utc)).total_seconds()) + 2
|
||||
status = None
|
||||
while time.monotonic() < deadline + 10:
|
||||
response = c.call('GET', '/api/v1/users/me', (200, 401), actor=actor)
|
||||
status = response['status']
|
||||
if status == 401:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
check(status == 401, 'expired token still authenticates (status %r)' % (status,))
|
||||
challenge = c.call('GET', '/api/v1/users/me', 401, actor=actor)['headers'].get('WWW-Authenticate', '')
|
||||
check(challenge.lower().startswith('bearer'), 'expired token 401 has no Bearer challenge')
|
||||
# Revoked/expired sessions cannot be logged out a second time.
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor)
|
||||
|
||||
summary = {
|
||||
'checked_at': dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z'),
|
||||
'configured_ttl_seconds': args.expected_ttl,
|
||||
'observed_ttl_seconds': round(remaining, 3),
|
||||
'api_restart': bool(args.restart_api),
|
||||
'api_restart_seconds': None if restart_seconds is None else round(restart_seconds, 3),
|
||||
'instance_before': instance_before,
|
||||
'instance_after': instance_after,
|
||||
'expired_status': status,
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
|
||||
print('PASS: short-TTL expiry, absolute deadline, and API-restart session survival')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Dependency-outage checks for lab2.
|
||||
|
||||
Stops and starts the real lab2 containers with `docker stop` / `docker start`.
|
||||
Volumes are never removed. It verifies the level-4 requirement that loss of
|
||||
Valkey or PostgreSQL produces a bounded 503 and never turns an anonymous
|
||||
request into a trusted one, and that recovery keeps the existing session and
|
||||
confirmed data.
|
||||
|
||||
The operator is expected to run this against the local teaching stand only.
|
||||
"""
|
||||
import base64
|
||||
import datetime as dt
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check # noqa: E402
|
||||
|
||||
POSTGRES = 'mtusi-lab2-melnikov-postgres'
|
||||
VALKEY = 'mtusi-lab2-melnikov-valkey'
|
||||
VOLUMES = ['mtusi-lab2-melnikov-pgdata', 'mtusi-lab2-melnikov-valkeydata']
|
||||
|
||||
|
||||
def docker(*args, quiet=False):
|
||||
result = subprocess.run(['docker'] + list(args), capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
raise Failure('docker ' + ' '.join(args) + ' failed: ' + result.stderr.strip()[:200])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def inspect_state(name):
|
||||
raw = docker('inspect', name)
|
||||
return json.loads(raw)[0]
|
||||
|
||||
|
||||
def http(base, method, path, token=None, body=None, timeout=10, extra_headers=None):
|
||||
headers = {'Accept': 'application/json'}
|
||||
data = None
|
||||
if token:
|
||||
headers['Authorization'] = 'Bearer ' + token
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode('utf-8')
|
||||
headers['Content-Type'] = 'application/json'
|
||||
request = urllib.request.Request(base + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
raw = response.read()
|
||||
return response.status, dict(response.headers), json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as error:
|
||||
raw = error.read()
|
||||
return error.code, dict(error.headers), json.loads(raw) if raw else None
|
||||
except Exception: # noqa: BLE001 - a refused connection is an expected observation
|
||||
return None, {}, None
|
||||
|
||||
|
||||
def wait_status(base, path, expected, timeout=45):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
status, _, _ = http(base, 'GET', path)
|
||||
last = status
|
||||
if status == expected:
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise Failure('%s did not reach %s within %ss (last %r)' % (path, expected, timeout, last))
|
||||
|
||||
|
||||
def expect_unavailable(base, path, token=None):
|
||||
status, headers, payload = http(base, 'GET', path, token=token)
|
||||
check(status == 503, path + ' expected 503, got %r' % (status,))
|
||||
check(payload and payload.get('error', {}).get('code') == 'unavailable', path + ' error code')
|
||||
check(payload['error']['request_id'] == headers.get('X-Request-Id'), path + ' request id mismatch')
|
||||
return {'path': path, 'status': status, 'code': payload['error']['code']}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--output', default=None, help='optional JSON evidence path')
|
||||
|
||||
args = arguments('Stop/start Valkey and PostgreSQL; volumes are preserved', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
actor = c.user('failure')
|
||||
chat = c.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': 'Отказ зависимости', 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
probe = 'failure-probe-' + uuid.uuid4().hex
|
||||
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
||||
body={'text': probe}, schema='Message')['json']
|
||||
|
||||
volume_before = {name: inspect_state(name)['Mountpoint'] for name in VOLUMES}
|
||||
states_before = {name: inspect_state(name)['State']['StartedAt'] for name in (POSTGRES, VALKEY)}
|
||||
observations = {'probe_message_id': message['id'], 'volumes_before': volume_before,
|
||||
'containers_started_before': states_before}
|
||||
|
||||
try:
|
||||
# ---- Valkey outage -------------------------------------------------
|
||||
docker('stop', '--time', '20', VALKEY)
|
||||
stopped = time.monotonic()
|
||||
wait_status(args.base_url, '/health/ready', 503)
|
||||
valkey = {}
|
||||
status, headers, payload = http(args.base_url, 'GET', '/health/live')
|
||||
check(status == 200 and payload == {'status': 'ok'}, 'liveness must stay 200 without Valkey')
|
||||
valkey['liveness'] = {'status': status, 'body': payload}
|
||||
valkey['readiness'] = {'status': 503}
|
||||
valkey['authenticated_request'] = expect_unavailable(args.base_url, '/api/v1/users/me', actor['token'])
|
||||
status, headers, payload = http(args.base_url, 'GET', '/api/v1/users/me')
|
||||
check(status == 401 and payload['error']['code'] == 'unauthorized',
|
||||
'anonymous request without Valkey must stay 401')
|
||||
valkey['anonymous_request'] = {'status': status, 'code': payload['error']['code']}
|
||||
credential = 'Basic ' + base64.b64encode(
|
||||
(actor['registration']['username'] + ':' + actor['registration']['password']).encode('utf-8')).decode('ascii')
|
||||
status, headers, payload = http(args.base_url, 'POST', '/api/v1/auth/sessions',
|
||||
extra_headers={'Authorization': credential})
|
||||
check(status == 503 and payload['error']['code'] == 'unavailable',
|
||||
'login with valid credentials must be a bounded 503 without Valkey')
|
||||
valkey['login'] = {'status': status, 'code': payload['error']['code']}
|
||||
# Registration only needs PostgreSQL; it is allowed to work while the
|
||||
# session store is down, and proves the outage is bounded to sessions.
|
||||
outage_user = 'outage_' + uuid.uuid4().hex[:10]
|
||||
status, headers, payload = http(args.base_url, 'POST', '/api/v1/users', body={
|
||||
'username': outage_user,
|
||||
'display_name': 'Во время отказа Valkey',
|
||||
'password': 'Outage-password-123',
|
||||
})
|
||||
check(status == 201 and payload['username'] == outage_user,
|
||||
'registration should be independent of the session store')
|
||||
valkey['registration_while_down'] = {'status': status}
|
||||
|
||||
# ---- Valkey recovery ----------------------------------------------
|
||||
docker('start', VALKEY)
|
||||
wait_status(args.base_url, '/health/ready', 200)
|
||||
valkey['recovery_seconds'] = round(time.monotonic() - stopped, 3)
|
||||
status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me', token=actor['token'])
|
||||
check(status == 200 and payload['id'] == actor['id'],
|
||||
'existing session did not survive the Valkey stop/start')
|
||||
valkey['session_after_recovery'] = {'status': status}
|
||||
observations['valkey_outage'] = valkey
|
||||
|
||||
# ---- PostgreSQL outage --------------------------------------------
|
||||
docker('stop', '--time', '20', POSTGRES)
|
||||
stopped = time.monotonic()
|
||||
wait_status(args.base_url, '/health/ready', 503)
|
||||
postgres = {}
|
||||
status, _, payload = http(args.base_url, 'GET', '/health/live')
|
||||
check(status == 200 and payload == {'status': 'ok'}, 'liveness must stay 200 without PostgreSQL')
|
||||
postgres['liveness'] = {'status': status, 'body': payload}
|
||||
postgres['readiness'] = {'status': http(args.base_url, 'GET', '/health/ready')[0]}
|
||||
postgres['authenticated_request'] = expect_unavailable(args.base_url, '/api/v1/users/me', actor['token'])
|
||||
status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me')
|
||||
check(status == 401, 'anonymous request without PostgreSQL must stay 401')
|
||||
postgres['anonymous_request'] = {'status': status, 'code': payload['error']['code']}
|
||||
status, _, payload = http(args.base_url, 'POST', '/api/v1/users', body={
|
||||
'username': 'unreachable_' + uuid.uuid4().hex[:8],
|
||||
'display_name': 'Не должно создаться',
|
||||
'password': 'Outage-password-123',
|
||||
})
|
||||
check(status == 503 and payload['error']['code'] == 'unavailable',
|
||||
'registration must be a bounded 503 without PostgreSQL')
|
||||
postgres['registration'] = {'status': status, 'code': payload['error']['code']}
|
||||
|
||||
# ---- PostgreSQL recovery ------------------------------------------
|
||||
docker('start', POSTGRES)
|
||||
wait_status(args.base_url, '/health/ready', 200)
|
||||
postgres['recovery_seconds'] = round(time.monotonic() - stopped, 3)
|
||||
status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me', token=actor['token'])
|
||||
check(status == 200 and payload['id'] == actor['id'],
|
||||
'existing session did not survive the PostgreSQL stop/start')
|
||||
postgres['session_after_recovery'] = {'status': status}
|
||||
status, _, payload = http(
|
||||
args.base_url, 'GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', token=actor['token'])
|
||||
check(status == 200 and any(item['id'] == message['id'] for item in payload['items']),
|
||||
'confirmed message was lost across the PostgreSQL stop/start')
|
||||
postgres['message_after_recovery'] = {'status': status, 'found': True}
|
||||
observations['postgres_outage'] = postgres
|
||||
finally:
|
||||
for name in (POSTGRES, VALKEY):
|
||||
state = inspect_state(name)['State']
|
||||
if not state['Running']:
|
||||
docker('start', name)
|
||||
try:
|
||||
wait_status(args.base_url, '/health/ready', 200)
|
||||
except Failure:
|
||||
pass
|
||||
|
||||
volume_after = {name: inspect_state(name)['Mountpoint'] for name in VOLUMES}
|
||||
states_after = {name: inspect_state(name)['State']['StartedAt'] for name in (POSTGRES, VALKEY)}
|
||||
check(volume_after == volume_before, 'named volumes changed or were removed during the outage test')
|
||||
check(all(states_after[name] != states_before[name] for name in states_before),
|
||||
'containers were not really restarted')
|
||||
observations['volumes_after'] = volume_after
|
||||
observations['containers_started_after'] = states_after
|
||||
observations['finished_at'] = dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
|
||||
if args.output:
|
||||
destination = Path(args.output)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(observations, indent=2, ensure_ascii=False) + '\n')
|
||||
print(json.dumps({'valkey_recovery_seconds': observations['valkey_outage']['recovery_seconds'],
|
||||
'postgres_recovery_seconds': observations['postgres_outage']['recovery_seconds'],
|
||||
'volumes_kept': sorted(volume_after),
|
||||
'workers_really_restarted': True}, ensure_ascii=False, sort_keys=True))
|
||||
print('PASS: bounded 503 on Valkey/PostgreSQL outage; session and data survive recovery; volumes kept')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Create a local .env with fresh synthetic passwords. The file is ignored by
|
||||
# Git, is readable only by the current user, and its values are never printed.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ -f .env ]; then
|
||||
echo ".env already exists; refusing to overwrite it" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Alphanumeric only, so the values are safe inside a URL with no percent
|
||||
# encoding. 32 bytes of /dev/urandom gives 256 bits of entropy.
|
||||
random_secret() {
|
||||
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32
|
||||
}
|
||||
|
||||
postgres_password=$(random_secret)
|
||||
valkey_password=$(random_secret)
|
||||
if [ "${#postgres_password}" -ne 32 ] || [ "${#valkey_password}" -ne 32 ]; then
|
||||
echo "could not generate local secrets" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
umask 077
|
||||
sed \
|
||||
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${postgres_password}|" \
|
||||
-e "s|^VALKEY_PASSWORD=.*|VALKEY_PASSWORD=${valkey_password}|" \
|
||||
.env.example > .env
|
||||
chmod 600 .env
|
||||
echo "wrote .env with generated local synthetic credentials (mode 600); values not printed"
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# Restart the API and every state store this lab uses, keeping the named
|
||||
# volumes and all data. This is the hook for
|
||||
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
# It never removes volumes, never re-seeds and never prints credentials.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
echo "restart.sh: .env is missing; run make env first" >&2
|
||||
exit 2
|
||||
fi
|
||||
if ! ./scripts/compose.sh --env-file .env ps --status running --quiet >/dev/null 2>&1; then
|
||||
echo "restart.sh: compose stack is not available" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
wait_healthy() {
|
||||
container=$1
|
||||
attempts=0
|
||||
while [ "$attempts" -lt 60 ]; do
|
||||
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container" 2>/dev/null || echo missing)
|
||||
if [ "$status" = "healthy" ] || [ "$status" = "running" ]; then
|
||||
return 0
|
||||
fi
|
||||
attempts=$((attempts + 1))
|
||||
sleep 1
|
||||
done
|
||||
echo "restart.sh: $container did not become healthy" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
echo "restart.sh: restarting postgres and valkey (volumes kept)"
|
||||
./scripts/compose.sh --env-file .env restart postgres valkey
|
||||
wait_healthy mtusi-lab2-melnikov-postgres
|
||||
wait_healthy mtusi-lab2-melnikov-valkey
|
||||
|
||||
echo "restart.sh: restarting api (migrations re-applied idempotently)"
|
||||
./scripts/compose.sh --env-file .env restart api
|
||||
wait_healthy mtusi-lab2-melnikov-api
|
||||
|
||||
echo "restart.sh: all lab2 services restarted with volumes preserved"
|
||||
@@ -0,0 +1,520 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level-5 track 2: query plan and recovery.
|
||||
|
||||
Experiment (contract: README.md "Оценка 5", track 2):
|
||||
* build >=100 000 messages in six chats of uneven size (60000, 25000,
|
||||
10000, 4000, 900, 100);
|
||||
* compare the production composite index (chat_id, created_at, id) with a
|
||||
naive chat_id-only index for the same keyset page, including
|
||||
EXPLAIN (ANALYZE, BUFFERS) and a write-cost microbenchmark;
|
||||
* take a PostgreSQL custom-format backup, restore it into a NEW PostgreSQL
|
||||
container with a NEW volume, and reconcile row counts, per-chat counts,
|
||||
an ordered checksum and one selected message;
|
||||
* record wall-clock timings, the source revision, image id, host limits and
|
||||
the raw plans in evidence/track5/.
|
||||
|
||||
The script is explicit and safe for the local teaching stand: the temporary
|
||||
restore container and volume are removed in `finally`; the main lab volumes are
|
||||
never touched. It is idempotent for a single stand because research chats are
|
||||
looked up by title+owner and only the missing message range is inserted.
|
||||
"""
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check # noqa: E402
|
||||
|
||||
POSTGRES = 'mtusi-lab2-melnikov-postgres'
|
||||
RESTORE = 'mtusi-lab2-melnikov-pgrestore'
|
||||
RESTORE_VOLUME = 'mtusi-lab2-melnikov-restoredata'
|
||||
NETWORK = 'mtusi-lab2-melnikov-net'
|
||||
POSTGRES_IMAGE = 'postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c'
|
||||
RESEARCH_PASSWORD = 'Track5-research-password-123'
|
||||
SIZES = [
|
||||
('track5 uneven 60000', 60000),
|
||||
('track5 uneven 25000', 25000),
|
||||
('track5 uneven 10000', 10000),
|
||||
('track5 uneven 4000', 4000),
|
||||
('track5 uneven 900', 900),
|
||||
('track5 uneven 100', 100),
|
||||
]
|
||||
|
||||
|
||||
def read_env():
|
||||
values = {}
|
||||
for line in (ROOT / '.env').read_text().splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
key, value = line.split('=', 1)
|
||||
values[key.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
ENV = read_env()
|
||||
|
||||
|
||||
def docker(*args, check_result=True):
|
||||
result = subprocess.run(['docker'] + list(args), capture_output=True, text=True)
|
||||
if check_result and result.returncode != 0:
|
||||
raise Failure('docker ' + ' '.join(args) + ' failed: ' + result.stderr.strip()[:400])
|
||||
return result
|
||||
|
||||
|
||||
def psql(sql, container=POSTGRES, allow_failure=False):
|
||||
result = subprocess.run(
|
||||
['docker', 'exec', '-i', container, 'psql', '-X', '-A', '-t', '-F', '|',
|
||||
'-v', 'ON_ERROR_STOP=1', '-U', ENV['POSTGRES_USER'], '-d', ENV['POSTGRES_DB']],
|
||||
input=sql, capture_output=True, text=True)
|
||||
if result.returncode != 0 and not allow_failure:
|
||||
raise Failure('psql failed: ' + result.stderr.strip()[:500])
|
||||
return result
|
||||
|
||||
|
||||
def query(sql, container=POSTGRES):
|
||||
return psql(sql, container).stdout.strip()
|
||||
|
||||
|
||||
def now_iso():
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def basic_header(username, password):
|
||||
import base64
|
||||
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def research_actor(client):
|
||||
"""Reuse the fixed research account, falling back to a random one if a
|
||||
previous run used a different password for the same username."""
|
||||
username = 'track5_owner'
|
||||
body = {'username': username, 'display_name': 'Track 5 research',
|
||||
'password': RESEARCH_PASSWORD}
|
||||
response = client.call('POST', '/api/v1/users', (201, 409), body=body)
|
||||
if response['status'] == 201:
|
||||
user = json.loads(response['bytes'])
|
||||
else:
|
||||
try:
|
||||
session = client.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': basic_header(username, RESEARCH_PASSWORD)},
|
||||
schema='Session')['json']
|
||||
return {'id': session['user']['id'], 'token': session['token'],
|
||||
'registration': body, 'user': session['user']}
|
||||
except Failure:
|
||||
username = 'track5_owner_' + os.urandom(5).hex()
|
||||
body = {'username': username, 'display_name': 'Track 5 research',
|
||||
'password': RESEARCH_PASSWORD}
|
||||
user = client.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
|
||||
session = client.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': basic_header(username, RESEARCH_PASSWORD)},
|
||||
schema='Session')['json']
|
||||
check(session['user']['id'] == user['id'], 'research login resolved to another user')
|
||||
return {'id': user['id'], 'token': session['token'], 'registration': body, 'user': user}
|
||||
|
||||
|
||||
def ensure_datasets(client):
|
||||
actor = research_actor(client)
|
||||
datasets = []
|
||||
for title, target in SIZES:
|
||||
existing = query("""
|
||||
SELECT c.id::text FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = '%s'::uuid
|
||||
WHERE c.title = '%s'
|
||||
ORDER BY c.created_at LIMIT 1;
|
||||
""" % (actor['id'], title))
|
||||
if existing:
|
||||
chat = {'id': existing, 'title': title}
|
||||
else:
|
||||
chat = client.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': title, 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
count = int(query("SELECT count(*) FROM messages WHERE chat_id='%s';" % chat['id']))
|
||||
if count < target:
|
||||
psql("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), '%s'::uuid, '%s'::uuid,
|
||||
'track5 %s row ' || g,
|
||||
timestamptz '2026-01-01 00:00:00+00' + (g || ' milliseconds')::interval
|
||||
FROM generate_series(%d, %d) AS g;
|
||||
""" % (chat['id'], actor['id'], target, count + 1, target))
|
||||
count = int(query("SELECT count(*) FROM messages WHERE chat_id='%s';" % chat['id']))
|
||||
check(count == target, '%s has %d messages, want %d' % (title, count, target))
|
||||
datasets.append({'title': title, 'chat_id': chat['id'], 'messages': count})
|
||||
psql('ANALYZE messages; ANALYZE chats; ANALYZE users; ANALYZE chat_members;')
|
||||
return actor, datasets
|
||||
|
||||
|
||||
def explain(sql):
|
||||
return query('EXPLAIN (ANALYZE, BUFFERS) ' + sql + ';')
|
||||
|
||||
|
||||
def index_scan_rows(plan, index_name):
|
||||
match = re.search(
|
||||
r'Index Scan using ' + re.escape(index_name) +
|
||||
r'.*?actual time=[\d.]+\.\.[\d.]+ rows=(\d+)', plan, re.S)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def execution_time(plan):
|
||||
match = re.search(r'Execution Time: ([\d.]+) ms', plan)
|
||||
return float(match.group(1)) if match else None
|
||||
|
||||
|
||||
def keyset_sql(chat_id, cursor_time, cursor_id, limit=50):
|
||||
return ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id='%s'::uuid AND (created_at, messages.id) > ('%s'::timestamptz, '%s'::uuid)
|
||||
ORDER BY created_at, messages.id LIMIT %d
|
||||
""" % (chat_id, cursor_time, cursor_id, limit))
|
||||
|
||||
|
||||
def measure_indexes(largest_chat, output_dir):
|
||||
count = largest_chat['messages']
|
||||
deep_offset = max(1000, count // 2)
|
||||
row = query("""
|
||||
SELECT created_at::text || '|' || id::text FROM messages
|
||||
WHERE chat_id='%s' ORDER BY created_at, messages.id OFFSET %d LIMIT 1;
|
||||
""" % (largest_chat['chat_id'], deep_offset)).split('|')
|
||||
cursor_time, cursor_id = row
|
||||
first_sql = ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE chat_id='%s'::uuid ORDER BY created_at, messages.id LIMIT 50
|
||||
""" % largest_chat['chat_id'])
|
||||
deep_sql = keyset_sql(largest_chat['chat_id'], cursor_time, cursor_id)
|
||||
offset_sql = ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE chat_id='%s'::uuid
|
||||
ORDER BY created_at, messages.id OFFSET %d LIMIT 50
|
||||
""" % (largest_chat['chat_id'], deep_offset))
|
||||
|
||||
started = time.monotonic()
|
||||
first_a = explain(first_sql)
|
||||
deep_a = explain(deep_sql)
|
||||
offset_a = explain(offset_sql)
|
||||
index_a_seconds = time.monotonic() - started
|
||||
check('Index Scan using messages_chat_created_id_idx' in first_a,
|
||||
'first page does not use the composite index:\n' + first_a)
|
||||
check('Index Scan using messages_chat_created_id_idx' in deep_a,
|
||||
'deep keyset page does not use the composite index:\n' + deep_a)
|
||||
a_rows = index_scan_rows(deep_a, 'messages_chat_created_id_idx')
|
||||
offset_rows = index_scan_rows(offset_a, 'messages_chat_created_id_idx')
|
||||
check(a_rows == 50, 'composite index deep page read %r rows, want 50' % (a_rows,))
|
||||
check(offset_rows is not None and offset_rows > deep_offset,
|
||||
'OFFSET plan did not scan a large prefix (%r)' % (offset_rows,))
|
||||
(output_dir / 'explain-composite-index.txt').write_text(
|
||||
'COMPOSITE INDEX (chat_id, created_at, id)\n\n'
|
||||
'=== first page ===\n%s\n\n=== deep keyset page, offset %d ===\n%s\n\n'
|
||||
'=== naive OFFSET %d ===\n%s\n' % (first_a, deep_offset, deep_a, deep_offset, offset_a))
|
||||
|
||||
# Swap indexes and repeat the same deep keyset query.
|
||||
psql("""
|
||||
DROP INDEX messages_chat_created_id_idx;
|
||||
CREATE INDEX messages_chat_only_idx ON messages (chat_id);
|
||||
ANALYZE messages;
|
||||
""")
|
||||
try:
|
||||
started = time.monotonic()
|
||||
deep_b = explain(deep_sql)
|
||||
index_b_seconds = time.monotonic() - started
|
||||
check('messages_chat_created_id_idx' not in deep_b, 'composite index still used after it was dropped')
|
||||
check(('messages_chat_only_idx' in deep_b) or ('Seq Scan on messages' in deep_b),
|
||||
'naive index comparison plan is unexpected:\n' + deep_b)
|
||||
finally:
|
||||
psql("""
|
||||
DROP INDEX IF EXISTS messages_chat_only_idx;
|
||||
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
ANALYZE messages;
|
||||
""")
|
||||
restored = explain(deep_sql)
|
||||
check('Index Scan using messages_chat_created_id_idx' in restored,
|
||||
'composite index was not restored:\n' + restored)
|
||||
(output_dir / 'explain-chat-only-index.txt').write_text(
|
||||
'NAIVE INDEX (chat_id) ONLY\n\n=== deep keyset page, offset %d ===\n%s\n' % (deep_offset, deep_b))
|
||||
|
||||
return {
|
||||
'largest_chat_id': largest_chat['chat_id'],
|
||||
'largest_chat_messages': count,
|
||||
'deep_offset': deep_offset,
|
||||
'cursor': {'created_at': cursor_time, 'id': cursor_id},
|
||||
'composite_index': {
|
||||
'deep_page_rows_read': a_rows,
|
||||
'offset_page_rows_read': offset_rows,
|
||||
'first_page_execution_ms': execution_time(first_a),
|
||||
'deep_page_execution_ms': execution_time(deep_a),
|
||||
'offset_page_execution_ms': execution_time(offset_a),
|
||||
'planning_and_execution_seconds_for_three_queries': round(index_a_seconds, 3),
|
||||
},
|
||||
'chat_only_index': {
|
||||
'deep_page_execution_ms': execution_time(deep_b),
|
||||
'plan_uses_chat_only_index': 'messages_chat_only_idx' in deep_b,
|
||||
'plan_uses_seq_scan': 'Seq Scan on messages' in deep_b,
|
||||
'plan_wall_seconds': round(index_b_seconds, 3),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def write_cost(output_dir):
|
||||
psql("""
|
||||
DROP TABLE IF EXISTS track5_write_composite;
|
||||
DROP TABLE IF EXISTS track5_write_chat_only;
|
||||
CREATE TABLE track5_write_composite (
|
||||
id uuid NOT NULL, chat_id uuid NOT NULL, created_at timestamptz NOT NULL, payload text NOT NULL);
|
||||
CREATE TABLE track5_write_chat_only (
|
||||
id uuid NOT NULL, chat_id uuid NOT NULL, created_at timestamptz NOT NULL, payload text NOT NULL);
|
||||
CREATE INDEX track5_write_composite_idx ON track5_write_composite (chat_id, created_at, id);
|
||||
CREATE INDEX track5_write_chat_only_idx ON track5_write_chat_only (chat_id);
|
||||
""")
|
||||
insert = """
|
||||
INSERT INTO %s (id, chat_id, created_at, payload)
|
||||
SELECT gen_random_uuid(), gen_random_uuid(),
|
||||
timestamptz '2026-03-01 00:00:00+00' + (g || ' milliseconds')::interval,
|
||||
'write cost row ' || g
|
||||
FROM generate_series(1, 20000) AS g
|
||||
"""
|
||||
measurements = {'rows_per_run': 20000, 'runs': 3, 'metric': 'PostgreSQL EXPLAIN ANALYZE Execution Time, ms'}
|
||||
try:
|
||||
for label, table in (('composite', 'track5_write_composite'), ('chat_only', 'track5_write_chat_only')):
|
||||
times = []
|
||||
for _ in range(3):
|
||||
psql('TRUNCATE %s;' % table)
|
||||
plan = query('EXPLAIN (ANALYZE, TIMING OFF, SUMMARY ON) ' + (insert % table) + ';')
|
||||
value = execution_time(plan)
|
||||
check(value is not None, 'no Execution Time in write-cost plan')
|
||||
times.append(value)
|
||||
measurements[label] = {'runs_ms': times, 'median_ms': round(sorted(times)[1], 3)}
|
||||
finally:
|
||||
psql('DROP TABLE IF EXISTS track5_write_composite; DROP TABLE IF EXISTS track5_write_chat_only;')
|
||||
(output_dir / 'write-cost.json').write_text(json.dumps(measurements, indent=2) + '\n')
|
||||
return measurements
|
||||
|
||||
|
||||
def wait_pg(container, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = docker('exec', container, 'pg_isready', '-U', ENV['POSTGRES_USER'],
|
||||
'-d', ENV['POSTGRES_DB'], check_result=False)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise Failure(container + ' did not become ready')
|
||||
|
||||
|
||||
def backup_and_restore(largest_chat, output_dir, artifacts_dir):
|
||||
"""pg_dump -> new container+volume -> pg_restore -> reconcile."""
|
||||
dump_in_container = '/tmp/lab2-track5.dump'
|
||||
dump_path = artifacts_dir / 'lab2-track5.dump'
|
||||
source_counts = query("""
|
||||
SELECT (SELECT count(*) FROM users) || '|' || (SELECT count(*) FROM chats) || '|' ||
|
||||
(SELECT count(*) FROM chat_members) || '|' || (SELECT count(*) FROM messages) || '|' ||
|
||||
(SELECT count(*) FROM schema_migrations);
|
||||
""")
|
||||
per_chat_before = query("""
|
||||
SELECT chat_id::text || '|' || count(*) FROM messages GROUP BY chat_id ORDER BY chat_id;
|
||||
""")
|
||||
checksum_sql = """
|
||||
SELECT md5(coalesce(string_agg(id::text || ':' || text || ':' || created_at::text,
|
||||
',' ORDER BY created_at, id), ''))
|
||||
FROM messages WHERE chat_id='%s';
|
||||
""" % largest_chat['chat_id']
|
||||
checksum_before = query(checksum_sql)
|
||||
selected = query("""
|
||||
SELECT id::text || '|' || chat_id::text || '|' || sender_id::text || '|' || text || '|' || created_at::text
|
||||
FROM messages WHERE chat_id='%s' ORDER BY created_at, messages.id OFFSET 30000 LIMIT 1;
|
||||
""" % largest_chat['chat_id']).split('|')
|
||||
check(len(selected) == 5, 'selected message query returned unexpected data')
|
||||
selected_id = selected[0]
|
||||
|
||||
started = time.monotonic()
|
||||
dump = docker('exec', POSTGRES, 'pg_dump', '-U', ENV['POSTGRES_USER'],
|
||||
'-d', ENV['POSTGRES_DB'], '-Fc', '-f', dump_in_container)
|
||||
dump_seconds = time.monotonic() - started
|
||||
copy = docker('cp', POSTGRES + ':' + dump_in_container, str(dump_path))
|
||||
dump_bytes = dump_path.stat().st_size
|
||||
dump_sha = hashlib.sha256(dump_path.read_bytes()).hexdigest()
|
||||
|
||||
# Any leftovers from an interrupted run are temporary restore resources;
|
||||
# the main lab volumes are never named here.
|
||||
docker('rm', '-f', RESTORE, check_result=False)
|
||||
docker('volume', 'rm', '-f', RESTORE_VOLUME, check_result=False)
|
||||
recovery_started = time.monotonic()
|
||||
docker('run', '-d', '--name', RESTORE, '--network', NETWORK,
|
||||
'-e', 'POSTGRES_USER=' + ENV['POSTGRES_USER'],
|
||||
'-e', 'POSTGRES_PASSWORD=' + ENV['POSTGRES_PASSWORD'],
|
||||
'-e', 'POSTGRES_DB=' + ENV['POSTGRES_DB'],
|
||||
'-v', RESTORE_VOLUME + ':/var/lib/postgresql/data',
|
||||
POSTGRES_IMAGE)
|
||||
try:
|
||||
wait_pg(RESTORE, timeout=90)
|
||||
docker('cp', str(dump_path), RESTORE + ':' + dump_in_container)
|
||||
restore_started = time.monotonic()
|
||||
restore = docker('exec', RESTORE, 'pg_restore', '-U', ENV['POSTGRES_USER'],
|
||||
'-d', ENV['POSTGRES_DB'], '--no-owner', '--no-privileges',
|
||||
'--clean', '--if-exists', dump_in_container)
|
||||
restore_seconds = time.monotonic() - restore_started
|
||||
total_recovery_seconds = time.monotonic() - recovery_started
|
||||
|
||||
restored_counts = query("""
|
||||
SELECT (SELECT count(*) FROM users) || '|' || (SELECT count(*) FROM chats) || '|' ||
|
||||
(SELECT count(*) FROM chat_members) || '|' || (SELECT count(*) FROM messages) || '|' ||
|
||||
(SELECT count(*) FROM schema_migrations);
|
||||
""", container=RESTORE)
|
||||
per_chat_after = query("""
|
||||
SELECT chat_id::text || '|' || count(*) FROM messages GROUP BY chat_id ORDER BY chat_id;
|
||||
""", container=RESTORE)
|
||||
checksum_after = query(checksum_sql, container=RESTORE)
|
||||
selected_after = query("""
|
||||
SELECT id::text || '|' || chat_id::text || '|' || sender_id::text || '|' || text || '|' || created_at::text
|
||||
FROM messages WHERE id='%s'::uuid;
|
||||
""" % selected_id, container=RESTORE).split('|')
|
||||
check(restored_counts == source_counts,
|
||||
'restored row counts differ: %r != %r' % (restored_counts, source_counts))
|
||||
check(per_chat_after == per_chat_before, 'restored per-chat counts differ')
|
||||
check(checksum_after == checksum_before, 'restored history checksum differs')
|
||||
check(selected_after == selected, 'selected message differs after restore')
|
||||
finally:
|
||||
docker('rm', '-f', RESTORE, check_result=False)
|
||||
docker('volume', 'rm', '-f', RESTORE_VOLUME, check_result=False)
|
||||
docker('exec', POSTGRES, 'rm', '-f', dump_in_container, check_result=False)
|
||||
dump_path.unlink(missing_ok=True)
|
||||
|
||||
result = {
|
||||
'source_counts_users_chats_members_messages_migrations': source_counts,
|
||||
'restored_counts': restored_counts,
|
||||
'counts_equal': source_counts == restored_counts,
|
||||
'per_chat_counts_equal': per_chat_after == per_chat_before,
|
||||
'history_checksum_md5': checksum_before,
|
||||
'checksum_equal': checksum_after == checksum_before,
|
||||
'selected_message_id': selected_id,
|
||||
'selected_message_equal': selected_after == selected,
|
||||
'dump_seconds': round(dump_seconds, 3),
|
||||
'dump_bytes': dump_bytes,
|
||||
'dump_sha256': dump_sha,
|
||||
'restore_seconds': round(restore_seconds, 3),
|
||||
'total_recovery_seconds_including_container_start': round(total_recovery_seconds, 3),
|
||||
'restore_target': {'container': RESTORE, 'volume': RESTORE_VOLUME, 'image': POSTGRES_IMAGE},
|
||||
'cleanup': 'restore container and volume removed in finally; dump file deleted',
|
||||
}
|
||||
(output_dir / 'backup-restore.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--output-dir', default='evidence/track5')
|
||||
parser.add_argument('--artifacts', default=None,
|
||||
help='directory for the raw dump; a temporary directory is used by default')
|
||||
|
||||
args = arguments('Level-5 track 2: indexes, write cost, backup/restore', configure)
|
||||
output_dir = ROOT / args.output_dir
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
artifacts = Path(args.artifacts) if args.artifacts else Path(tempfile.mkdtemp(prefix='mtusi-lab2-track5-'))
|
||||
artifacts.mkdir(parents=True, exist_ok=True)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
started_at = now_iso()
|
||||
started = time.monotonic()
|
||||
seed_started_at = now_iso()
|
||||
actor, datasets = ensure_datasets(c)
|
||||
seed_seconds = time.monotonic() - started
|
||||
seed_finished_at = now_iso()
|
||||
total_messages = int(query('SELECT count(*) FROM messages;'))
|
||||
check(total_messages >= 100000, 'research dataset has only %d messages' % total_messages)
|
||||
|
||||
largest = max(datasets, key=lambda item: item['messages'])
|
||||
phase_started = time.monotonic()
|
||||
index_started_at = now_iso()
|
||||
indexes = measure_indexes(largest, output_dir)
|
||||
indexes['interval'] = {'started_at': index_started_at, 'finished_at': now_iso(),
|
||||
'seconds': round(time.monotonic() - phase_started, 3)}
|
||||
|
||||
phase_started = time.monotonic()
|
||||
write_started_at = now_iso()
|
||||
writes = write_cost(output_dir)
|
||||
writes['interval'] = {'started_at': write_started_at, 'finished_at': now_iso(),
|
||||
'seconds': round(time.monotonic() - phase_started, 3)}
|
||||
|
||||
phase_started = time.monotonic()
|
||||
backup_started_at = now_iso()
|
||||
backup = backup_and_restore(largest, output_dir, artifacts)
|
||||
backup['interval'] = {'started_at': backup_started_at, 'finished_at': now_iso(),
|
||||
'seconds': round(time.monotonic() - phase_started, 3)}
|
||||
|
||||
info = json.loads(subprocess.run(['docker', 'info', '--format', '{{json .}}'],
|
||||
capture_output=True, text=True, check=True).stdout)
|
||||
image = json.loads(subprocess.run(['docker', 'inspect', 'mtusi-messenger-lab2-melnikov:1.0.0'],
|
||||
capture_output=True, text=True, check=True).stdout)[0]
|
||||
revision = subprocess.run(['git', '-C', str(ROOT), 'rev-parse', 'HEAD'],
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
status = subprocess.run(['git', '-C', str(ROOT), 'status', '--porcelain'],
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
|
||||
summary = {
|
||||
'track': 'track 2: query plan and recovery',
|
||||
'started_at': started_at,
|
||||
'finished_at': now_iso(),
|
||||
'duration_seconds': round(time.monotonic() - started, 3),
|
||||
'code_revision': revision,
|
||||
'git_status': status,
|
||||
'image': {'reference': 'mtusi-messenger-lab2-melnikov:1.0.0', 'id': image['Id'],
|
||||
'created': image['Created']},
|
||||
'postgres_image': POSTGRES_IMAGE,
|
||||
'host': {'docker_server_version': info.get('ServerVersion'),
|
||||
'cpus': info.get('NCPU'), 'memory_bytes': info.get('MemTotal'),
|
||||
'architecture': info.get('Architecture')},
|
||||
'declared_limits': {'api': '1 CPU / 256 MiB', 'postgres': '1 CPU / 512 MiB',
|
||||
'valkey': '1 CPU / 256 MiB'},
|
||||
'dataset': {'chat_sizes': SIZES, 'per_chat': datasets, 'total_messages': total_messages,
|
||||
'seed_and_verify_seconds': round(seed_seconds, 3),
|
||||
'seed_interval': {'started_at': seed_started_at, 'finished_at': seed_finished_at},
|
||||
'sample_timestamps': 'research chats sorted by (created_at,id), one-millisecond steps '
|
||||
'from 2026-01-01T00:00:00Z per chat'},
|
||||
'indexes': indexes,
|
||||
'write_cost': writes,
|
||||
'backup_restore': backup,
|
||||
'artifacts_dir_removed_after_run': str(artifacts) if args.artifacts else 'temporary directory',
|
||||
'measurement_notes': [
|
||||
'EXPLAIN elapsed values are PostgreSQL Execution Time on the local container; wall times include psql/docker exec overhead.',
|
||||
'deep page cursor is a real (created_at, id) row at the recorded OFFSET; the OFFSET comparison scans the same prefix.',
|
||||
'write cost measures INSERT plus index maintenance for 20 000 synthetic rows, 3 runs per index, median reported.',
|
||||
'backup is a single pg_dump custom-format snapshot; no WAL archiving, so RPO is the age of the last dump.',
|
||||
'restore target is a new PostgreSQL container with a new named volume, removed after reconciliation.',
|
||||
],
|
||||
}
|
||||
(output_dir / 'summary.json').write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n')
|
||||
|
||||
if not args.artifacts:
|
||||
shutil.rmtree(artifacts, ignore_errors=True)
|
||||
print(json.dumps({
|
||||
'total_messages': total_messages,
|
||||
'largest_chat_messages': largest['messages'],
|
||||
'composite_deep_rows': indexes['composite_index']['deep_page_rows_read'],
|
||||
'offset_rows': indexes['composite_index']['offset_page_rows_read'],
|
||||
'write_median_ms': {'composite': writes['composite']['median_ms'],
|
||||
'chat_only': writes['chat_only']['median_ms']},
|
||||
'dump_seconds': backup['dump_seconds'],
|
||||
'dump_bytes': backup['dump_bytes'],
|
||||
'restore_seconds': backup['restore_seconds'],
|
||||
'total_recovery_seconds': backup['total_recovery_seconds_including_container_start'],
|
||||
'counts_equal': backup['source_counts_users_chats_members_messages_migrations'] == backup['restored_counts'],
|
||||
'checksum_equal': backup['checksum_equal'],
|
||||
}, ensure_ascii=False, sort_keys=True))
|
||||
print('PASS: track 2 completed; summary in evidence/track5/summary.json')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# Wait until /health/ready answers 200. Usage: scripts/wait-ready.sh [url]
|
||||
set -eu
|
||||
url=${1:-http://127.0.0.1:8080/health/ready}
|
||||
attempts=0
|
||||
while [ "$attempts" -lt 90 ]; do
|
||||
if curl -fsS -o /dev/null "$url" 2>/dev/null; then
|
||||
echo "ready: $url"
|
||||
exit 0
|
||||
fi
|
||||
attempts=$((attempts + 1))
|
||||
sleep 1
|
||||
done
|
||||
echo "not ready after 90 seconds: $url" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,48 @@
|
||||
# Собственные тесты лабораторной 2
|
||||
|
||||
Публичные `tests/` не изменялись и не ослаблялись. Свои проверки дополняют
|
||||
публичный smoke и лежат в штатной структуре Go и в `student-tests/`.
|
||||
|
||||
## Команды
|
||||
|
||||
```sh
|
||||
make test-student # go test ./... + чёрный ящик против запущенного стенда
|
||||
make test-student-race # go test -race ./...
|
||||
python3 student-tests/blackbox.py --base-url http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
Go-тесты не требуют запущенного сервера и БД: они проверяют строгий разбор
|
||||
JSON, границы Unicode, Argon2id, Basic/Bearer-разбор, курсоры, конфигурацию и
|
||||
контрактные ошибки. Чёрный ящик требует `make up` и создаёт только синтетические
|
||||
данные.
|
||||
|
||||
## Что и где проверяется
|
||||
|
||||
| Требование контракта/рубрики | Проверка |
|
||||
| --- | --- |
|
||||
| Точные JSON-ключи, лишние поля, алиасы регистра, дубликаты, неверные типы, malformed JSON | `TestDecodeJSONRejectsContractViolations`, `test_registration_validation` |
|
||||
| `400` для UUID, limit, cursor; `limit` 1–100 и смена limit при продолжении | `TestPageParams`, `test_pagination` |
|
||||
| `username` `[a-z0-9_]{3,32}`, уникальность; `display_name` 1–100 code points | `TestUsernameValidation`, `TestLengthValidationCountsCodePoints`, blackbox |
|
||||
| E-mail/пароль: 12–128 code points, Unicode, двоеточие в пароле | `test_registration_and_login`, `TestHashUnicodeAndMaximumLength` |
|
||||
| Пароль и его hash никогда не в ответах; Argon2id PHC | `TestUserJSONHasOnlyPublicFields`, blackbox, `db-checks.py` |
|
||||
| Basic только на login; Bearer на бизнес-endpoint; `X-User-Id` игнорируется | `test_registration_and_login`, `TestBearerTokenParsing` |
|
||||
| Одинаковый 401 на неверный пароль/неизвестного пользователя, Basic challenge | `test_registration_and_login`, `TestParseBasic` |
|
||||
| Членство: чужой чат 404 на GET/историю/запись, не попадает в список | `test_chats`, `test_messages` |
|
||||
| `sender_id` выводится из сессии, а не из body | `test_messages` |
|
||||
| Текст 1–4000 code points, пустой/пробельный отклоняется, Unicode round-trip | `test_messages`, `TestLengthValidationCountsCodePoints` |
|
||||
| Keyset-пагинация `(created_at,id)`, отсутствие повторов/потерь, cursor другого чата 400 | `test_pagination` |
|
||||
| Конкурентная регистрация одного username: ровно один 201, остальные 409 | `test_concurrent_registration`, `db-checks.py` |
|
||||
| Конкурентные записи: 24 сообщения, уникальные id, порядок истории | `test_concurrent_messages` |
|
||||
| Logout: 204 без тела, повторный запрос 401, вторая сессия жива | `test_logout` |
|
||||
| Строгие ответы, `X-Request-Id` и совпадение с `error.request_id` | все вызовы через `tests/client.py` |
|
||||
| Истечение TTL, сохранение сессии при рестарте API | `make test-expiry` |
|
||||
| Недоступность Valkey/PostgreSQL: ограниченный 503, анонимный остаётся 401, данные и сессия после восстановления | `make test-failure` |
|
||||
| Ограничения/FK/уникальность/миграции/rollback/EXPLAIN ≥10 000 | `make test-db` |
|
||||
| Реальные контейнеры, volumes, non-root, graceful shutdown, отсутствие секретов в логах/Git | `make test-container` |
|
||||
| Трек 5 (план запроса и восстановление) | `make track5` |
|
||||
|
||||
## Что намеренно не доказывают Go-тесты
|
||||
|
||||
Docker-стенд, PostgreSQL, Valkey, миграции, гонки на реальной БД и нагрузка
|
||||
проверяются отдельными скриптами из таблицы. Публичный контракт целиком
|
||||
проверяет `make test`.
|
||||
@@ -0,0 +1,398 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Own black-box tests for lab2. They complement, and never weaken, tests/smoke.py.
|
||||
|
||||
The suite assumes a running stack (make up) and creates only synthetic data.
|
||||
It checks the contract expectations derived from contracts/openapi.json and
|
||||
contracts/README.md: exact JSON keys, strict input validation, Bearer-only
|
||||
business API, membership hiding as 404, keyset pagination, concurrent username
|
||||
registration and concurrent message writes.
|
||||
|
||||
Python 3.9+, standard library only.
|
||||
"""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import datetime as dt
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, arguments, check, timestamp # noqa: E402
|
||||
|
||||
CHECKS = 0
|
||||
|
||||
|
||||
def ok(condition, message):
|
||||
global CHECKS
|
||||
CHECKS += 1
|
||||
check(condition, message)
|
||||
|
||||
|
||||
def expect_keys(payload, expected, where):
|
||||
ok(set(payload) == set(expected), where + ': JSON keys differ: ' + repr(sorted(payload)))
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def register(c, username=None, display_name=None, password=None):
|
||||
username = username or 'bb_' + uuid.uuid4().hex[:12]
|
||||
password = password or 'B3st-' + uuid.uuid4().hex
|
||||
display_name = display_name or 'Тестовый пользователь'
|
||||
body = {'username': username, 'display_name': display_name, 'password': password}
|
||||
user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
|
||||
expect_keys(user, {'id', 'username', 'display_name', 'created_at'}, 'User')
|
||||
return {'id': user['id'], 'user': user, 'registration': body, 'password': password}
|
||||
|
||||
|
||||
def login(c, actor):
|
||||
response = c.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': basic(actor['registration']['username'], actor['password'])},
|
||||
schema='Session')['json']
|
||||
expect_keys(response, {'token', 'token_type', 'expires_at', 'user'}, 'Session')
|
||||
actor['token'] = response['token']
|
||||
actor['session'] = response
|
||||
return actor
|
||||
|
||||
|
||||
def new_chat(c, actor, title, member_ids):
|
||||
return c.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': title, 'member_ids': member_ids}, schema='Chat')['json']
|
||||
|
||||
|
||||
def send(c, actor, chat, text, headers=None):
|
||||
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
||||
body={'text': text}, headers=headers, schema='Message')['json']
|
||||
|
||||
|
||||
def all_messages(c, actor, chat, limit=100):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit)
|
||||
items, seen = [], set()
|
||||
for _ in range(1000):
|
||||
page = c.call('GET', path, actor=actor, schema='MessagePage')['json']
|
||||
items.extend(page['items'])
|
||||
if page['next_cursor'] is None:
|
||||
return items
|
||||
ok(page['next_cursor'] not in seen, 'message cursor cycle')
|
||||
seen.add(page['next_cursor'])
|
||||
from urllib.parse import quote
|
||||
path = ('/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit) +
|
||||
'&cursor=' + quote(page['next_cursor'], safe=''))
|
||||
raise AssertionError('message pagination exceeded safety bound')
|
||||
|
||||
|
||||
def sorted_messages(items):
|
||||
return sorted(items, key=lambda x: (timestamp(x['created_at']), uuid.UUID(x['id']).int))
|
||||
|
||||
|
||||
def test_health(c):
|
||||
live = c.call('GET', '/health/live', schema='Health')
|
||||
ok(live['json'] == {'status': 'ok'}, 'liveness body')
|
||||
ok(bool(live['headers'].get('X-Request-Id')), 'liveness X-Request-Id')
|
||||
ok(bool(live['headers'].get('X-Instance-Id')), 'liveness X-Instance-Id')
|
||||
ready = c.call('GET', '/health/ready', schema='Health')
|
||||
ok(ready['json'] == {'status': 'ok'}, 'readiness body')
|
||||
print('PASS health')
|
||||
|
||||
|
||||
def test_registration_and_login(c):
|
||||
alice = register(c)
|
||||
bob = register(c)
|
||||
login(c, alice)
|
||||
login(c, bob)
|
||||
|
||||
ok(len(alice['session']['token']) >= 32, 'session token shorter than contract minimum')
|
||||
ok(alice['session']['token_type'] == 'Bearer', 'token_type')
|
||||
ok(timestamp(alice['session']['expires_at']) > dt.datetime.now(dt.timezone.utc), 'expiry in the past')
|
||||
ok(alice['session']['user'] == alice['user'], 'session user differs from created user')
|
||||
|
||||
# Duplicate username, including a different display name/password.
|
||||
c.call('POST', '/api/v1/users', 409, body={
|
||||
'username': alice['registration']['username'],
|
||||
'display_name': 'Другой',
|
||||
'password': 'Another-password-123',
|
||||
})
|
||||
|
||||
# Wrong / unknown / malformed credentials all give the same Basic 401.
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic(alice['registration']['username'], 'wrong-password-123')})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic('definitely_unknown', 'wrong-password-123')})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic !!!!'})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + base64.b64encode(b'no-colon').decode()})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz'})
|
||||
|
||||
# Basic is not accepted on business endpoints; X-User-Id grants nothing.
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': basic(alice['registration']['username'], alice['password'])})
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer ' + 'a' * 43})
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'X-User-Id ' + alice['id']})
|
||||
|
||||
me = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')['json']
|
||||
ok(me['id'] == alice['id'], 'X-User-Id overrode the bearer identity')
|
||||
|
||||
# A UTF-8 password containing colons is valid and is not truncated at the
|
||||
# first colon by Basic parsing.
|
||||
unicode_password = 'pässwörd:with:12'
|
||||
unicode_user = register(c, password=unicode_password)
|
||||
login(c, unicode_user)
|
||||
ok(unicode_user['session']['user']['username'] == unicode_user['registration']['username'], 'unicode password login')
|
||||
|
||||
# Session JSON must never contain the password or its hash.
|
||||
serialized = json.dumps(alice['session'], ensure_ascii=False)
|
||||
for forbidden in ('password', 'argon2', 'salt'):
|
||||
ok(forbidden not in serialized, 'session leaks ' + forbidden)
|
||||
print('PASS registration/auth')
|
||||
|
||||
|
||||
def test_registration_validation(c):
|
||||
username = 'bb_' + uuid.uuid4().hex[:10]
|
||||
password = 'B3st-' + uuid.uuid4().hex
|
||||
valid = {'username': username, 'display_name': 'Имя', 'password': password}
|
||||
|
||||
def bad(body, status=400, raw=None, headers=None):
|
||||
c.call('POST', '/api/v1/users', status, body=body if raw is None else None, raw=raw,
|
||||
headers=headers)
|
||||
|
||||
bad({'username': username, 'display_name': 'Имя'})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': 'short'})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': 'p' * 129})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': ' ' * 12})
|
||||
bad({'username': 'ab', 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': 'a' * 33, 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': 'UPPER', 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': 'bad-name', 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': 'бвт', 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': username, 'display_name': '', 'password': password})
|
||||
bad({'username': username, 'display_name': ' ', 'password': password})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': password, 'extra': 1})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': password, 'Password': 'x'})
|
||||
bad({'Username': username, 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': 123456789012})
|
||||
bad({'username': None, 'display_name': 'Имя', 'password': password})
|
||||
bad({}, raw=b'{', headers={'Content-Type': 'application/json'})
|
||||
bad({}, raw=b'[]', headers={'Content-Type': 'application/json'})
|
||||
bad({}, status=415, raw=json.dumps(valid).encode(), headers={'Content-Type': 'text/plain'})
|
||||
bad({}, raw=(json.dumps(valid)[:-1] + ', "username": "x"}').encode(), headers={'Content-Type': 'application/json'})
|
||||
|
||||
# Exact code-point boundaries.
|
||||
long_name = register(c, display_name='😀' * 100)
|
||||
ok(long_name['user']['display_name'] == '😀' * 100, '100 code points display_name changed')
|
||||
c.call('POST', '/api/v1/users', 400, body={
|
||||
'username': 'bb_' + uuid.uuid4().hex[:10],
|
||||
'display_name': '😀' * 101,
|
||||
'password': password,
|
||||
})
|
||||
c.call('POST', '/api/v1/users', 400, body={
|
||||
'username': 'a' * 32 + 'b',
|
||||
'display_name': 'Имя', 'password': password,
|
||||
})
|
||||
register(c, username='a' * 24 + uuid.uuid4().hex[:8])
|
||||
print('PASS registration validation')
|
||||
|
||||
|
||||
def test_chats(c, alice, bob, eve):
|
||||
chat = new_chat(c, alice, 'Комната с Unicode 🚀', [alice['id'], bob['id']])
|
||||
ok(set(chat['member_ids']) == {alice['id'], bob['id']}, 'chat member set')
|
||||
expect_keys(chat, {'id', 'title', 'member_ids', 'created_at'}, 'Chat')
|
||||
|
||||
def bad(body, status=400):
|
||||
c.call('POST', '/api/v1/chats', status, actor=alice, body=body)
|
||||
|
||||
bad({'title': 'Без автора', 'member_ids': [bob['id']]})
|
||||
bad({'title': 'Дубликат', 'member_ids': [alice['id'], alice['id']]})
|
||||
bad({'title': 'Неизвестный', 'member_ids': [alice['id'], str(uuid.uuid4())]})
|
||||
bad({'title': 'Не UUID', 'member_ids': [alice['id'], 'not-a-uuid']})
|
||||
bad({'title': 'Слишком много', 'member_ids': [alice['id']] + [str(uuid.uuid4()) for _ in range(100)]})
|
||||
bad({'title': '', 'member_ids': [alice['id']]})
|
||||
bad({'title': ' ', 'member_ids': [alice['id']]})
|
||||
bad({'title': 'я' * 101, 'member_ids': [alice['id']]})
|
||||
bad({'title': 'Лишнее', 'member_ids': [alice['id']], 'extra': True})
|
||||
bad({'title': 'Нет списка'})
|
||||
|
||||
own = c.call('GET', '/api/v1/chats/' + chat['id'], actor=bob, schema='Chat')['json']
|
||||
ok(own['id'] == chat['id'], 'member cannot read chat')
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'], 404, actor=eve)
|
||||
c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve, body={'text': 'чужое'})
|
||||
|
||||
hidden = c.call('GET', '/api/v1/chats?limit=100', actor=eve, schema='ChatPage')['json']
|
||||
ok(all(item['id'] != chat['id'] for item in hidden['items']), 'foreign chat leaked into list')
|
||||
listed = c.call('GET', '/api/v1/chats?limit=100', actor=bob, schema='ChatPage')['json']
|
||||
ok(any(item['id'] == chat['id'] for item in listed['items']), 'member chat missing from list')
|
||||
print('PASS chats/membership')
|
||||
|
||||
|
||||
def test_messages(c, alice, bob, eve, chat):
|
||||
text = 'Привет 👋 e\u0301 中文'
|
||||
message = send(c, alice, chat, text)
|
||||
expect_keys(message, {'id', 'chat_id', 'sender_id', 'text', 'created_at'}, 'Message')
|
||||
ok(message['text'] == text, 'message text changed')
|
||||
ok(message['sender_id'] == alice['id'] and message['chat_id'] == chat['id'], 'message identity')
|
||||
|
||||
# X-User-Id cannot substitute for the Bearer owner.
|
||||
spoofed = send(c, alice, chat, 'не от Боба', headers={'X-User-Id': bob['id']})
|
||||
ok(spoofed['sender_id'] == alice['id'], 'X-User-Id changed the message sender')
|
||||
|
||||
def bad(actor, body, status=400, raw=None):
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=actor, body=body, raw=raw)
|
||||
|
||||
bad(alice, {'text': ''})
|
||||
bad(alice, {'text': ' '})
|
||||
bad(alice, {'text': None})
|
||||
bad(alice, {})
|
||||
bad(alice, {'text': 'x' * 4001})
|
||||
bad(alice, {'text': 'ok', 'sender_id': alice['id']})
|
||||
bad(alice, {'text': 'ok', 'attachment_ids': []})
|
||||
bad(alice, {'Text': 'ok'})
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
raw=b'{', headers={'Content-Type': 'application/json'})
|
||||
# Resource access is checked before body parsing: a foreign chat with a
|
||||
# malformed body still looks like a missing chat.
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
|
||||
raw=b'{', headers={'Content-Type': 'application/json'})
|
||||
|
||||
boundary = send(c, alice, chat, 'я' * 4000)
|
||||
ok(len(boundary['text']) == 4000, '4000 code point message changed')
|
||||
|
||||
history = all_messages(c, bob, chat)
|
||||
ok(any(item == boundary for item in history), 'member cannot read message history')
|
||||
print('PASS messages')
|
||||
|
||||
|
||||
def test_pagination(c, alice, bob):
|
||||
chat = new_chat(c, alice, 'Пагинация', [alice['id'], bob['id']])
|
||||
for index in range(23):
|
||||
send(c, alice if index % 2 == 0 else bob, chat, 'строка %02d' % index)
|
||||
|
||||
expected = sorted_messages(all_messages(c, alice, chat, limit=100))
|
||||
collected = []
|
||||
cursor = None
|
||||
limits = [7, 5, 100, 1, 3, 9]
|
||||
step = 0
|
||||
while True:
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limits[step % len(limits)])
|
||||
if cursor:
|
||||
from urllib.parse import quote
|
||||
path += '&cursor=' + quote(cursor, safe='')
|
||||
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
|
||||
collected.extend(page['items'])
|
||||
step += 1
|
||||
if page['next_cursor'] is None:
|
||||
break
|
||||
cursor = page['next_cursor']
|
||||
ok(step < 100, 'pagination did not finish')
|
||||
ok(collected == expected, 'pagination lost, duplicated or reordered messages')
|
||||
ids = [item['id'] for item in collected]
|
||||
ok(len(ids) == len(set(ids)), 'pagination repeated an id')
|
||||
|
||||
first = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=3', actor=alice, schema='MessagePage')['json']
|
||||
ok(first['next_cursor'] is not None, 'first page cursor missing')
|
||||
other = new_chat(c, alice, 'Другой чат', [alice['id']])
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + first['next_cursor'], 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=not-base64!!', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=0', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=101', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=abc', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1&limit=2', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=', 400, actor=alice)
|
||||
|
||||
# A message cursor is scoped to a chat and cannot continue the chat list.
|
||||
c.call('GET', '/api/v1/chats?cursor=' + first['next_cursor'], 400, actor=alice)
|
||||
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
|
||||
ok(any(item['id'] == chat['id'] for item in listed['items']), 'paginated chat missing from list')
|
||||
ok(any(item['id'] == other['id'] for item in listed['items']), 'other chat missing from list')
|
||||
print('PASS pagination')
|
||||
|
||||
|
||||
def test_concurrent_registration(c):
|
||||
username = 'race_' + uuid.uuid4().hex[:10]
|
||||
body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-123'}
|
||||
|
||||
def attempt(_):
|
||||
local = Client(c.base)
|
||||
try:
|
||||
return local.call('POST', '/api/v1/users', (201, 409), body=body)['status']
|
||||
except Exception as exc: # failures are assertions for this test
|
||||
return 'error:' + type(exc).__name__
|
||||
|
||||
barrier = threading.Barrier(8)
|
||||
|
||||
def synchronized_attempt(index):
|
||||
barrier.wait()
|
||||
return attempt(index)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
statuses = list(pool.map(synchronized_attempt, range(8)))
|
||||
ok(statuses.count(201) == 1, 'concurrent registration: expected exactly one 201, got ' + repr(statuses))
|
||||
ok(statuses.count(409) == 7, 'concurrent registration: expected seven 409, got ' + repr(statuses))
|
||||
c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': basic(username, 'Race-password-123')}, schema='Session')
|
||||
print('PASS concurrent registration')
|
||||
|
||||
|
||||
def test_concurrent_messages(c, alice, bob):
|
||||
chat = new_chat(c, alice, 'Конкурентная запись', [alice['id'], bob['id']])
|
||||
|
||||
def worker(index):
|
||||
local = Client(c.base)
|
||||
actor = alice if index % 2 == 0 else bob
|
||||
return local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
||||
body={'text': 'concurrent %02d' % index}, schema='Message')['json']
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
|
||||
messages = list(pool.map(worker, range(24)))
|
||||
ids = [message['id'] for message in messages]
|
||||
ok(len(ids) == 24 and len(set(ids)) == 24, 'concurrent messages produced duplicate ids')
|
||||
for index, message in enumerate(messages):
|
||||
ok(message['sender_id'] == (alice['id'] if index % 2 == 0 else bob['id']), 'concurrent sender mismatch')
|
||||
history = all_messages(c, alice, chat)
|
||||
ok(len(history) == 24, 'concurrent history has %d rows, want 24' % len(history))
|
||||
ok(sorted_messages(history) == history, 'concurrent history is not ordered by (created_at, id)')
|
||||
ok([item['text'] for item in history].count('concurrent 00') == 1, 'concurrent duplicate text')
|
||||
print('PASS concurrent messages')
|
||||
|
||||
|
||||
def test_logout(c, alice):
|
||||
second = login(c, {'id': alice['id'], 'user': alice['user'],
|
||||
'registration': alice['registration'], 'password': alice['password']})
|
||||
first_token = alice['token']
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor={'token': first_token})
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor={'token': first_token})
|
||||
me = c.call('GET', '/api/v1/users/me', actor=second, schema='User')['json']
|
||||
ok(me['id'] == alice['id'], 'logout revoked another session of the same user')
|
||||
alice['token'] = second['token']
|
||||
print('PASS logout')
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab2 own black-box suite; creates synthetic data')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
test_health(c)
|
||||
alice = register(c)
|
||||
bob = register(c)
|
||||
eve = register(c)
|
||||
login(c, alice)
|
||||
login(c, bob)
|
||||
login(c, eve)
|
||||
test_registration_and_login(c)
|
||||
test_registration_validation(c)
|
||||
test_chats(c, alice, bob, eve)
|
||||
chat = new_chat(c, alice, 'Основной чат blackbox', [alice['id'], bob['id']])
|
||||
test_messages(c, alice, bob, eve, chat)
|
||||
test_pagination(c, alice, bob)
|
||||
test_concurrent_registration(c)
|
||||
test_concurrent_messages(c, alice, bob)
|
||||
test_logout(c, alice)
|
||||
print('PASS: lab2 student black-box suite, %d checks' % CHECKS)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2016 Caleb Spare
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
# xxhash
|
||||
|
||||
[](https://pkg.go.dev/github.com/cespare/xxhash/v2)
|
||||
[](https://github.com/cespare/xxhash/actions/workflows/test.yml)
|
||||
|
||||
xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a
|
||||
high-quality hashing algorithm that is much faster than anything in the Go
|
||||
standard library.
|
||||
|
||||
This package provides a straightforward API:
|
||||
|
||||
```
|
||||
func Sum64(b []byte) uint64
|
||||
func Sum64String(s string) uint64
|
||||
type Digest struct{ ... }
|
||||
func New() *Digest
|
||||
```
|
||||
|
||||
The `Digest` type implements hash.Hash64. Its key methods are:
|
||||
|
||||
```
|
||||
func (*Digest) Write([]byte) (int, error)
|
||||
func (*Digest) WriteString(string) (int, error)
|
||||
func (*Digest) Sum64() uint64
|
||||
```
|
||||
|
||||
The package is written with optimized pure Go and also contains even faster
|
||||
assembly implementations for amd64 and arm64. If desired, the `purego` build tag
|
||||
opts into using the Go code even on those architectures.
|
||||
|
||||
[xxHash]: http://cyan4973.github.io/xxHash/
|
||||
|
||||
## Compatibility
|
||||
|
||||
This package is in a module and the latest code is in version 2 of the module.
|
||||
You need a version of Go with at least "minimal module compatibility" to use
|
||||
github.com/cespare/xxhash/v2:
|
||||
|
||||
* 1.9.7+ for Go 1.9
|
||||
* 1.10.3+ for Go 1.10
|
||||
* Go 1.11 or later
|
||||
|
||||
I recommend using the latest release of Go.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Here are some quick benchmarks comparing the pure-Go and assembly
|
||||
implementations of Sum64.
|
||||
|
||||
| input size | purego | asm |
|
||||
| ---------- | --------- | --------- |
|
||||
| 4 B | 1.3 GB/s | 1.2 GB/s |
|
||||
| 16 B | 2.9 GB/s | 3.5 GB/s |
|
||||
| 100 B | 6.9 GB/s | 8.1 GB/s |
|
||||
| 4 KB | 11.7 GB/s | 16.7 GB/s |
|
||||
| 10 MB | 12.0 GB/s | 17.3 GB/s |
|
||||
|
||||
These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C
|
||||
CPU using the following commands under Go 1.19.2:
|
||||
|
||||
```
|
||||
benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$')
|
||||
benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$')
|
||||
```
|
||||
|
||||
## Projects using this package
|
||||
|
||||
- [InfluxDB](https://github.com/influxdata/influxdb)
|
||||
- [Prometheus](https://github.com/prometheus/prometheus)
|
||||
- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics)
|
||||
- [FreeCache](https://github.com/coocood/freecache)
|
||||
- [FastCache](https://github.com/VictoriaMetrics/fastcache)
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
set -eu -o pipefail
|
||||
|
||||
# Small convenience script for running the tests with various combinations of
|
||||
# arch/tags. This assumes we're running on amd64 and have qemu available.
|
||||
|
||||
go test ./...
|
||||
go test -tags purego ./...
|
||||
GOARCH=arm64 go test
|
||||
GOARCH=arm64 go test -tags purego
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described
|
||||
// at http://cyan4973.github.io/xxHash/.
|
||||
package xxhash
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math/bits"
|
||||
)
|
||||
|
||||
const (
|
||||
prime1 uint64 = 11400714785074694791
|
||||
prime2 uint64 = 14029467366897019727
|
||||
prime3 uint64 = 1609587929392839161
|
||||
prime4 uint64 = 9650029242287828579
|
||||
prime5 uint64 = 2870177450012600261
|
||||
)
|
||||
|
||||
// Store the primes in an array as well.
|
||||
//
|
||||
// The consts are used when possible in Go code to avoid MOVs but we need a
|
||||
// contiguous array of the assembly code.
|
||||
var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5}
|
||||
|
||||
// Digest implements hash.Hash64.
|
||||
type Digest struct {
|
||||
v1 uint64
|
||||
v2 uint64
|
||||
v3 uint64
|
||||
v4 uint64
|
||||
total uint64
|
||||
mem [32]byte
|
||||
n int // how much of mem is used
|
||||
}
|
||||
|
||||
// New creates a new Digest that computes the 64-bit xxHash algorithm.
|
||||
func New() *Digest {
|
||||
var d Digest
|
||||
d.Reset()
|
||||
return &d
|
||||
}
|
||||
|
||||
// Reset clears the Digest's state so that it can be reused.
|
||||
func (d *Digest) Reset() {
|
||||
d.v1 = primes[0] + prime2
|
||||
d.v2 = prime2
|
||||
d.v3 = 0
|
||||
d.v4 = -primes[0]
|
||||
d.total = 0
|
||||
d.n = 0
|
||||
}
|
||||
|
||||
// Size always returns 8 bytes.
|
||||
func (d *Digest) Size() int { return 8 }
|
||||
|
||||
// BlockSize always returns 32 bytes.
|
||||
func (d *Digest) BlockSize() int { return 32 }
|
||||
|
||||
// Write adds more data to d. It always returns len(b), nil.
|
||||
func (d *Digest) Write(b []byte) (n int, err error) {
|
||||
n = len(b)
|
||||
d.total += uint64(n)
|
||||
|
||||
memleft := d.mem[d.n&(len(d.mem)-1):]
|
||||
|
||||
if d.n+n < 32 {
|
||||
// This new data doesn't even fill the current block.
|
||||
copy(memleft, b)
|
||||
d.n += n
|
||||
return
|
||||
}
|
||||
|
||||
if d.n > 0 {
|
||||
// Finish off the partial block.
|
||||
c := copy(memleft, b)
|
||||
d.v1 = round(d.v1, u64(d.mem[0:8]))
|
||||
d.v2 = round(d.v2, u64(d.mem[8:16]))
|
||||
d.v3 = round(d.v3, u64(d.mem[16:24]))
|
||||
d.v4 = round(d.v4, u64(d.mem[24:32]))
|
||||
b = b[c:]
|
||||
d.n = 0
|
||||
}
|
||||
|
||||
if len(b) >= 32 {
|
||||
// One or more full blocks left.
|
||||
nw := writeBlocks(d, b)
|
||||
b = b[nw:]
|
||||
}
|
||||
|
||||
// Store any remaining partial block.
|
||||
copy(d.mem[:], b)
|
||||
d.n = len(b)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Sum appends the current hash to b and returns the resulting slice.
|
||||
func (d *Digest) Sum(b []byte) []byte {
|
||||
s := d.Sum64()
|
||||
return append(
|
||||
b,
|
||||
byte(s>>56),
|
||||
byte(s>>48),
|
||||
byte(s>>40),
|
||||
byte(s>>32),
|
||||
byte(s>>24),
|
||||
byte(s>>16),
|
||||
byte(s>>8),
|
||||
byte(s),
|
||||
)
|
||||
}
|
||||
|
||||
// Sum64 returns the current hash.
|
||||
func (d *Digest) Sum64() uint64 {
|
||||
var h uint64
|
||||
|
||||
if d.total >= 32 {
|
||||
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
|
||||
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
|
||||
h = mergeRound(h, v1)
|
||||
h = mergeRound(h, v2)
|
||||
h = mergeRound(h, v3)
|
||||
h = mergeRound(h, v4)
|
||||
} else {
|
||||
h = d.v3 + prime5
|
||||
}
|
||||
|
||||
h += d.total
|
||||
|
||||
b := d.mem[:d.n&(len(d.mem)-1)]
|
||||
for ; len(b) >= 8; b = b[8:] {
|
||||
k1 := round(0, u64(b[:8]))
|
||||
h ^= k1
|
||||
h = rol27(h)*prime1 + prime4
|
||||
}
|
||||
if len(b) >= 4 {
|
||||
h ^= uint64(u32(b[:4])) * prime1
|
||||
h = rol23(h)*prime2 + prime3
|
||||
b = b[4:]
|
||||
}
|
||||
for ; len(b) > 0; b = b[1:] {
|
||||
h ^= uint64(b[0]) * prime5
|
||||
h = rol11(h) * prime1
|
||||
}
|
||||
|
||||
h ^= h >> 33
|
||||
h *= prime2
|
||||
h ^= h >> 29
|
||||
h *= prime3
|
||||
h ^= h >> 32
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
const (
|
||||
magic = "xxh\x06"
|
||||
marshaledSize = len(magic) + 8*5 + 32
|
||||
)
|
||||
|
||||
// MarshalBinary implements the encoding.BinaryMarshaler interface.
|
||||
func (d *Digest) MarshalBinary() ([]byte, error) {
|
||||
b := make([]byte, 0, marshaledSize)
|
||||
b = append(b, magic...)
|
||||
b = appendUint64(b, d.v1)
|
||||
b = appendUint64(b, d.v2)
|
||||
b = appendUint64(b, d.v3)
|
||||
b = appendUint64(b, d.v4)
|
||||
b = appendUint64(b, d.total)
|
||||
b = append(b, d.mem[:d.n]...)
|
||||
b = b[:len(b)+len(d.mem)-d.n]
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
|
||||
func (d *Digest) UnmarshalBinary(b []byte) error {
|
||||
if len(b) < len(magic) || string(b[:len(magic)]) != magic {
|
||||
return errors.New("xxhash: invalid hash state identifier")
|
||||
}
|
||||
if len(b) != marshaledSize {
|
||||
return errors.New("xxhash: invalid hash state size")
|
||||
}
|
||||
b = b[len(magic):]
|
||||
b, d.v1 = consumeUint64(b)
|
||||
b, d.v2 = consumeUint64(b)
|
||||
b, d.v3 = consumeUint64(b)
|
||||
b, d.v4 = consumeUint64(b)
|
||||
b, d.total = consumeUint64(b)
|
||||
copy(d.mem[:], b)
|
||||
d.n = int(d.total % uint64(len(d.mem)))
|
||||
return nil
|
||||
}
|
||||
|
||||
func appendUint64(b []byte, x uint64) []byte {
|
||||
var a [8]byte
|
||||
binary.LittleEndian.PutUint64(a[:], x)
|
||||
return append(b, a[:]...)
|
||||
}
|
||||
|
||||
func consumeUint64(b []byte) ([]byte, uint64) {
|
||||
x := u64(b)
|
||||
return b[8:], x
|
||||
}
|
||||
|
||||
func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) }
|
||||
func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) }
|
||||
|
||||
func round(acc, input uint64) uint64 {
|
||||
acc += input * prime2
|
||||
acc = rol31(acc)
|
||||
acc *= prime1
|
||||
return acc
|
||||
}
|
||||
|
||||
func mergeRound(acc, val uint64) uint64 {
|
||||
val = round(0, val)
|
||||
acc ^= val
|
||||
acc = acc*prime1 + prime4
|
||||
return acc
|
||||
}
|
||||
|
||||
func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) }
|
||||
func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) }
|
||||
func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) }
|
||||
func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) }
|
||||
func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) }
|
||||
func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) }
|
||||
func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) }
|
||||
func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) }
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
//go:build !appengine && gc && !purego
|
||||
// +build !appengine
|
||||
// +build gc
|
||||
// +build !purego
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
// Registers:
|
||||
#define h AX
|
||||
#define d AX
|
||||
#define p SI // pointer to advance through b
|
||||
#define n DX
|
||||
#define end BX // loop end
|
||||
#define v1 R8
|
||||
#define v2 R9
|
||||
#define v3 R10
|
||||
#define v4 R11
|
||||
#define x R12
|
||||
#define prime1 R13
|
||||
#define prime2 R14
|
||||
#define prime4 DI
|
||||
|
||||
#define round(acc, x) \
|
||||
IMULQ prime2, x \
|
||||
ADDQ x, acc \
|
||||
ROLQ $31, acc \
|
||||
IMULQ prime1, acc
|
||||
|
||||
// round0 performs the operation x = round(0, x).
|
||||
#define round0(x) \
|
||||
IMULQ prime2, x \
|
||||
ROLQ $31, x \
|
||||
IMULQ prime1, x
|
||||
|
||||
// mergeRound applies a merge round on the two registers acc and x.
|
||||
// It assumes that prime1, prime2, and prime4 have been loaded.
|
||||
#define mergeRound(acc, x) \
|
||||
round0(x) \
|
||||
XORQ x, acc \
|
||||
IMULQ prime1, acc \
|
||||
ADDQ prime4, acc
|
||||
|
||||
// blockLoop processes as many 32-byte blocks as possible,
|
||||
// updating v1, v2, v3, and v4. It assumes that there is at least one block
|
||||
// to process.
|
||||
#define blockLoop() \
|
||||
loop: \
|
||||
MOVQ +0(p), x \
|
||||
round(v1, x) \
|
||||
MOVQ +8(p), x \
|
||||
round(v2, x) \
|
||||
MOVQ +16(p), x \
|
||||
round(v3, x) \
|
||||
MOVQ +24(p), x \
|
||||
round(v4, x) \
|
||||
ADDQ $32, p \
|
||||
CMPQ p, end \
|
||||
JLE loop
|
||||
|
||||
// func Sum64(b []byte) uint64
|
||||
TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32
|
||||
// Load fixed primes.
|
||||
MOVQ ·primes+0(SB), prime1
|
||||
MOVQ ·primes+8(SB), prime2
|
||||
MOVQ ·primes+24(SB), prime4
|
||||
|
||||
// Load slice.
|
||||
MOVQ b_base+0(FP), p
|
||||
MOVQ b_len+8(FP), n
|
||||
LEAQ (p)(n*1), end
|
||||
|
||||
// The first loop limit will be len(b)-32.
|
||||
SUBQ $32, end
|
||||
|
||||
// Check whether we have at least one block.
|
||||
CMPQ n, $32
|
||||
JLT noBlocks
|
||||
|
||||
// Set up initial state (v1, v2, v3, v4).
|
||||
MOVQ prime1, v1
|
||||
ADDQ prime2, v1
|
||||
MOVQ prime2, v2
|
||||
XORQ v3, v3
|
||||
XORQ v4, v4
|
||||
SUBQ prime1, v4
|
||||
|
||||
blockLoop()
|
||||
|
||||
MOVQ v1, h
|
||||
ROLQ $1, h
|
||||
MOVQ v2, x
|
||||
ROLQ $7, x
|
||||
ADDQ x, h
|
||||
MOVQ v3, x
|
||||
ROLQ $12, x
|
||||
ADDQ x, h
|
||||
MOVQ v4, x
|
||||
ROLQ $18, x
|
||||
ADDQ x, h
|
||||
|
||||
mergeRound(h, v1)
|
||||
mergeRound(h, v2)
|
||||
mergeRound(h, v3)
|
||||
mergeRound(h, v4)
|
||||
|
||||
JMP afterBlocks
|
||||
|
||||
noBlocks:
|
||||
MOVQ ·primes+32(SB), h
|
||||
|
||||
afterBlocks:
|
||||
ADDQ n, h
|
||||
|
||||
ADDQ $24, end
|
||||
CMPQ p, end
|
||||
JG try4
|
||||
|
||||
loop8:
|
||||
MOVQ (p), x
|
||||
ADDQ $8, p
|
||||
round0(x)
|
||||
XORQ x, h
|
||||
ROLQ $27, h
|
||||
IMULQ prime1, h
|
||||
ADDQ prime4, h
|
||||
|
||||
CMPQ p, end
|
||||
JLE loop8
|
||||
|
||||
try4:
|
||||
ADDQ $4, end
|
||||
CMPQ p, end
|
||||
JG try1
|
||||
|
||||
MOVL (p), x
|
||||
ADDQ $4, p
|
||||
IMULQ prime1, x
|
||||
XORQ x, h
|
||||
|
||||
ROLQ $23, h
|
||||
IMULQ prime2, h
|
||||
ADDQ ·primes+16(SB), h
|
||||
|
||||
try1:
|
||||
ADDQ $4, end
|
||||
CMPQ p, end
|
||||
JGE finalize
|
||||
|
||||
loop1:
|
||||
MOVBQZX (p), x
|
||||
ADDQ $1, p
|
||||
IMULQ ·primes+32(SB), x
|
||||
XORQ x, h
|
||||
ROLQ $11, h
|
||||
IMULQ prime1, h
|
||||
|
||||
CMPQ p, end
|
||||
JL loop1
|
||||
|
||||
finalize:
|
||||
MOVQ h, x
|
||||
SHRQ $33, x
|
||||
XORQ x, h
|
||||
IMULQ prime2, h
|
||||
MOVQ h, x
|
||||
SHRQ $29, x
|
||||
XORQ x, h
|
||||
IMULQ ·primes+16(SB), h
|
||||
MOVQ h, x
|
||||
SHRQ $32, x
|
||||
XORQ x, h
|
||||
|
||||
MOVQ h, ret+24(FP)
|
||||
RET
|
||||
|
||||
// func writeBlocks(d *Digest, b []byte) int
|
||||
TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40
|
||||
// Load fixed primes needed for round.
|
||||
MOVQ ·primes+0(SB), prime1
|
||||
MOVQ ·primes+8(SB), prime2
|
||||
|
||||
// Load slice.
|
||||
MOVQ b_base+8(FP), p
|
||||
MOVQ b_len+16(FP), n
|
||||
LEAQ (p)(n*1), end
|
||||
SUBQ $32, end
|
||||
|
||||
// Load vN from d.
|
||||
MOVQ s+0(FP), d
|
||||
MOVQ 0(d), v1
|
||||
MOVQ 8(d), v2
|
||||
MOVQ 16(d), v3
|
||||
MOVQ 24(d), v4
|
||||
|
||||
// We don't need to check the loop condition here; this function is
|
||||
// always called with at least one block of data to process.
|
||||
blockLoop()
|
||||
|
||||
// Copy vN back to d.
|
||||
MOVQ v1, 0(d)
|
||||
MOVQ v2, 8(d)
|
||||
MOVQ v3, 16(d)
|
||||
MOVQ v4, 24(d)
|
||||
|
||||
// The number of bytes written is p minus the old base pointer.
|
||||
SUBQ b_base+8(FP), p
|
||||
MOVQ p, ret+32(FP)
|
||||
|
||||
RET
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
//go:build !appengine && gc && !purego
|
||||
// +build !appengine
|
||||
// +build gc
|
||||
// +build !purego
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
// Registers:
|
||||
#define digest R1
|
||||
#define h R2 // return value
|
||||
#define p R3 // input pointer
|
||||
#define n R4 // input length
|
||||
#define nblocks R5 // n / 32
|
||||
#define prime1 R7
|
||||
#define prime2 R8
|
||||
#define prime3 R9
|
||||
#define prime4 R10
|
||||
#define prime5 R11
|
||||
#define v1 R12
|
||||
#define v2 R13
|
||||
#define v3 R14
|
||||
#define v4 R15
|
||||
#define x1 R20
|
||||
#define x2 R21
|
||||
#define x3 R22
|
||||
#define x4 R23
|
||||
|
||||
#define round(acc, x) \
|
||||
MADD prime2, acc, x, acc \
|
||||
ROR $64-31, acc \
|
||||
MUL prime1, acc
|
||||
|
||||
// round0 performs the operation x = round(0, x).
|
||||
#define round0(x) \
|
||||
MUL prime2, x \
|
||||
ROR $64-31, x \
|
||||
MUL prime1, x
|
||||
|
||||
#define mergeRound(acc, x) \
|
||||
round0(x) \
|
||||
EOR x, acc \
|
||||
MADD acc, prime4, prime1, acc
|
||||
|
||||
// blockLoop processes as many 32-byte blocks as possible,
|
||||
// updating v1, v2, v3, and v4. It assumes that n >= 32.
|
||||
#define blockLoop() \
|
||||
LSR $5, n, nblocks \
|
||||
PCALIGN $16 \
|
||||
loop: \
|
||||
LDP.P 16(p), (x1, x2) \
|
||||
LDP.P 16(p), (x3, x4) \
|
||||
round(v1, x1) \
|
||||
round(v2, x2) \
|
||||
round(v3, x3) \
|
||||
round(v4, x4) \
|
||||
SUB $1, nblocks \
|
||||
CBNZ nblocks, loop
|
||||
|
||||
// func Sum64(b []byte) uint64
|
||||
TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32
|
||||
LDP b_base+0(FP), (p, n)
|
||||
|
||||
LDP ·primes+0(SB), (prime1, prime2)
|
||||
LDP ·primes+16(SB), (prime3, prime4)
|
||||
MOVD ·primes+32(SB), prime5
|
||||
|
||||
CMP $32, n
|
||||
CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 }
|
||||
BLT afterLoop
|
||||
|
||||
ADD prime1, prime2, v1
|
||||
MOVD prime2, v2
|
||||
MOVD $0, v3
|
||||
NEG prime1, v4
|
||||
|
||||
blockLoop()
|
||||
|
||||
ROR $64-1, v1, x1
|
||||
ROR $64-7, v2, x2
|
||||
ADD x1, x2
|
||||
ROR $64-12, v3, x3
|
||||
ROR $64-18, v4, x4
|
||||
ADD x3, x4
|
||||
ADD x2, x4, h
|
||||
|
||||
mergeRound(h, v1)
|
||||
mergeRound(h, v2)
|
||||
mergeRound(h, v3)
|
||||
mergeRound(h, v4)
|
||||
|
||||
afterLoop:
|
||||
ADD n, h
|
||||
|
||||
TBZ $4, n, try8
|
||||
LDP.P 16(p), (x1, x2)
|
||||
|
||||
round0(x1)
|
||||
|
||||
// NOTE: here and below, sequencing the EOR after the ROR (using a
|
||||
// rotated register) is worth a small but measurable speedup for small
|
||||
// inputs.
|
||||
ROR $64-27, h
|
||||
EOR x1 @> 64-27, h, h
|
||||
MADD h, prime4, prime1, h
|
||||
|
||||
round0(x2)
|
||||
ROR $64-27, h
|
||||
EOR x2 @> 64-27, h, h
|
||||
MADD h, prime4, prime1, h
|
||||
|
||||
try8:
|
||||
TBZ $3, n, try4
|
||||
MOVD.P 8(p), x1
|
||||
|
||||
round0(x1)
|
||||
ROR $64-27, h
|
||||
EOR x1 @> 64-27, h, h
|
||||
MADD h, prime4, prime1, h
|
||||
|
||||
try4:
|
||||
TBZ $2, n, try2
|
||||
MOVWU.P 4(p), x2
|
||||
|
||||
MUL prime1, x2
|
||||
ROR $64-23, h
|
||||
EOR x2 @> 64-23, h, h
|
||||
MADD h, prime3, prime2, h
|
||||
|
||||
try2:
|
||||
TBZ $1, n, try1
|
||||
MOVHU.P 2(p), x3
|
||||
AND $255, x3, x1
|
||||
LSR $8, x3, x2
|
||||
|
||||
MUL prime5, x1
|
||||
ROR $64-11, h
|
||||
EOR x1 @> 64-11, h, h
|
||||
MUL prime1, h
|
||||
|
||||
MUL prime5, x2
|
||||
ROR $64-11, h
|
||||
EOR x2 @> 64-11, h, h
|
||||
MUL prime1, h
|
||||
|
||||
try1:
|
||||
TBZ $0, n, finalize
|
||||
MOVBU (p), x4
|
||||
|
||||
MUL prime5, x4
|
||||
ROR $64-11, h
|
||||
EOR x4 @> 64-11, h, h
|
||||
MUL prime1, h
|
||||
|
||||
finalize:
|
||||
EOR h >> 33, h
|
||||
MUL prime2, h
|
||||
EOR h >> 29, h
|
||||
MUL prime3, h
|
||||
EOR h >> 32, h
|
||||
|
||||
MOVD h, ret+24(FP)
|
||||
RET
|
||||
|
||||
// func writeBlocks(d *Digest, b []byte) int
|
||||
TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40
|
||||
LDP ·primes+0(SB), (prime1, prime2)
|
||||
|
||||
// Load state. Assume v[1-4] are stored contiguously.
|
||||
MOVD d+0(FP), digest
|
||||
LDP 0(digest), (v1, v2)
|
||||
LDP 16(digest), (v3, v4)
|
||||
|
||||
LDP b_base+8(FP), (p, n)
|
||||
|
||||
blockLoop()
|
||||
|
||||
// Store updated state.
|
||||
STP (v1, v2), 0(digest)
|
||||
STP (v3, v4), 16(digest)
|
||||
|
||||
BIC $31, n
|
||||
MOVD n, ret+32(FP)
|
||||
RET
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
//go:build (amd64 || arm64) && !appengine && gc && !purego
|
||||
// +build amd64 arm64
|
||||
// +build !appengine
|
||||
// +build gc
|
||||
// +build !purego
|
||||
|
||||
package xxhash
|
||||
|
||||
// Sum64 computes the 64-bit xxHash digest of b.
|
||||
//
|
||||
//go:noescape
|
||||
func Sum64(b []byte) uint64
|
||||
|
||||
//go:noescape
|
||||
func writeBlocks(d *Digest, b []byte) int
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
//go:build (!amd64 && !arm64) || appengine || !gc || purego
|
||||
// +build !amd64,!arm64 appengine !gc purego
|
||||
|
||||
package xxhash
|
||||
|
||||
// Sum64 computes the 64-bit xxHash digest of b.
|
||||
func Sum64(b []byte) uint64 {
|
||||
// A simpler version would be
|
||||
// d := New()
|
||||
// d.Write(b)
|
||||
// return d.Sum64()
|
||||
// but this is faster, particularly for small inputs.
|
||||
|
||||
n := len(b)
|
||||
var h uint64
|
||||
|
||||
if n >= 32 {
|
||||
v1 := primes[0] + prime2
|
||||
v2 := prime2
|
||||
v3 := uint64(0)
|
||||
v4 := -primes[0]
|
||||
for len(b) >= 32 {
|
||||
v1 = round(v1, u64(b[0:8:len(b)]))
|
||||
v2 = round(v2, u64(b[8:16:len(b)]))
|
||||
v3 = round(v3, u64(b[16:24:len(b)]))
|
||||
v4 = round(v4, u64(b[24:32:len(b)]))
|
||||
b = b[32:len(b):len(b)]
|
||||
}
|
||||
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
|
||||
h = mergeRound(h, v1)
|
||||
h = mergeRound(h, v2)
|
||||
h = mergeRound(h, v3)
|
||||
h = mergeRound(h, v4)
|
||||
} else {
|
||||
h = prime5
|
||||
}
|
||||
|
||||
h += uint64(n)
|
||||
|
||||
for ; len(b) >= 8; b = b[8:] {
|
||||
k1 := round(0, u64(b[:8]))
|
||||
h ^= k1
|
||||
h = rol27(h)*prime1 + prime4
|
||||
}
|
||||
if len(b) >= 4 {
|
||||
h ^= uint64(u32(b[:4])) * prime1
|
||||
h = rol23(h)*prime2 + prime3
|
||||
b = b[4:]
|
||||
}
|
||||
for ; len(b) > 0; b = b[1:] {
|
||||
h ^= uint64(b[0]) * prime5
|
||||
h = rol11(h) * prime1
|
||||
}
|
||||
|
||||
h ^= h >> 33
|
||||
h *= prime2
|
||||
h ^= h >> 29
|
||||
h *= prime3
|
||||
h ^= h >> 32
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
func writeBlocks(d *Digest, b []byte) int {
|
||||
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
|
||||
n := len(b)
|
||||
for len(b) >= 32 {
|
||||
v1 = round(v1, u64(b[0:8:len(b)]))
|
||||
v2 = round(v2, u64(b[8:16:len(b)]))
|
||||
v3 = round(v3, u64(b[16:24:len(b)]))
|
||||
v4 = round(v4, u64(b[24:32:len(b)]))
|
||||
b = b[32:len(b):len(b)]
|
||||
}
|
||||
d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4
|
||||
return n - len(b)
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
//go:build appengine
|
||||
// +build appengine
|
||||
|
||||
// This file contains the safe implementations of otherwise unsafe-using code.
|
||||
|
||||
package xxhash
|
||||
|
||||
// Sum64String computes the 64-bit xxHash digest of s.
|
||||
func Sum64String(s string) uint64 {
|
||||
return Sum64([]byte(s))
|
||||
}
|
||||
|
||||
// WriteString adds more data to d. It always returns len(s), nil.
|
||||
func (d *Digest) WriteString(s string) (n int, err error) {
|
||||
return d.Write([]byte(s))
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
//go:build !appengine
|
||||
// +build !appengine
|
||||
|
||||
// This file encapsulates usage of unsafe.
|
||||
// xxhash_safe.go contains the safe implementations.
|
||||
|
||||
package xxhash
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// In the future it's possible that compiler optimizations will make these
|
||||
// XxxString functions unnecessary by realizing that calls such as
|
||||
// Sum64([]byte(s)) don't need to copy s. See https://go.dev/issue/2205.
|
||||
// If that happens, even if we keep these functions they can be replaced with
|
||||
// the trivial safe code.
|
||||
|
||||
// NOTE: The usual way of doing an unsafe string-to-[]byte conversion is:
|
||||
//
|
||||
// var b []byte
|
||||
// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
|
||||
// bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
|
||||
// bh.Len = len(s)
|
||||
// bh.Cap = len(s)
|
||||
//
|
||||
// Unfortunately, as of Go 1.15.3 the inliner's cost model assigns a high enough
|
||||
// weight to this sequence of expressions that any function that uses it will
|
||||
// not be inlined. Instead, the functions below use a different unsafe
|
||||
// conversion designed to minimize the inliner weight and allow both to be
|
||||
// inlined. There is also a test (TestInlining) which verifies that these are
|
||||
// inlined.
|
||||
//
|
||||
// See https://github.com/golang/go/issues/42739 for discussion.
|
||||
|
||||
// Sum64String computes the 64-bit xxHash digest of s.
|
||||
// It may be faster than Sum64([]byte(s)) by avoiding a copy.
|
||||
func Sum64String(s string) uint64 {
|
||||
b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))
|
||||
return Sum64(b)
|
||||
}
|
||||
|
||||
// WriteString adds more data to d. It always returns len(s), nil.
|
||||
// It may be faster than Write([]byte(s)) by avoiding a copy.
|
||||
func (d *Digest) WriteString(s string) (n int, err error) {
|
||||
d.Write(*(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)})))
|
||||
// d.Write always returns len(s), nil.
|
||||
// Ignoring the return output and returning these fixed values buys a
|
||||
// savings of 6 in the inliner's cost model.
|
||||
return len(s), nil
|
||||
}
|
||||
|
||||
// sliceHeader is similar to reflect.SliceHeader, but it assumes that the layout
|
||||
// of the first two words is the same as the layout of a string.
|
||||
type sliceHeader struct {
|
||||
s string
|
||||
cap int
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2020 Damian Gryski <damian@gryski.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package rendezvous
|
||||
|
||||
type Rendezvous struct {
|
||||
nodes map[string]int
|
||||
nstr []string
|
||||
nhash []uint64
|
||||
hash Hasher
|
||||
}
|
||||
|
||||
type Hasher func(s string) uint64
|
||||
|
||||
func New(nodes []string, hash Hasher) *Rendezvous {
|
||||
r := &Rendezvous{
|
||||
nodes: make(map[string]int, len(nodes)),
|
||||
nstr: make([]string, len(nodes)),
|
||||
nhash: make([]uint64, len(nodes)),
|
||||
hash: hash,
|
||||
}
|
||||
|
||||
for i, n := range nodes {
|
||||
r.nodes[n] = i
|
||||
r.nstr[i] = n
|
||||
r.nhash[i] = hash(n)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *Rendezvous) Lookup(k string) string {
|
||||
// short-circuit if we're empty
|
||||
if len(r.nodes) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
khash := r.hash(k)
|
||||
|
||||
var midx int
|
||||
var mhash = xorshiftMult64(khash ^ r.nhash[0])
|
||||
|
||||
for i, nhash := range r.nhash[1:] {
|
||||
if h := xorshiftMult64(khash ^ nhash); h > mhash {
|
||||
midx = i + 1
|
||||
mhash = h
|
||||
}
|
||||
}
|
||||
|
||||
return r.nstr[midx]
|
||||
}
|
||||
|
||||
func (r *Rendezvous) Add(node string) {
|
||||
r.nodes[node] = len(r.nstr)
|
||||
r.nstr = append(r.nstr, node)
|
||||
r.nhash = append(r.nhash, r.hash(node))
|
||||
}
|
||||
|
||||
func (r *Rendezvous) Remove(node string) {
|
||||
// find index of node to remove
|
||||
nidx := r.nodes[node]
|
||||
|
||||
// remove from the slices
|
||||
l := len(r.nstr)
|
||||
r.nstr[nidx] = r.nstr[l]
|
||||
r.nstr = r.nstr[:l]
|
||||
|
||||
r.nhash[nidx] = r.nhash[l]
|
||||
r.nhash = r.nhash[:l]
|
||||
|
||||
// update the map
|
||||
delete(r.nodes, node)
|
||||
moved := r.nstr[nidx]
|
||||
r.nodes[moved] = nidx
|
||||
}
|
||||
|
||||
func xorshiftMult64(x uint64) uint64 {
|
||||
x ^= x >> 12 // a
|
||||
x ^= x << 25 // b
|
||||
x ^= x >> 27 // c
|
||||
return x * 2685821657736338717
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.x
|
||||
- tip
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: tip
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2019 Jack Christensen
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
[](https://godoc.org/github.com/jackc/pgpassfile)
|
||||
[](https://travis-ci.org/jackc/pgpassfile)
|
||||
|
||||
# pgpassfile
|
||||
|
||||
Package pgpassfile is a parser PostgreSQL .pgpass files.
|
||||
|
||||
Extracted and rewritten from original implementation in https://github.com/jackc/pgx.
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
// Package pgpassfile is a parser PostgreSQL .pgpass files.
|
||||
package pgpassfile
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Entry represents a line in a PG passfile.
|
||||
type Entry struct {
|
||||
Hostname string
|
||||
Port string
|
||||
Database string
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
// Passfile is the in memory data structure representing a PG passfile.
|
||||
type Passfile struct {
|
||||
Entries []*Entry
|
||||
}
|
||||
|
||||
// ReadPassfile reads the file at path and parses it into a Passfile.
|
||||
func ReadPassfile(path string) (*Passfile, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
return ParsePassfile(f)
|
||||
}
|
||||
|
||||
// ParsePassfile reads r and parses it into a Passfile.
|
||||
func ParsePassfile(r io.Reader) (*Passfile, error) {
|
||||
passfile := &Passfile{}
|
||||
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
entry := parseLine(scanner.Text())
|
||||
if entry != nil {
|
||||
passfile.Entries = append(passfile.Entries, entry)
|
||||
}
|
||||
}
|
||||
|
||||
return passfile, scanner.Err()
|
||||
}
|
||||
|
||||
// Match (not colons or escaped colon or escaped backslash)+. Essentially gives a split on unescaped
|
||||
// colon.
|
||||
var colonSplitterRegexp = regexp.MustCompile("(([^:]|(\\:)))+")
|
||||
|
||||
// var colonSplitterRegexp = regexp.MustCompile("((?:[^:]|(?:\\:)|(?:\\\\))+)")
|
||||
|
||||
// parseLine parses a line into an *Entry. It returns nil on comment lines or any other unparsable
|
||||
// line.
|
||||
func parseLine(line string) *Entry {
|
||||
const (
|
||||
tmpBackslash = "\r"
|
||||
tmpColon = "\n"
|
||||
)
|
||||
|
||||
line = strings.TrimSpace(line)
|
||||
|
||||
if strings.HasPrefix(line, "#") {
|
||||
return nil
|
||||
}
|
||||
|
||||
line = strings.Replace(line, `\\`, tmpBackslash, -1)
|
||||
line = strings.Replace(line, `\:`, tmpColon, -1)
|
||||
|
||||
parts := strings.Split(line, ":")
|
||||
if len(parts) != 5 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unescape escaped colons and backslashes
|
||||
for i := range parts {
|
||||
parts[i] = strings.Replace(parts[i], tmpBackslash, `\`, -1)
|
||||
parts[i] = strings.Replace(parts[i], tmpColon, `:`, -1)
|
||||
}
|
||||
|
||||
return &Entry{
|
||||
Hostname: parts[0],
|
||||
Port: parts[1],
|
||||
Database: parts[2],
|
||||
Username: parts[3],
|
||||
Password: parts[4],
|
||||
}
|
||||
}
|
||||
|
||||
// FindPassword finds the password for the provided hostname, port, database, and username. For a
|
||||
// Unix domain socket hostname must be set to "localhost". An empty string will be returned if no
|
||||
// match is found.
|
||||
//
|
||||
// See https://www.postgresql.org/docs/current/libpq-pgpass.html for more password file information.
|
||||
func (pf *Passfile) FindPassword(hostname, port, database, username string) (password string) {
|
||||
for _, e := range pf.Entries {
|
||||
if (e.Hostname == "*" || e.Hostname == hostname) &&
|
||||
(e.Port == "*" || e.Port == port) &&
|
||||
(e.Database == "*" || e.Database == database) &&
|
||||
(e.Username == "*" || e.Username == username) {
|
||||
return e.Password
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2020 Jack Christensen
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
[](https://pkg.go.dev/github.com/jackc/pgservicefile)
|
||||
[](https://github.com/jackc/pgservicefile/actions/workflows/ci.yml)
|
||||
|
||||
|
||||
# pgservicefile
|
||||
|
||||
Package pgservicefile is a parser for PostgreSQL service files (e.g. `.pg_service.conf`).
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
// Package pgservicefile is a parser for PostgreSQL service files (e.g. .pg_service.conf).
|
||||
package pgservicefile
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
Name string
|
||||
Settings map[string]string
|
||||
}
|
||||
|
||||
type Servicefile struct {
|
||||
Services []*Service
|
||||
servicesByName map[string]*Service
|
||||
}
|
||||
|
||||
// GetService returns the named service.
|
||||
func (sf *Servicefile) GetService(name string) (*Service, error) {
|
||||
service, present := sf.servicesByName[name]
|
||||
if !present {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
return service, nil
|
||||
}
|
||||
|
||||
// ReadServicefile reads the file at path and parses it into a Servicefile.
|
||||
func ReadServicefile(path string) (*Servicefile, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
return ParseServicefile(f)
|
||||
}
|
||||
|
||||
// ParseServicefile reads r and parses it into a Servicefile.
|
||||
func ParseServicefile(r io.Reader) (*Servicefile, error) {
|
||||
servicefile := &Servicefile{}
|
||||
|
||||
var service *Service
|
||||
scanner := bufio.NewScanner(r)
|
||||
lineNum := 0
|
||||
for scanner.Scan() {
|
||||
lineNum += 1
|
||||
line := scanner.Text()
|
||||
line = strings.TrimSpace(line)
|
||||
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
// ignore comments and empty lines
|
||||
} else if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
|
||||
service = &Service{Name: line[1 : len(line)-1], Settings: make(map[string]string)}
|
||||
servicefile.Services = append(servicefile.Services, service)
|
||||
} else if service != nil {
|
||||
parts := strings.SplitN(line, "=", 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("unable to parse line %d", lineNum)
|
||||
}
|
||||
|
||||
key := strings.TrimSpace(parts[0])
|
||||
value := strings.TrimSpace(parts[1])
|
||||
|
||||
service.Settings[key] = value
|
||||
} else {
|
||||
return nil, fmt.Errorf("line %d is not in a section", lineNum)
|
||||
}
|
||||
}
|
||||
|
||||
servicefile.servicesByName = make(map[string]*Service, len(servicefile.Services))
|
||||
for _, service := range servicefile.Services {
|
||||
servicefile.servicesByName[service.Name] = service
|
||||
}
|
||||
|
||||
return servicefile, scanner.Err()
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
|
||||
.envrc
|
||||
/.testdb
|
||||
|
||||
.DS_Store
|
||||
+434
@@ -0,0 +1,434 @@
|
||||
# 5.7.2 (December 21, 2024)
|
||||
|
||||
* Fix prepared statement already exists on batch prepare failure
|
||||
* Add commit query to tx options (Lucas Hild)
|
||||
* Fix pgtype.Timestamp json unmarshal (Shean de Montigny-Desautels)
|
||||
* Add message body size limits in frontend and backend (zene)
|
||||
* Add xid8 type
|
||||
* Ensure planning encodes and scans cannot infinitely recurse
|
||||
* Implement pgtype.UUID.String() (Konstantin Grachev)
|
||||
* Switch from ExecParams to Exec in ValidateConnectTargetSessionAttrs functions (Alexander Rumyantsev)
|
||||
* Update golang.org/x/crypto
|
||||
|
||||
# 5.7.1 (September 10, 2024)
|
||||
|
||||
* Fix data race in tracelog.TraceLog
|
||||
* Update puddle to v2.2.2. This removes the import of nanotime via linkname.
|
||||
* Update golang.org/x/crypto and golang.org/x/text
|
||||
|
||||
# 5.7.0 (September 7, 2024)
|
||||
|
||||
* Add support for sslrootcert=system (Yann Soubeyrand)
|
||||
* Add LoadTypes to load multiple types in a single SQL query (Nick Farrell)
|
||||
* Add XMLCodec supports encoding + scanning XML column type like json (nickcruess-soda)
|
||||
* Add MultiTrace (Stepan Rabotkin)
|
||||
* Add TraceLogConfig with customizable TimeKey (stringintech)
|
||||
* pgx.ErrNoRows wraps sql.ErrNoRows to aid in database/sql compatibility with native pgx functions (merlin)
|
||||
* Support scanning binary formatted uint32 into string / TextScanner (jennifersp)
|
||||
* Fix interval encoding to allow 0s and avoid extra spaces (Carlos Pérez-Aradros Herce)
|
||||
* Update pgservicefile - fixes panic when parsing invalid file
|
||||
* Better error message when reading past end of batch
|
||||
* Don't print url when url.Parse returns an error (Kevin Biju)
|
||||
* Fix snake case name normalization collision in RowToStructByName with db tag (nolandseigler)
|
||||
* Fix: Scan and encode types with underlying types of arrays
|
||||
|
||||
# 5.6.0 (May 25, 2024)
|
||||
|
||||
* Add StrictNamedArgs (Tomas Zahradnicek)
|
||||
* Add support for macaddr8 type (Carlos Pérez-Aradros Herce)
|
||||
* Add SeverityUnlocalized field to PgError / Notice
|
||||
* Performance optimization of RowToStructByPos/Name (Zach Olstein)
|
||||
* Allow customizing context canceled behavior for pgconn
|
||||
* Add ScanLocation to pgtype.Timestamp[tz]Codec
|
||||
* Add custom data to pgconn.PgConn
|
||||
* Fix ResultReader.Read() to handle nil values
|
||||
* Do not encode interval microseconds when they are 0 (Carlos Pérez-Aradros Herce)
|
||||
* pgconn.SafeToRetry checks for wrapped errors (tjasko)
|
||||
* Failed connection attempts include all errors
|
||||
* Optimize LargeObject.Read (Mitar)
|
||||
* Add tracing for connection acquire and release from pool (ngavinsir)
|
||||
* Fix encode driver.Valuer not called when nil
|
||||
* Add support for custom JSON marshal and unmarshal (Mitar)
|
||||
* Use Go default keepalive for TCP connections (Hans-Joachim Kliemeck)
|
||||
|
||||
# 5.5.5 (March 9, 2024)
|
||||
|
||||
Use spaces instead of parentheses for SQL sanitization.
|
||||
|
||||
This still solves the problem of negative numbers creating a line comment, but this avoids breaking edge cases such as
|
||||
`set foo to $1` where the substitution is taking place in a location where an arbitrary expression is not allowed.
|
||||
|
||||
# 5.5.4 (March 4, 2024)
|
||||
|
||||
Fix CVE-2024-27304
|
||||
|
||||
SQL injection can occur if an attacker can cause a single query or bind message to exceed 4 GB in size. An integer
|
||||
overflow in the calculated message size can cause the one large message to be sent as multiple messages under the
|
||||
attacker's control.
|
||||
|
||||
Thanks to Paul Gerste for reporting this issue.
|
||||
|
||||
* Fix behavior of CollectRows to return empty slice if Rows are empty (Felix)
|
||||
* Fix simple protocol encoding of json.RawMessage
|
||||
* Fix *Pipeline.getResults should close pipeline on error
|
||||
* Fix panic in TryFindUnderlyingTypeScanPlan (David Kurman)
|
||||
* Fix deallocation of invalidated cached statements in a transaction
|
||||
* Handle invalid sslkey file
|
||||
* Fix scan float4 into sql.Scanner
|
||||
* Fix pgtype.Bits not making copy of data from read buffer. This would cause the data to be corrupted by future reads.
|
||||
|
||||
# 5.5.3 (February 3, 2024)
|
||||
|
||||
* Fix: prepared statement already exists
|
||||
* Improve CopyFrom auto-conversion of text-ish values
|
||||
* Add ltree type support (Florent Viel)
|
||||
* Make some properties of Batch and QueuedQuery public (Pavlo Golub)
|
||||
* Add AppendRows function (Edoardo Spadolini)
|
||||
* Optimize convert UUID [16]byte to string (Kirill Malikov)
|
||||
* Fix: LargeObject Read and Write of more than ~1GB at a time (Mitar)
|
||||
|
||||
# 5.5.2 (January 13, 2024)
|
||||
|
||||
* Allow NamedArgs to start with underscore
|
||||
* pgproto3: Maximum message body length support (jeremy.spriet)
|
||||
* Upgrade golang.org/x/crypto to v0.17.0
|
||||
* Add snake_case support to RowToStructByName (Tikhon Fedulov)
|
||||
* Fix: update description cache after exec prepare (James Hartig)
|
||||
* Fix: pipeline checks if it is closed (James Hartig and Ryan Fowler)
|
||||
* Fix: normalize timeout / context errors during TLS startup (Samuel Stauffer)
|
||||
* Add OnPgError for easier centralized error handling (James Hartig)
|
||||
|
||||
# 5.5.1 (December 9, 2023)
|
||||
|
||||
* Add CopyFromFunc helper function. (robford)
|
||||
* Add PgConn.Deallocate method that uses PostgreSQL protocol Close message.
|
||||
* pgx uses new PgConn.Deallocate method. This allows deallocating statements to work in a failed transaction. This fixes a case where the prepared statement map could become invalid.
|
||||
* Fix: Prefer driver.Valuer over json.Marshaler for json fields. (Jacopo)
|
||||
* Fix: simple protocol SQL sanitizer previously panicked if an invalid $0 placeholder was used. This now returns an error instead. (maksymnevajdev)
|
||||
* Add pgtype.Numeric.ScanScientific (Eshton Robateau)
|
||||
|
||||
# 5.5.0 (November 4, 2023)
|
||||
|
||||
* Add CollectExactlyOneRow. (Julien GOTTELAND)
|
||||
* Add OpenDBFromPool to create *database/sql.DB from *pgxpool.Pool. (Lev Zakharov)
|
||||
* Prepare can automatically choose statement name based on sql. This makes it easier to explicitly manage prepared statements.
|
||||
* Statement cache now uses deterministic, stable statement names.
|
||||
* database/sql prepared statement names are deterministically generated.
|
||||
* Fix: SendBatch wasn't respecting context cancellation.
|
||||
* Fix: Timeout error from pipeline is now normalized.
|
||||
* Fix: database/sql encoding json.RawMessage to []byte.
|
||||
* CancelRequest: Wait for the cancel request to be acknowledged by the server. This should improve PgBouncer compatibility. (Anton Levakin)
|
||||
* stdlib: Use Ping instead of CheckConn in ResetSession
|
||||
* Add json.Marshaler and json.Unmarshaler for Float4, Float8 (Kirill Mironov)
|
||||
|
||||
# 5.4.3 (August 5, 2023)
|
||||
|
||||
* Fix: QCharArrayOID was defined with the wrong OID (Christoph Engelbert)
|
||||
* Fix: connect_timeout for sslmode=allow|prefer (smaher-edb)
|
||||
* Fix: pgxpool: background health check cannot overflow pool
|
||||
* Fix: Check for nil in defer when sending batch (recover properly from panic)
|
||||
* Fix: json scan of non-string pointer to pointer
|
||||
* Fix: zeronull.Timestamptz should use pgtype.Timestamptz
|
||||
* Fix: NewConnsCount was not correctly counting connections created by Acquire directly. (James Hartig)
|
||||
* RowTo(AddrOf)StructByPos ignores fields with "-" db tag
|
||||
* Optimization: improve text format numeric parsing (horpto)
|
||||
|
||||
# 5.4.2 (July 11, 2023)
|
||||
|
||||
* Fix: RowScanner errors are fatal to Rows
|
||||
* Fix: Enable failover efforts when pg_hba.conf disallows non-ssl connections (Brandon Kauffman)
|
||||
* Hstore text codec internal improvements (Evan Jones)
|
||||
* Fix: Stop timers for background reader when not in use. Fixes memory leak when closing connections (Adrian-Stefan Mares)
|
||||
* Fix: Stop background reader as soon as possible.
|
||||
* Add PgConn.SyncConn(). This combined with the above fix makes it safe to directly use the underlying net.Conn.
|
||||
|
||||
# 5.4.1 (June 18, 2023)
|
||||
|
||||
* Fix: concurrency bug with pgtypeDefaultMap and simple protocol (Lev Zakharov)
|
||||
* Add TxOptions.BeginQuery to allow overriding the default BEGIN query
|
||||
|
||||
# 5.4.0 (June 14, 2023)
|
||||
|
||||
* Replace platform specific syscalls for non-blocking IO with more traditional goroutines and deadlines. This returns to the v4 approach with some additional improvements and fixes. This restores the ability to use a pgx.Conn over an ssh.Conn as well as other non-TCP or Unix socket connections. In addition, it is a significantly simpler implementation that is less likely to have cross platform issues.
|
||||
* Optimization: The default type registrations are now shared among all connections. This saves about 100KB of memory per connection. `pgtype.Type` and `pgtype.Codec` values are now required to be immutable after registration. This was already necessary in most cases but wasn't documented until now. (Lev Zakharov)
|
||||
* Fix: Ensure pgxpool.Pool.QueryRow.Scan releases connection on panic
|
||||
* CancelRequest: don't try to read the reply (Nicola Murino)
|
||||
* Fix: correctly handle bool type aliases (Wichert Akkerman)
|
||||
* Fix: pgconn.CancelRequest: Fix unix sockets: don't use RemoteAddr()
|
||||
* Fix: pgx.Conn memory leak with prepared statement caching (Evan Jones)
|
||||
* Add BeforeClose to pgxpool.Pool (Evan Cordell)
|
||||
* Fix: various hstore fixes and optimizations (Evan Jones)
|
||||
* Fix: RowToStructByPos with embedded unexported struct
|
||||
* Support different bool string representations (Lev Zakharov)
|
||||
* Fix: error when using BatchResults.Exec on a select that returns an error after some rows.
|
||||
* Fix: pipelineBatchResults.Exec() not returning error from ResultReader
|
||||
* Fix: pipeline batch results not closing pipeline when error occurs while reading directly from results instead of using
|
||||
a callback.
|
||||
* Fix: scanning a table type into a struct
|
||||
* Fix: scan array of record to pointer to slice of struct
|
||||
* Fix: handle null for json (Cemre Mengu)
|
||||
* Batch Query callback is called even when there is an error
|
||||
* Add RowTo(AddrOf)StructByNameLax (Audi P. Risa P)
|
||||
|
||||
# 5.3.1 (February 27, 2023)
|
||||
|
||||
* Fix: Support v4 and v5 stdlib in same program (Tomáš Procházka)
|
||||
* Fix: sql.Scanner not being used in certain cases
|
||||
* Add text format jsonpath support
|
||||
* Fix: fake non-blocking read adaptive wait time
|
||||
|
||||
# 5.3.0 (February 11, 2023)
|
||||
|
||||
* Fix: json values work with sql.Scanner
|
||||
* Fixed / improved error messages (Mark Chambers and Yevgeny Pats)
|
||||
* Fix: support scan into single dimensional arrays
|
||||
* Fix: MaxConnLifetimeJitter setting actually jitter (Ben Weintraub)
|
||||
* Fix: driver.Value representation of bytea should be []byte not string
|
||||
* Fix: better handling of unregistered OIDs
|
||||
* CopyFrom can use query cache to avoid extra round trip to get OIDs (Alejandro Do Nascimento Mora)
|
||||
* Fix: encode to json ignoring driver.Valuer
|
||||
* Support sql.Scanner on renamed base type
|
||||
* Fix: pgtype.Numeric text encoding of negative numbers (Mark Chambers)
|
||||
* Fix: connect with multiple hostnames when one can't be resolved
|
||||
* Upgrade puddle to remove dependency on uber/atomic and fix alignment issue on 32-bit platform
|
||||
* Fix: scanning json column into **string
|
||||
* Multiple reductions in memory allocations
|
||||
* Fake non-blocking read adapts its max wait time
|
||||
* Improve CopyFrom performance and reduce memory usage
|
||||
* Fix: encode []any to array
|
||||
* Fix: LoadType for composite with dropped attributes (Felix Röhrich)
|
||||
* Support v4 and v5 stdlib in same program
|
||||
* Fix: text format array decoding with string of "NULL"
|
||||
* Prefer binary format for arrays
|
||||
|
||||
# 5.2.0 (December 5, 2022)
|
||||
|
||||
* `tracelog.TraceLog` implements the pgx.PrepareTracer interface. (Vitalii Solodilov)
|
||||
* Optimize creating begin transaction SQL string (Petr Evdokimov and ksco)
|
||||
* `Conn.LoadType` supports range and multirange types (Vitalii Solodilov)
|
||||
* Fix scan `uint` and `uint64` `ScanNumeric`. This resolves a PostgreSQL `numeric` being incorrectly scanned into `uint` and `uint64`.
|
||||
|
||||
# 5.1.1 (November 17, 2022)
|
||||
|
||||
* Fix simple query sanitizer where query text contains a Unicode replacement character.
|
||||
* Remove erroneous `name` argument from `DeallocateAll()`. Technically, this is a breaking change, but given that method was only added 5 days ago this change was accepted. (Bodo Kaiser)
|
||||
|
||||
# 5.1.0 (November 12, 2022)
|
||||
|
||||
* Update puddle to v2.1.2. This resolves a race condition and a deadlock in pgxpool.
|
||||
* `QueryRewriter.RewriteQuery` now returns an error. Technically, this is a breaking change for any external implementers, but given the minimal likelihood that there are actually any external implementers this change was accepted.
|
||||
* Expose `GetSSLPassword` support to pgx.
|
||||
* Fix encode `ErrorResponse` unknown field handling. This would only affect pgproto3 being used directly as a proxy with a non-PostgreSQL server that included additional error fields.
|
||||
* Fix date text format encoding with 5 digit years.
|
||||
* Fix date values passed to a `sql.Scanner` as `string` instead of `time.Time`.
|
||||
* DateCodec.DecodeValue can return `pgtype.InfinityModifier` instead of `string` for infinite values. This now matches the behavior of the timestamp types.
|
||||
* Add domain type support to `Conn.LoadType()`.
|
||||
* Add `RowToStructByName` and `RowToAddrOfStructByName`. (Pavlo Golub)
|
||||
* Add `Conn.DeallocateAll()` to clear all prepared statements including the statement cache. (Bodo Kaiser)
|
||||
|
||||
# 5.0.4 (October 24, 2022)
|
||||
|
||||
* Fix: CollectOneRow prefers PostgreSQL error over pgx.ErrorNoRows
|
||||
* Fix: some reflect Kind checks to first check for nil
|
||||
* Bump golang.org/x/text dependency to placate snyk
|
||||
* Fix: RowToStructByPos on structs with multiple anonymous sub-structs (Baptiste Fontaine)
|
||||
* Fix: Exec checks if tx is closed
|
||||
|
||||
# 5.0.3 (October 14, 2022)
|
||||
|
||||
* Fix `driver.Valuer` handling edge cases that could cause infinite loop or crash
|
||||
|
||||
# v5.0.2 (October 8, 2022)
|
||||
|
||||
* Fix date encoding in text format to always use 2 digits for month and day
|
||||
* Prefer driver.Valuer over wrap plans when encoding
|
||||
* Fix scan to pointer to pointer to renamed type
|
||||
* Allow scanning NULL even if PG and Go types are incompatible
|
||||
|
||||
# v5.0.1 (September 24, 2022)
|
||||
|
||||
* Fix 32-bit atomic usage
|
||||
* Add MarshalJSON for Float8 (yogipristiawan)
|
||||
* Add `[` and `]` to text encoding of `Lseg`
|
||||
* Fix sqlScannerWrapper NULL handling
|
||||
|
||||
# v5.0.0 (September 17, 2022)
|
||||
|
||||
## Merged Packages
|
||||
|
||||
`github.com/jackc/pgtype`, `github.com/jackc/pgconn`, and `github.com/jackc/pgproto3` are now included in the main
|
||||
`github.com/jackc/pgx` repository. Previously there was confusion as to where issues should be reported, additional
|
||||
release work due to releasing multiple packages, and less clear changelogs.
|
||||
|
||||
## pgconn
|
||||
|
||||
`CommandTag` is now an opaque type instead of directly exposing an underlying `[]byte`.
|
||||
|
||||
The return value `ResultReader.Values()` is no longer safe to retain a reference to after a subsequent call to `NextRow()` or `Close()`.
|
||||
|
||||
`Trace()` method adds low level message tracing similar to the `PQtrace` function in `libpq`.
|
||||
|
||||
pgconn now uses non-blocking IO. This is a significant internal restructuring, but it should not cause any visible changes on its own. However, it is important in implementing other new features.
|
||||
|
||||
`CheckConn()` checks a connection's liveness by doing a non-blocking read. This can be used to detect database restarts or network interruptions without executing a query or a ping.
|
||||
|
||||
pgconn now supports pipeline mode.
|
||||
|
||||
`*PgConn.ReceiveResults` removed. Use pipeline mode instead.
|
||||
|
||||
`Timeout()` no longer considers `context.Canceled` as a timeout error. `context.DeadlineExceeded` still is considered a timeout error.
|
||||
|
||||
## pgxpool
|
||||
|
||||
`Connect` and `ConnectConfig` have been renamed to `New` and `NewWithConfig` respectively. The `LazyConnect` option has been removed. Pools always lazily connect.
|
||||
|
||||
## pgtype
|
||||
|
||||
The `pgtype` package has been significantly changed.
|
||||
|
||||
### NULL Representation
|
||||
|
||||
Previously, types had a `Status` field that could be `Undefined`, `Null`, or `Present`. This has been changed to a
|
||||
`Valid` `bool` field to harmonize with how `database/sql` represents `NULL` and to make the zero value useable.
|
||||
|
||||
Previously, a type that implemented `driver.Valuer` would have the `Value` method called even on a nil pointer. All nils
|
||||
whether typed or untyped now represent `NULL`.
|
||||
|
||||
### Codec and Value Split
|
||||
|
||||
Previously, the type system combined decoding and encoding values with the value types. e.g. Type `Int8` both handled
|
||||
encoding and decoding the PostgreSQL representation and acted as a value object. This caused some difficulties when
|
||||
there was not an exact 1 to 1 relationship between the Go types and the PostgreSQL types For example, scanning a
|
||||
PostgreSQL binary `numeric` into a Go `float64` was awkward (see https://github.com/jackc/pgtype/issues/147). This
|
||||
concepts have been separated. A `Codec` only has responsibility for encoding and decoding values. Value types are
|
||||
generally defined by implementing an interface that a particular `Codec` understands (e.g. `PointScanner` and
|
||||
`PointValuer` for the PostgreSQL `point` type).
|
||||
|
||||
### Array Types
|
||||
|
||||
All array types are now handled by `ArrayCodec` instead of using code generation for each new array type. This also
|
||||
means that less common array types such as `point[]` are now supported. `Array[T]` supports PostgreSQL multi-dimensional
|
||||
arrays.
|
||||
|
||||
### Composite Types
|
||||
|
||||
Composite types must be registered before use. `CompositeFields` may still be used to construct and destruct composite
|
||||
values, but any type may now implement `CompositeIndexGetter` and `CompositeIndexScanner` to be used as a composite.
|
||||
|
||||
### Range Types
|
||||
|
||||
Range types are now handled with types `RangeCodec` and `Range[T]`. This allows additional user defined range types to
|
||||
easily be handled. Multirange types are handled similarly with `MultirangeCodec` and `Multirange[T]`.
|
||||
|
||||
### pgxtype
|
||||
|
||||
`LoadDataType` moved to `*Conn` as `LoadType`.
|
||||
|
||||
### Bytea
|
||||
|
||||
The `Bytea` and `GenericBinary` types have been replaced. Use the following instead:
|
||||
|
||||
* `[]byte` - For normal usage directly use `[]byte`.
|
||||
* `DriverBytes` - Uses driver memory only available until next database method call. Avoids a copy and an allocation.
|
||||
* `PreallocBytes` - Uses preallocated byte slice to avoid an allocation.
|
||||
* `UndecodedBytes` - Avoids any decoding. Allows working with raw bytes.
|
||||
|
||||
### Dropped lib/pq Support
|
||||
|
||||
`pgtype` previously supported and was tested against [lib/pq](https://github.com/lib/pq). While it will continue to work
|
||||
in most cases this is no longer supported.
|
||||
|
||||
### database/sql Scan
|
||||
|
||||
Previously, most `Scan` implementations would convert `[]byte` to `string` automatically to decode a text value. Now
|
||||
only `string` is handled. This is to allow the possibility of future binary support in `database/sql` mode by
|
||||
considering `[]byte` to be binary format and `string` text format. This change should have no effect for any use with
|
||||
`pgx`. The previous behavior was only necessary for `lib/pq` compatibility.
|
||||
|
||||
Added `*Map.SQLScanner` to create a `sql.Scanner` for types such as `[]int32` and `Range[T]` that do not implement
|
||||
`sql.Scanner` directly.
|
||||
|
||||
### Number Type Fields Include Bit size
|
||||
|
||||
`Int2`, `Int4`, `Int8`, `Float4`, `Float8`, and `Uint32` fields now include bit size. e.g. `Int` is renamed to `Int64`.
|
||||
This matches the convention set by `database/sql`. In addition, for comparable types like `pgtype.Int8` and
|
||||
`sql.NullInt64` the structures are identical. This means they can be directly converted one to another.
|
||||
|
||||
### 3rd Party Type Integrations
|
||||
|
||||
* Extracted integrations with https://github.com/shopspring/decimal and https://github.com/gofrs/uuid to
|
||||
https://github.com/jackc/pgx-shopspring-decimal and https://github.com/jackc/pgx-gofrs-uuid respectively. This trims
|
||||
the pgx dependency tree.
|
||||
|
||||
### Other Changes
|
||||
|
||||
* `Bit` and `Varbit` are both replaced by the `Bits` type.
|
||||
* `CID`, `OID`, `OIDValue`, and `XID` are replaced by the `Uint32` type.
|
||||
* `Hstore` is now defined as `map[string]*string`.
|
||||
* `JSON` and `JSONB` types removed. Use `[]byte` or `string` directly.
|
||||
* `QChar` type removed. Use `rune` or `byte` directly.
|
||||
* `Inet` and `Cidr` types removed. Use `netip.Addr` and `netip.Prefix` directly. These types are more memory efficient than the previous `net.IPNet`.
|
||||
* `Macaddr` type removed. Use `net.HardwareAddr` directly.
|
||||
* Renamed `pgtype.ConnInfo` to `pgtype.Map`.
|
||||
* Renamed `pgtype.DataType` to `pgtype.Type`.
|
||||
* Renamed `pgtype.None` to `pgtype.Finite`.
|
||||
* `RegisterType` now accepts a `*Type` instead of `Type`.
|
||||
* Assorted array helper methods and types made private.
|
||||
|
||||
## stdlib
|
||||
|
||||
* Removed `AcquireConn` and `ReleaseConn` as that functionality has been built in since Go 1.13.
|
||||
|
||||
## Reduced Memory Usage by Reusing Read Buffers
|
||||
|
||||
Previously, the connection read buffer would allocate large chunks of memory and never reuse them. This allowed
|
||||
transferring ownership to anything such as scanned values without incurring an additional allocation and memory copy.
|
||||
However, this came at the cost of overall increased memory allocation size. But worse it was also possible to pin large
|
||||
chunks of memory by retaining a reference to a small value that originally came directly from the read buffer. Now
|
||||
ownership remains with the read buffer and anything needing to retain a value must make a copy.
|
||||
|
||||
## Query Execution Modes
|
||||
|
||||
Control over automatic prepared statement caching and simple protocol use are now combined into query execution mode.
|
||||
See documentation for `QueryExecMode`.
|
||||
|
||||
## QueryRewriter Interface and NamedArgs
|
||||
|
||||
pgx now supports named arguments with the `NamedArgs` type. This is implemented via the new `QueryRewriter` interface which
|
||||
allows arbitrary rewriting of query SQL and arguments.
|
||||
|
||||
## RowScanner Interface
|
||||
|
||||
The `RowScanner` interface allows a single argument to Rows.Scan to scan the entire row.
|
||||
|
||||
## Rows Result Helpers
|
||||
|
||||
* `CollectRows` and `RowTo*` functions simplify collecting results into a slice.
|
||||
* `CollectOneRow` collects one row using `RowTo*` functions.
|
||||
* `ForEachRow` simplifies scanning each row and executing code using the scanned values. `ForEachRow` replaces `QueryFunc`.
|
||||
|
||||
## Tx Helpers
|
||||
|
||||
Rather than every type that implemented `Begin` or `BeginTx` methods also needing to implement `BeginFunc` and
|
||||
`BeginTxFunc` these methods have been converted to functions that take a db that implements `Begin` or `BeginTx`.
|
||||
|
||||
## Improved Batch Query Ergonomics
|
||||
|
||||
Previously, the code for building a batch went in one place before the call to `SendBatch`, and the code for reading the
|
||||
results went in one place after the call to `SendBatch`. This could make it difficult to match up the query and the code
|
||||
to handle the results. Now `Queue` returns a `QueuedQuery` which has methods `Query`, `QueryRow`, and `Exec` which can
|
||||
be used to register a callback function that will handle the result. Callback functions are called automatically when
|
||||
`BatchResults.Close` is called.
|
||||
|
||||
## SendBatch Uses Pipeline Mode When Appropriate
|
||||
|
||||
Previously, a batch with 10 unique parameterized statements executed 100 times would entail 11 network round trips. 1
|
||||
for each prepare / describe and 1 for executing them all. Now pipeline mode is used to prepare / describe all statements
|
||||
in a single network round trip. So it would only take 2 round trips.
|
||||
|
||||
## Tracing and Logging
|
||||
|
||||
Internal logging support has been replaced with tracing hooks. This allows custom tracing integration with tools like OpenTelemetry. Package tracelog provides an adapter for pgx v4 loggers to act as a tracer.
|
||||
|
||||
All integrations with 3rd party loggers have been extracted to separate repositories. This trims the pgx dependency
|
||||
tree.
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
# Contributing
|
||||
|
||||
## Discuss Significant Changes
|
||||
|
||||
Before you invest a significant amount of time on a change, please create a discussion or issue describing your
|
||||
proposal. This will help to ensure your proposed change has a reasonable chance of being merged.
|
||||
|
||||
## Avoid Dependencies
|
||||
|
||||
Adding a dependency is a big deal. While on occasion a new dependency may be accepted, the default answer to any change
|
||||
that adds a dependency is no.
|
||||
|
||||
## Development Environment Setup
|
||||
|
||||
pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the `PGX_TEST_DATABASE`
|
||||
environment variable. The `PGX_TEST_DATABASE` environment variable can either be a URL or key-value pairs. In addition,
|
||||
the standard `PG*` environment variables will be respected. Consider using [direnv](https://github.com/direnv/direnv) to
|
||||
simplify environment variable handling.
|
||||
|
||||
### Using an Existing PostgreSQL Cluster
|
||||
|
||||
If you already have a PostgreSQL development server this is the quickest way to start and run the majority of the pgx
|
||||
test suite. Some tests will be skipped that require server configuration changes (e.g. those testing different
|
||||
authentication methods).
|
||||
|
||||
Create and setup a test database:
|
||||
|
||||
```
|
||||
export PGDATABASE=pgx_test
|
||||
createdb
|
||||
psql -c 'create extension hstore;'
|
||||
psql -c 'create extension ltree;'
|
||||
psql -c 'create domain uint64 as numeric(20,0);'
|
||||
```
|
||||
|
||||
Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some installation methods
|
||||
such as Homebrew do not.
|
||||
|
||||
```
|
||||
createuser -s postgres
|
||||
```
|
||||
|
||||
Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run the tests.
|
||||
|
||||
```
|
||||
export PGX_TEST_DATABASE="host=/private/tmp database=pgx_test"
|
||||
go test ./...
|
||||
```
|
||||
|
||||
This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing different connection methods).
|
||||
|
||||
### Creating a New PostgreSQL Cluster Exclusively for Testing
|
||||
|
||||
The following environment variables need to be set both for initial setup and whenever the tests are run. (direnv is
|
||||
highly recommended). Depending on your platform, you may need to change the host for `PGX_TEST_UNIX_SOCKET_CONN_STRING`.
|
||||
|
||||
```
|
||||
export PGPORT=5015
|
||||
export PGUSER=postgres
|
||||
export PGDATABASE=pgx_test
|
||||
export POSTGRESQL_DATA_DIR=postgresql
|
||||
|
||||
export PGX_TEST_DATABASE="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
|
||||
export PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/private/tmp database=pgx_test"
|
||||
export PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
|
||||
export PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_scram password=secret database=pgx_test"
|
||||
export PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret"
|
||||
export PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_pw password=secret"
|
||||
export PGX_TEST_TLS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem"
|
||||
export PGX_SSL_PASSWORD=certpw
|
||||
export PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost user=pgx_sslcert sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test sslcert=`pwd`/.testdb/pgx_sslcert.crt sslkey=`pwd`/.testdb/pgx_sslcert.key"
|
||||
```
|
||||
|
||||
Create a new database cluster.
|
||||
|
||||
```
|
||||
initdb --locale=en_US -E UTF-8 --username=postgres .testdb/$POSTGRESQL_DATA_DIR
|
||||
|
||||
echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
|
||||
echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
|
||||
cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf
|
||||
cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf
|
||||
|
||||
cd .testdb
|
||||
|
||||
# Generate CA, server, and encrypted client certificates.
|
||||
go run ../testsetup/generate_certs.go
|
||||
|
||||
# Copy certificates to server directory and set permissions.
|
||||
cp ca.pem $POSTGRESQL_DATA_DIR/root.crt
|
||||
cp localhost.key $POSTGRESQL_DATA_DIR/server.key
|
||||
chmod 600 $POSTGRESQL_DATA_DIR/server.key
|
||||
cp localhost.crt $POSTGRESQL_DATA_DIR/server.crt
|
||||
|
||||
cd ..
|
||||
```
|
||||
|
||||
|
||||
Start the new cluster. This will be necessary whenever you are running pgx tests.
|
||||
|
||||
```
|
||||
postgres -D .testdb/$POSTGRESQL_DATA_DIR
|
||||
```
|
||||
|
||||
Setup the test database in the new cluster.
|
||||
|
||||
```
|
||||
createdb
|
||||
psql --no-psqlrc -f testsetup/postgresql_setup.sql
|
||||
```
|
||||
|
||||
### PgBouncer
|
||||
|
||||
There are tests specific for PgBouncer that will be executed if `PGX_TEST_PGBOUNCER_CONN_STRING` is set.
|
||||
|
||||
### Optional Tests
|
||||
|
||||
pgx supports multiple connection types and means of authentication. These tests are optional. They will only run if the
|
||||
appropriate environment variables are set. In addition, there may be tests specific to particular PostgreSQL versions,
|
||||
non-PostgreSQL servers (e.g. CockroachDB), or connection poolers (e.g. PgBouncer). `go test ./... -v | grep SKIP` to see
|
||||
if any tests are being skipped.
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
Copyright (c) 2013-2021 Jack Christensen
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
[](https://pkg.go.dev/github.com/jackc/pgx/v5)
|
||||
[](https://github.com/jackc/pgx/actions/workflows/ci.yml)
|
||||
|
||||
# pgx - PostgreSQL Driver and Toolkit
|
||||
|
||||
pgx is a pure Go driver and toolkit for PostgreSQL.
|
||||
|
||||
The pgx driver is a low-level, high performance interface that exposes PostgreSQL-specific features such as `LISTEN` /
|
||||
`NOTIFY` and `COPY`. It also includes an adapter for the standard `database/sql` interface.
|
||||
|
||||
The toolkit component is a related set of packages that implement PostgreSQL functionality such as parsing the wire protocol
|
||||
and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers,
|
||||
proxies, load balancers, logical replication clients, etc.
|
||||
|
||||
## Example Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// urlExample := "postgres://username:password@localhost:5432/database_name"
|
||||
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer conn.Close(context.Background())
|
||||
|
||||
var name string
|
||||
var weight int64
|
||||
err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Println(name, weight)
|
||||
}
|
||||
```
|
||||
|
||||
See the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx) for more information.
|
||||
|
||||
## Features
|
||||
|
||||
* Support for approximately 70 different PostgreSQL types
|
||||
* Automatic statement preparation and caching
|
||||
* Batch queries
|
||||
* Single-round trip query mode
|
||||
* Full TLS connection control
|
||||
* Binary format support for custom types (allows for much quicker encoding/decoding)
|
||||
* `COPY` protocol support for faster bulk data loads
|
||||
* Tracing and logging support
|
||||
* Connection pool with after-connect hook for arbitrary connection setup
|
||||
* `LISTEN` / `NOTIFY`
|
||||
* Conversion of PostgreSQL arrays to Go slice mappings for integers, floats, and strings
|
||||
* `hstore` support
|
||||
* `json` and `jsonb` support
|
||||
* Maps `inet` and `cidr` PostgreSQL types to `netip.Addr` and `netip.Prefix`
|
||||
* Large object support
|
||||
* NULL mapping to pointer to pointer
|
||||
* Supports `database/sql.Scanner` and `database/sql/driver.Valuer` interfaces for custom types
|
||||
* Notice response handling
|
||||
* Simulated nested transactions with savepoints
|
||||
|
||||
## Choosing Between the pgx and database/sql Interfaces
|
||||
|
||||
The pgx interface is faster. Many PostgreSQL specific features such as `LISTEN` / `NOTIFY` and `COPY` are not available
|
||||
through the `database/sql` interface.
|
||||
|
||||
The pgx interface is recommended when:
|
||||
|
||||
1. The application only targets PostgreSQL.
|
||||
2. No other libraries that require `database/sql` are in use.
|
||||
|
||||
It is also possible to use the `database/sql` interface and convert a connection to the lower-level pgx interface as needed.
|
||||
|
||||
## Testing
|
||||
|
||||
See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions.
|
||||
|
||||
## Architecture
|
||||
|
||||
See the presentation at Golang Estonia, [PGX Top to Bottom](https://www.youtube.com/watch?v=sXMSWhcHCf8) for a description of pgx architecture.
|
||||
|
||||
## Supported Go and PostgreSQL Versions
|
||||
|
||||
pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases and for [PostgreSQL](https://www.postgresql.org/support/versioning/) the major releases in the last 5 years. This means pgx supports Go 1.21 and higher and PostgreSQL 12 and higher. pgx also is tested against the latest version of [CockroachDB](https://www.cockroachlabs.com/product/).
|
||||
|
||||
## Version Policy
|
||||
|
||||
pgx follows semantic versioning for the documented public API on stable releases. `v5` is the latest stable major version.
|
||||
|
||||
## PGX Family Libraries
|
||||
|
||||
### [github.com/jackc/pglogrepl](https://github.com/jackc/pglogrepl)
|
||||
|
||||
pglogrepl provides functionality to act as a client for PostgreSQL logical replication.
|
||||
|
||||
### [github.com/jackc/pgmock](https://github.com/jackc/pgmock)
|
||||
|
||||
pgmock offers the ability to create a server that mocks the PostgreSQL wire protocol. This is used internally to test pgx by purposely inducing unusual errors. pgproto3 and pgmock together provide most of the foundational tooling required to implement a PostgreSQL proxy or MitM (such as for a custom connection pooler).
|
||||
|
||||
### [github.com/jackc/tern](https://github.com/jackc/tern)
|
||||
|
||||
tern is a stand-alone SQL migration system.
|
||||
|
||||
### [github.com/jackc/pgerrcode](https://github.com/jackc/pgerrcode)
|
||||
|
||||
pgerrcode contains constants for the PostgreSQL error codes.
|
||||
|
||||
## Adapters for 3rd Party Types
|
||||
|
||||
* [github.com/jackc/pgx-gofrs-uuid](https://github.com/jackc/pgx-gofrs-uuid)
|
||||
* [github.com/jackc/pgx-shopspring-decimal](https://github.com/jackc/pgx-shopspring-decimal)
|
||||
* [github.com/twpayne/pgx-geos](https://github.com/twpayne/pgx-geos) ([PostGIS](https://postgis.net/) and [GEOS](https://libgeos.org/) via [go-geos](https://github.com/twpayne/go-geos))
|
||||
* [github.com/vgarvardt/pgx-google-uuid](https://github.com/vgarvardt/pgx-google-uuid)
|
||||
|
||||
|
||||
## Adapters for 3rd Party Tracers
|
||||
|
||||
* [github.com/jackhopner/pgx-xray-tracer](https://github.com/jackhopner/pgx-xray-tracer)
|
||||
|
||||
## Adapters for 3rd Party Loggers
|
||||
|
||||
These adapters can be used with the tracelog package.
|
||||
|
||||
* [github.com/jackc/pgx-go-kit-log](https://github.com/jackc/pgx-go-kit-log)
|
||||
* [github.com/jackc/pgx-log15](https://github.com/jackc/pgx-log15)
|
||||
* [github.com/jackc/pgx-logrus](https://github.com/jackc/pgx-logrus)
|
||||
* [github.com/jackc/pgx-zap](https://github.com/jackc/pgx-zap)
|
||||
* [github.com/jackc/pgx-zerolog](https://github.com/jackc/pgx-zerolog)
|
||||
* [github.com/mcosta74/pgx-slog](https://github.com/mcosta74/pgx-slog)
|
||||
* [github.com/kataras/pgx-golog](https://github.com/kataras/pgx-golog)
|
||||
|
||||
## 3rd Party Libraries with PGX Support
|
||||
|
||||
### [github.com/pashagolub/pgxmock](https://github.com/pashagolub/pgxmock)
|
||||
|
||||
pgxmock is a mock library implementing pgx interfaces.
|
||||
pgxmock has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection.
|
||||
|
||||
### [github.com/georgysavva/scany](https://github.com/georgysavva/scany)
|
||||
|
||||
Library for scanning data from a database into Go structs and more.
|
||||
|
||||
### [github.com/vingarcia/ksql](https://github.com/vingarcia/ksql)
|
||||
|
||||
A carefully designed SQL client for making using SQL easier,
|
||||
more productive, and less error-prone on Golang.
|
||||
|
||||
### [github.com/otan/gopgkrb5](https://github.com/otan/gopgkrb5)
|
||||
|
||||
Adds GSSAPI / Kerberos authentication support.
|
||||
|
||||
### [github.com/wcamarao/pmx](https://github.com/wcamarao/pmx)
|
||||
|
||||
Explicit data mapping and scanning library for Go structs and slices.
|
||||
|
||||
### [github.com/stephenafamo/scan](https://github.com/stephenafamo/scan)
|
||||
|
||||
Type safe and flexible package for scanning database data into Go types.
|
||||
Supports, structs, maps, slices and custom mapping functions.
|
||||
|
||||
### [github.com/z0ne-dev/mgx](https://github.com/z0ne-dev/mgx)
|
||||
|
||||
Code first migration library for native pgx (no database/sql abstraction).
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
require "erb"
|
||||
|
||||
rule '.go' => '.go.erb' do |task|
|
||||
erb = ERB.new(File.read(task.source))
|
||||
File.write(task.name, "// Do not edit. Generated from #{task.source}\n" + erb.result(binding))
|
||||
sh "goimports", "-w", task.name
|
||||
end
|
||||
|
||||
generated_code_files = [
|
||||
"pgtype/int.go",
|
||||
"pgtype/int_test.go",
|
||||
"pgtype/integration_benchmark_test.go",
|
||||
"pgtype/zeronull/int.go",
|
||||
"pgtype/zeronull/int_test.go"
|
||||
]
|
||||
|
||||
desc "Generate code"
|
||||
task generate: generated_code_files
|
||||
+443
@@ -0,0 +1,443 @@
|
||||
package pgx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
// QueuedQuery is a query that has been queued for execution via a Batch.
|
||||
type QueuedQuery struct {
|
||||
SQL string
|
||||
Arguments []any
|
||||
Fn batchItemFunc
|
||||
sd *pgconn.StatementDescription
|
||||
}
|
||||
|
||||
type batchItemFunc func(br BatchResults) error
|
||||
|
||||
// Query sets fn to be called when the response to qq is received.
|
||||
func (qq *QueuedQuery) Query(fn func(rows Rows) error) {
|
||||
qq.Fn = func(br BatchResults) error {
|
||||
rows, _ := br.Query()
|
||||
defer rows.Close()
|
||||
|
||||
err := fn(rows)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
return rows.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// Query sets fn to be called when the response to qq is received.
|
||||
func (qq *QueuedQuery) QueryRow(fn func(row Row) error) {
|
||||
qq.Fn = func(br BatchResults) error {
|
||||
row := br.QueryRow()
|
||||
return fn(row)
|
||||
}
|
||||
}
|
||||
|
||||
// Exec sets fn to be called when the response to qq is received.
|
||||
func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) {
|
||||
qq.Fn = func(br BatchResults) error {
|
||||
ct, err := br.Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return fn(ct)
|
||||
}
|
||||
}
|
||||
|
||||
// Batch queries are a way of bundling multiple queries together to avoid
|
||||
// unnecessary network round trips. A Batch must only be sent once.
|
||||
type Batch struct {
|
||||
QueuedQueries []*QueuedQuery
|
||||
}
|
||||
|
||||
// Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. The only pgx option
|
||||
// argument that is supported is QueryRewriter. Queries are executed using the connection's DefaultQueryExecMode.
|
||||
//
|
||||
// While query can contain multiple statements if the connection's DefaultQueryExecMode is QueryModeSimple, this should
|
||||
// be avoided. QueuedQuery.Fn must not be set as it will only be called for the first query. That is, QueuedQuery.Query,
|
||||
// QueuedQuery.QueryRow, and QueuedQuery.Exec must not be called. In addition, any error messages or tracing that
|
||||
// include the current query may reference the wrong query.
|
||||
func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery {
|
||||
qq := &QueuedQuery{
|
||||
SQL: query,
|
||||
Arguments: arguments,
|
||||
}
|
||||
b.QueuedQueries = append(b.QueuedQueries, qq)
|
||||
return qq
|
||||
}
|
||||
|
||||
// Len returns number of queries that have been queued so far.
|
||||
func (b *Batch) Len() int {
|
||||
return len(b.QueuedQueries)
|
||||
}
|
||||
|
||||
type BatchResults interface {
|
||||
// Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec. Prefer
|
||||
// calling Exec on the QueuedQuery.
|
||||
Exec() (pgconn.CommandTag, error)
|
||||
|
||||
// Query reads the results from the next query in the batch as if the query has been sent with Conn.Query. Prefer
|
||||
// calling Query on the QueuedQuery.
|
||||
Query() (Rows, error)
|
||||
|
||||
// QueryRow reads the results from the next query in the batch as if the query has been sent with Conn.QueryRow.
|
||||
// Prefer calling QueryRow on the QueuedQuery.
|
||||
QueryRow() Row
|
||||
|
||||
// Close closes the batch operation. All unread results are read and any callback functions registered with
|
||||
// QueuedQuery.Query, QueuedQuery.QueryRow, or QueuedQuery.Exec will be called. If a callback function returns an
|
||||
// error or the batch encounters an error subsequent callback functions will not be called.
|
||||
//
|
||||
// Close must be called before the underlying connection can be used again. Any error that occurred during a batch
|
||||
// operation may have made it impossible to resyncronize the connection with the server. In this case the underlying
|
||||
// connection will have been closed.
|
||||
//
|
||||
// Close is safe to call multiple times. If it returns an error subsequent calls will return the same error. Callback
|
||||
// functions will not be rerun.
|
||||
Close() error
|
||||
}
|
||||
|
||||
type batchResults struct {
|
||||
ctx context.Context
|
||||
conn *Conn
|
||||
mrr *pgconn.MultiResultReader
|
||||
err error
|
||||
b *Batch
|
||||
qqIdx int
|
||||
closed bool
|
||||
endTraced bool
|
||||
}
|
||||
|
||||
// Exec reads the results from the next query in the batch as if the query has been sent with Exec.
|
||||
func (br *batchResults) Exec() (pgconn.CommandTag, error) {
|
||||
if br.err != nil {
|
||||
return pgconn.CommandTag{}, br.err
|
||||
}
|
||||
if br.closed {
|
||||
return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
|
||||
}
|
||||
|
||||
query, arguments, _ := br.nextQueryAndArgs()
|
||||
|
||||
if !br.mrr.NextResult() {
|
||||
err := br.mrr.Close()
|
||||
if err == nil {
|
||||
err = errors.New("no more results in batch")
|
||||
}
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: err,
|
||||
})
|
||||
}
|
||||
return pgconn.CommandTag{}, err
|
||||
}
|
||||
|
||||
commandTag, err := br.mrr.ResultReader().Close()
|
||||
if err != nil {
|
||||
br.err = err
|
||||
br.mrr.Close()
|
||||
}
|
||||
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
CommandTag: commandTag,
|
||||
Err: br.err,
|
||||
})
|
||||
}
|
||||
|
||||
return commandTag, br.err
|
||||
}
|
||||
|
||||
// Query reads the results from the next query in the batch as if the query has been sent with Query.
|
||||
func (br *batchResults) Query() (Rows, error) {
|
||||
query, arguments, ok := br.nextQueryAndArgs()
|
||||
if !ok {
|
||||
query = "batch query"
|
||||
}
|
||||
|
||||
if br.err != nil {
|
||||
return &baseRows{err: br.err, closed: true}, br.err
|
||||
}
|
||||
|
||||
if br.closed {
|
||||
alreadyClosedErr := fmt.Errorf("batch already closed")
|
||||
return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
|
||||
}
|
||||
|
||||
rows := br.conn.getRows(br.ctx, query, arguments)
|
||||
rows.batchTracer = br.conn.batchTracer
|
||||
|
||||
if !br.mrr.NextResult() {
|
||||
rows.err = br.mrr.Close()
|
||||
if rows.err == nil {
|
||||
rows.err = errors.New("no more results in batch")
|
||||
}
|
||||
rows.closed = true
|
||||
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: rows.err,
|
||||
})
|
||||
}
|
||||
|
||||
return rows, rows.err
|
||||
}
|
||||
|
||||
rows.resultReader = br.mrr.ResultReader()
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
|
||||
func (br *batchResults) QueryRow() Row {
|
||||
rows, _ := br.Query()
|
||||
return (*connRow)(rows.(*baseRows))
|
||||
|
||||
}
|
||||
|
||||
// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
|
||||
// resyncronize the connection with the server. In this case the underlying connection will have been closed.
|
||||
func (br *batchResults) Close() error {
|
||||
defer func() {
|
||||
if !br.endTraced {
|
||||
if br.conn != nil && br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err})
|
||||
}
|
||||
br.endTraced = true
|
||||
}
|
||||
}()
|
||||
|
||||
if br.err != nil {
|
||||
return br.err
|
||||
}
|
||||
|
||||
if br.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read and run fn for all remaining items
|
||||
for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
|
||||
if br.b.QueuedQueries[br.qqIdx].Fn != nil {
|
||||
err := br.b.QueuedQueries[br.qqIdx].Fn(br)
|
||||
if err != nil {
|
||||
br.err = err
|
||||
}
|
||||
} else {
|
||||
br.Exec()
|
||||
}
|
||||
}
|
||||
|
||||
br.closed = true
|
||||
|
||||
err := br.mrr.Close()
|
||||
if br.err == nil {
|
||||
br.err = err
|
||||
}
|
||||
|
||||
return br.err
|
||||
}
|
||||
|
||||
func (br *batchResults) earlyError() error {
|
||||
return br.err
|
||||
}
|
||||
|
||||
func (br *batchResults) nextQueryAndArgs() (query string, args []any, ok bool) {
|
||||
if br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
|
||||
bi := br.b.QueuedQueries[br.qqIdx]
|
||||
query = bi.SQL
|
||||
args = bi.Arguments
|
||||
ok = true
|
||||
br.qqIdx++
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type pipelineBatchResults struct {
|
||||
ctx context.Context
|
||||
conn *Conn
|
||||
pipeline *pgconn.Pipeline
|
||||
lastRows *baseRows
|
||||
err error
|
||||
b *Batch
|
||||
qqIdx int
|
||||
closed bool
|
||||
endTraced bool
|
||||
}
|
||||
|
||||
// Exec reads the results from the next query in the batch as if the query has been sent with Exec.
|
||||
func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) {
|
||||
if br.err != nil {
|
||||
return pgconn.CommandTag{}, br.err
|
||||
}
|
||||
if br.closed {
|
||||
return pgconn.CommandTag{}, fmt.Errorf("batch already closed")
|
||||
}
|
||||
if br.lastRows != nil && br.lastRows.err != nil {
|
||||
return pgconn.CommandTag{}, br.err
|
||||
}
|
||||
|
||||
query, arguments, err := br.nextQueryAndArgs()
|
||||
if err != nil {
|
||||
return pgconn.CommandTag{}, err
|
||||
}
|
||||
|
||||
results, err := br.pipeline.GetResults()
|
||||
if err != nil {
|
||||
br.err = err
|
||||
return pgconn.CommandTag{}, br.err
|
||||
}
|
||||
var commandTag pgconn.CommandTag
|
||||
switch results := results.(type) {
|
||||
case *pgconn.ResultReader:
|
||||
commandTag, br.err = results.Close()
|
||||
default:
|
||||
return pgconn.CommandTag{}, fmt.Errorf("unexpected pipeline result: %T", results)
|
||||
}
|
||||
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
CommandTag: commandTag,
|
||||
Err: br.err,
|
||||
})
|
||||
}
|
||||
|
||||
return commandTag, br.err
|
||||
}
|
||||
|
||||
// Query reads the results from the next query in the batch as if the query has been sent with Query.
|
||||
func (br *pipelineBatchResults) Query() (Rows, error) {
|
||||
if br.err != nil {
|
||||
return &baseRows{err: br.err, closed: true}, br.err
|
||||
}
|
||||
|
||||
if br.closed {
|
||||
alreadyClosedErr := fmt.Errorf("batch already closed")
|
||||
return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr
|
||||
}
|
||||
|
||||
if br.lastRows != nil && br.lastRows.err != nil {
|
||||
br.err = br.lastRows.err
|
||||
return &baseRows{err: br.err, closed: true}, br.err
|
||||
}
|
||||
|
||||
query, arguments, err := br.nextQueryAndArgs()
|
||||
if err != nil {
|
||||
return &baseRows{err: err, closed: true}, err
|
||||
}
|
||||
|
||||
rows := br.conn.getRows(br.ctx, query, arguments)
|
||||
rows.batchTracer = br.conn.batchTracer
|
||||
br.lastRows = rows
|
||||
|
||||
results, err := br.pipeline.GetResults()
|
||||
if err != nil {
|
||||
br.err = err
|
||||
rows.err = err
|
||||
rows.closed = true
|
||||
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: err,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
switch results := results.(type) {
|
||||
case *pgconn.ResultReader:
|
||||
rows.resultReader = results
|
||||
default:
|
||||
err = fmt.Errorf("unexpected pipeline result: %T", results)
|
||||
br.err = err
|
||||
rows.err = err
|
||||
rows.closed = true
|
||||
}
|
||||
}
|
||||
|
||||
return rows, rows.err
|
||||
}
|
||||
|
||||
// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow.
|
||||
func (br *pipelineBatchResults) QueryRow() Row {
|
||||
rows, _ := br.Query()
|
||||
return (*connRow)(rows.(*baseRows))
|
||||
|
||||
}
|
||||
|
||||
// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to
|
||||
// resyncronize the connection with the server. In this case the underlying connection will have been closed.
|
||||
func (br *pipelineBatchResults) Close() error {
|
||||
defer func() {
|
||||
if !br.endTraced {
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err})
|
||||
}
|
||||
br.endTraced = true
|
||||
}
|
||||
}()
|
||||
|
||||
if br.err == nil && br.lastRows != nil && br.lastRows.err != nil {
|
||||
br.err = br.lastRows.err
|
||||
return br.err
|
||||
}
|
||||
|
||||
if br.closed {
|
||||
return br.err
|
||||
}
|
||||
|
||||
// Read and run fn for all remaining items
|
||||
for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) {
|
||||
if br.b.QueuedQueries[br.qqIdx].Fn != nil {
|
||||
err := br.b.QueuedQueries[br.qqIdx].Fn(br)
|
||||
if err != nil {
|
||||
br.err = err
|
||||
}
|
||||
} else {
|
||||
br.Exec()
|
||||
}
|
||||
}
|
||||
|
||||
br.closed = true
|
||||
|
||||
err := br.pipeline.Close()
|
||||
if br.err == nil {
|
||||
br.err = err
|
||||
}
|
||||
|
||||
return br.err
|
||||
}
|
||||
|
||||
func (br *pipelineBatchResults) earlyError() error {
|
||||
return br.err
|
||||
}
|
||||
|
||||
func (br *pipelineBatchResults) nextQueryAndArgs() (query string, args []any, err error) {
|
||||
if br.b == nil {
|
||||
return "", nil, errors.New("no reference to batch")
|
||||
}
|
||||
|
||||
if br.qqIdx >= len(br.b.QueuedQueries) {
|
||||
return "", nil, errors.New("no more results in batch")
|
||||
}
|
||||
|
||||
bi := br.b.QueuedQueries[br.qqIdx]
|
||||
br.qqIdx++
|
||||
return bi.SQL, bi.Arguments, nil
|
||||
}
|
||||
+1444
File diff suppressed because it is too large
Load Diff
+276
@@ -0,0 +1,276 @@
|
||||
package pgx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/jackc/pgx/v5/internal/pgio"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
// CopyFromRows returns a CopyFromSource interface over the provided rows slice
|
||||
// making it usable by *Conn.CopyFrom.
|
||||
func CopyFromRows(rows [][]any) CopyFromSource {
|
||||
return ©FromRows{rows: rows, idx: -1}
|
||||
}
|
||||
|
||||
type copyFromRows struct {
|
||||
rows [][]any
|
||||
idx int
|
||||
}
|
||||
|
||||
func (ctr *copyFromRows) Next() bool {
|
||||
ctr.idx++
|
||||
return ctr.idx < len(ctr.rows)
|
||||
}
|
||||
|
||||
func (ctr *copyFromRows) Values() ([]any, error) {
|
||||
return ctr.rows[ctr.idx], nil
|
||||
}
|
||||
|
||||
func (ctr *copyFromRows) Err() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CopyFromSlice returns a CopyFromSource interface over a dynamic func
|
||||
// making it usable by *Conn.CopyFrom.
|
||||
func CopyFromSlice(length int, next func(int) ([]any, error)) CopyFromSource {
|
||||
return ©FromSlice{next: next, idx: -1, len: length}
|
||||
}
|
||||
|
||||
type copyFromSlice struct {
|
||||
next func(int) ([]any, error)
|
||||
idx int
|
||||
len int
|
||||
err error
|
||||
}
|
||||
|
||||
func (cts *copyFromSlice) Next() bool {
|
||||
cts.idx++
|
||||
return cts.idx < cts.len
|
||||
}
|
||||
|
||||
func (cts *copyFromSlice) Values() ([]any, error) {
|
||||
values, err := cts.next(cts.idx)
|
||||
if err != nil {
|
||||
cts.err = err
|
||||
}
|
||||
return values, err
|
||||
}
|
||||
|
||||
func (cts *copyFromSlice) Err() error {
|
||||
return cts.err
|
||||
}
|
||||
|
||||
// CopyFromFunc returns a CopyFromSource interface that relies on nxtf for values.
|
||||
// nxtf returns rows until it either signals an 'end of data' by returning row=nil and err=nil,
|
||||
// or it returns an error. If nxtf returns an error, the copy is aborted.
|
||||
func CopyFromFunc(nxtf func() (row []any, err error)) CopyFromSource {
|
||||
return ©FromFunc{next: nxtf}
|
||||
}
|
||||
|
||||
type copyFromFunc struct {
|
||||
next func() ([]any, error)
|
||||
valueRow []any
|
||||
err error
|
||||
}
|
||||
|
||||
func (g *copyFromFunc) Next() bool {
|
||||
g.valueRow, g.err = g.next()
|
||||
// only return true if valueRow exists and no error
|
||||
return g.valueRow != nil && g.err == nil
|
||||
}
|
||||
|
||||
func (g *copyFromFunc) Values() ([]any, error) {
|
||||
return g.valueRow, g.err
|
||||
}
|
||||
|
||||
func (g *copyFromFunc) Err() error {
|
||||
return g.err
|
||||
}
|
||||
|
||||
// CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data.
|
||||
type CopyFromSource interface {
|
||||
// Next returns true if there is another row and makes the next row data
|
||||
// available to Values(). When there are no more rows available or an error
|
||||
// has occurred it returns false.
|
||||
Next() bool
|
||||
|
||||
// Values returns the values for the current row.
|
||||
Values() ([]any, error)
|
||||
|
||||
// Err returns any error that has been encountered by the CopyFromSource. If
|
||||
// this is not nil *Conn.CopyFrom will abort the copy.
|
||||
Err() error
|
||||
}
|
||||
|
||||
type copyFrom struct {
|
||||
conn *Conn
|
||||
tableName Identifier
|
||||
columnNames []string
|
||||
rowSrc CopyFromSource
|
||||
readerErrChan chan error
|
||||
mode QueryExecMode
|
||||
}
|
||||
|
||||
func (ct *copyFrom) run(ctx context.Context) (int64, error) {
|
||||
if ct.conn.copyFromTracer != nil {
|
||||
ctx = ct.conn.copyFromTracer.TraceCopyFromStart(ctx, ct.conn, TraceCopyFromStartData{
|
||||
TableName: ct.tableName,
|
||||
ColumnNames: ct.columnNames,
|
||||
})
|
||||
}
|
||||
|
||||
quotedTableName := ct.tableName.Sanitize()
|
||||
cbuf := &bytes.Buffer{}
|
||||
for i, cn := range ct.columnNames {
|
||||
if i != 0 {
|
||||
cbuf.WriteString(", ")
|
||||
}
|
||||
cbuf.WriteString(quoteIdentifier(cn))
|
||||
}
|
||||
quotedColumnNames := cbuf.String()
|
||||
|
||||
var sd *pgconn.StatementDescription
|
||||
switch ct.mode {
|
||||
case QueryExecModeExec, QueryExecModeSimpleProtocol:
|
||||
// These modes don't support the binary format. Before the inclusion of the
|
||||
// QueryExecModes, Conn.Prepare was called on every COPY operation to get
|
||||
// the OIDs. These prepared statements were not cached.
|
||||
//
|
||||
// Since that's the same behavior provided by QueryExecModeDescribeExec,
|
||||
// we'll default to that mode.
|
||||
ct.mode = QueryExecModeDescribeExec
|
||||
fallthrough
|
||||
case QueryExecModeCacheStatement, QueryExecModeCacheDescribe, QueryExecModeDescribeExec:
|
||||
var err error
|
||||
sd, err = ct.conn.getStatementDescription(
|
||||
ctx,
|
||||
ct.mode,
|
||||
fmt.Sprintf("select %s from %s", quotedColumnNames, quotedTableName),
|
||||
)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("statement description failed: %w", err)
|
||||
}
|
||||
default:
|
||||
return 0, fmt.Errorf("unknown QueryExecMode: %v", ct.mode)
|
||||
}
|
||||
|
||||
r, w := io.Pipe()
|
||||
doneChan := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
defer close(doneChan)
|
||||
|
||||
// Purposely NOT using defer w.Close(). See https://github.com/golang/go/issues/24283.
|
||||
buf := ct.conn.wbuf
|
||||
|
||||
buf = append(buf, "PGCOPY\n\377\r\n\000"...)
|
||||
buf = pgio.AppendInt32(buf, 0)
|
||||
buf = pgio.AppendInt32(buf, 0)
|
||||
|
||||
moreRows := true
|
||||
for moreRows {
|
||||
var err error
|
||||
moreRows, buf, err = ct.buildCopyBuf(buf, sd)
|
||||
if err != nil {
|
||||
w.CloseWithError(err)
|
||||
return
|
||||
}
|
||||
|
||||
if ct.rowSrc.Err() != nil {
|
||||
w.CloseWithError(ct.rowSrc.Err())
|
||||
return
|
||||
}
|
||||
|
||||
if len(buf) > 0 {
|
||||
_, err = w.Write(buf)
|
||||
if err != nil {
|
||||
w.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
buf = buf[:0]
|
||||
}
|
||||
|
||||
w.Close()
|
||||
}()
|
||||
|
||||
commandTag, err := ct.conn.pgConn.CopyFrom(ctx, r, fmt.Sprintf("copy %s ( %s ) from stdin binary;", quotedTableName, quotedColumnNames))
|
||||
|
||||
r.Close()
|
||||
<-doneChan
|
||||
|
||||
if ct.conn.copyFromTracer != nil {
|
||||
ct.conn.copyFromTracer.TraceCopyFromEnd(ctx, ct.conn, TraceCopyFromEndData{
|
||||
CommandTag: commandTag,
|
||||
Err: err,
|
||||
})
|
||||
}
|
||||
|
||||
return commandTag.RowsAffected(), err
|
||||
}
|
||||
|
||||
func (ct *copyFrom) buildCopyBuf(buf []byte, sd *pgconn.StatementDescription) (bool, []byte, error) {
|
||||
const sendBufSize = 65536 - 5 // The packet has a 5-byte header
|
||||
lastBufLen := 0
|
||||
largestRowLen := 0
|
||||
|
||||
for ct.rowSrc.Next() {
|
||||
lastBufLen = len(buf)
|
||||
|
||||
values, err := ct.rowSrc.Values()
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
if len(values) != len(ct.columnNames) {
|
||||
return false, nil, fmt.Errorf("expected %d values, got %d values", len(ct.columnNames), len(values))
|
||||
}
|
||||
|
||||
buf = pgio.AppendInt16(buf, int16(len(ct.columnNames)))
|
||||
for i, val := range values {
|
||||
buf, err = encodeCopyValue(ct.conn.typeMap, buf, sd.Fields[i].DataTypeOID, val)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
rowLen := len(buf) - lastBufLen
|
||||
if rowLen > largestRowLen {
|
||||
largestRowLen = rowLen
|
||||
}
|
||||
|
||||
// Try not to overflow size of the buffer PgConn.CopyFrom will be reading into. If that happens then the nature of
|
||||
// io.Pipe means that the next Read will be short. This can lead to pathological send sizes such as 65531, 13, 65531
|
||||
// 13, 65531, 13, 65531, 13.
|
||||
if len(buf) > sendBufSize-largestRowLen {
|
||||
return true, buf, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, buf, nil
|
||||
}
|
||||
|
||||
// CopyFrom uses the PostgreSQL copy protocol to perform bulk data insertion. It returns the number of rows copied and
|
||||
// an error.
|
||||
//
|
||||
// CopyFrom requires all values use the binary format. A pgtype.Type that supports the binary format must be registered
|
||||
// for the type of each column. Almost all types implemented by pgx support the binary format.
|
||||
//
|
||||
// Even though enum types appear to be strings they still must be registered to use with CopyFrom. This can be done with
|
||||
// Conn.LoadType and pgtype.Map.RegisterType.
|
||||
func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) {
|
||||
ct := ©From{
|
||||
conn: c,
|
||||
tableName: tableName,
|
||||
columnNames: columnNames,
|
||||
rowSrc: rowSrc,
|
||||
readerErrChan: make(chan error),
|
||||
mode: c.config.DefaultQueryExecMode,
|
||||
}
|
||||
|
||||
return ct.run(ctx)
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
package pgx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
/*
|
||||
buildLoadDerivedTypesSQL generates the correct query for retrieving type information.
|
||||
|
||||
pgVersion: the major version of the PostgreSQL server
|
||||
typeNames: the names of the types to load. If nil, load all types.
|
||||
*/
|
||||
func buildLoadDerivedTypesSQL(pgVersion int64, typeNames []string) string {
|
||||
supportsMultirange := (pgVersion >= 14)
|
||||
var typeNamesClause string
|
||||
|
||||
if typeNames == nil {
|
||||
// This should not occur; this will not return any types
|
||||
typeNamesClause = "= ''"
|
||||
} else {
|
||||
typeNamesClause = "= ANY($1)"
|
||||
}
|
||||
parts := make([]string, 0, 10)
|
||||
|
||||
// Each of the type names provided might be found in pg_class or pg_type.
|
||||
// Additionally, it may or may not include a schema portion.
|
||||
parts = append(parts, `
|
||||
WITH RECURSIVE
|
||||
-- find the OIDs in pg_class which match one of the provided type names
|
||||
selected_classes(oid,reltype) AS (
|
||||
-- this query uses the namespace search path, so will match type names without a schema prefix
|
||||
SELECT pg_class.oid, pg_class.reltype
|
||||
FROM pg_catalog.pg_class
|
||||
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = pg_class.relnamespace
|
||||
WHERE pg_catalog.pg_table_is_visible(pg_class.oid)
|
||||
AND relname `, typeNamesClause, `
|
||||
UNION ALL
|
||||
-- this query will only match type names which include the schema prefix
|
||||
SELECT pg_class.oid, pg_class.reltype
|
||||
FROM pg_class
|
||||
INNER JOIN pg_namespace ON (pg_class.relnamespace = pg_namespace.oid)
|
||||
WHERE nspname || '.' || relname `, typeNamesClause, `
|
||||
),
|
||||
selected_types(oid) AS (
|
||||
-- collect the OIDs from pg_types which correspond to the selected classes
|
||||
SELECT reltype AS oid
|
||||
FROM selected_classes
|
||||
UNION ALL
|
||||
-- as well as any other type names which match our criteria
|
||||
SELECT pg_type.oid
|
||||
FROM pg_type
|
||||
LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid)
|
||||
WHERE typname `, typeNamesClause, `
|
||||
OR nspname || '.' || typname `, typeNamesClause, `
|
||||
),
|
||||
-- this builds a parent/child mapping of objects, allowing us to know
|
||||
-- all the child (ie: dependent) types that a parent (type) requires
|
||||
-- As can be seen, there are 3 ways this can occur (the last of which
|
||||
-- is due to being a composite class, where the composite fields are children)
|
||||
pc(parent, child) AS (
|
||||
SELECT parent.oid, parent.typelem
|
||||
FROM pg_type parent
|
||||
WHERE parent.typtype = 'b' AND parent.typelem != 0
|
||||
UNION ALL
|
||||
SELECT parent.oid, parent.typbasetype
|
||||
FROM pg_type parent
|
||||
WHERE parent.typtypmod = -1 AND parent.typbasetype != 0
|
||||
UNION ALL
|
||||
SELECT pg_type.oid, atttypid
|
||||
FROM pg_attribute
|
||||
INNER JOIN pg_class ON (pg_class.oid = pg_attribute.attrelid)
|
||||
INNER JOIN pg_type ON (pg_type.oid = pg_class.reltype)
|
||||
WHERE NOT attisdropped
|
||||
AND attnum > 0
|
||||
),
|
||||
-- Now construct a recursive query which includes a 'depth' element.
|
||||
-- This is used to ensure that the "youngest" children are registered before
|
||||
-- their parents.
|
||||
relationships(parent, child, depth) AS (
|
||||
SELECT DISTINCT 0::OID, selected_types.oid, 0
|
||||
FROM selected_types
|
||||
UNION ALL
|
||||
SELECT pg_type.oid AS parent, pg_attribute.atttypid AS child, 1
|
||||
FROM selected_classes c
|
||||
inner join pg_type ON (c.reltype = pg_type.oid)
|
||||
inner join pg_attribute on (c.oid = pg_attribute.attrelid)
|
||||
UNION ALL
|
||||
SELECT pc.parent, pc.child, relationships.depth + 1
|
||||
FROM pc
|
||||
INNER JOIN relationships ON (pc.parent = relationships.child)
|
||||
),
|
||||
-- composite fields need to be encapsulated as a couple of arrays to provide the required information for registration
|
||||
composite AS (
|
||||
SELECT pg_type.oid, ARRAY_AGG(attname ORDER BY attnum) AS attnames, ARRAY_AGG(atttypid ORDER BY ATTNUM) AS atttypids
|
||||
FROM pg_attribute
|
||||
INNER JOIN pg_class ON (pg_class.oid = pg_attribute.attrelid)
|
||||
INNER JOIN pg_type ON (pg_type.oid = pg_class.reltype)
|
||||
WHERE NOT attisdropped
|
||||
AND attnum > 0
|
||||
GROUP BY pg_type.oid
|
||||
)
|
||||
-- Bring together this information, showing all the information which might possibly be required
|
||||
-- to complete the registration, applying filters to only show the items which relate to the selected
|
||||
-- types/classes.
|
||||
SELECT typname,
|
||||
pg_namespace.nspname,
|
||||
typtype,
|
||||
typbasetype,
|
||||
typelem,
|
||||
pg_type.oid,`)
|
||||
if supportsMultirange {
|
||||
parts = append(parts, `
|
||||
COALESCE(multirange.rngtypid, 0) AS rngtypid,`)
|
||||
} else {
|
||||
parts = append(parts, `
|
||||
0 AS rngtypid,`)
|
||||
}
|
||||
parts = append(parts, `
|
||||
COALESCE(pg_range.rngsubtype, 0) AS rngsubtype,
|
||||
attnames, atttypids
|
||||
FROM relationships
|
||||
INNER JOIN pg_type ON (pg_type.oid = relationships.child)
|
||||
LEFT OUTER JOIN pg_range ON (pg_type.oid = pg_range.rngtypid)`)
|
||||
if supportsMultirange {
|
||||
parts = append(parts, `
|
||||
LEFT OUTER JOIN pg_range multirange ON (pg_type.oid = multirange.rngmultitypid)`)
|
||||
}
|
||||
|
||||
parts = append(parts, `
|
||||
LEFT OUTER JOIN composite USING (oid)
|
||||
LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid)
|
||||
WHERE NOT (typtype = 'b' AND typelem = 0)`)
|
||||
parts = append(parts, `
|
||||
GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, pg_type.oid, pg_range.rngsubtype,`)
|
||||
if supportsMultirange {
|
||||
parts = append(parts, `
|
||||
multirange.rngtypid,`)
|
||||
}
|
||||
parts = append(parts, `
|
||||
attnames, atttypids
|
||||
ORDER BY MAX(depth) desc, typname;`)
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
type derivedTypeInfo struct {
|
||||
Oid, Typbasetype, Typelem, Rngsubtype, Rngtypid uint32
|
||||
TypeName, Typtype, NspName string
|
||||
Attnames []string
|
||||
Atttypids []uint32
|
||||
}
|
||||
|
||||
// LoadTypes performs a single (complex) query, returning all the required
|
||||
// information to register the named types, as well as any other types directly
|
||||
// or indirectly required to complete the registration.
|
||||
// The result of this call can be passed into RegisterTypes to complete the process.
|
||||
func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Type, error) {
|
||||
m := c.TypeMap()
|
||||
if typeNames == nil || len(typeNames) == 0 {
|
||||
return nil, fmt.Errorf("No type names were supplied.")
|
||||
}
|
||||
|
||||
// Disregard server version errors. This will result in
|
||||
// the SQL not support recent structures such as multirange
|
||||
serverVersion, _ := serverVersion(c)
|
||||
sql := buildLoadDerivedTypesSQL(serverVersion, typeNames)
|
||||
var rows Rows
|
||||
var err error
|
||||
if typeNames == nil {
|
||||
rows, err = c.Query(ctx, sql, QueryExecModeSimpleProtocol)
|
||||
} else {
|
||||
rows, err = c.Query(ctx, sql, QueryExecModeSimpleProtocol, typeNames)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("While generating load types query: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := make([]*pgtype.Type, 0, 100)
|
||||
for rows.Next() {
|
||||
ti := derivedTypeInfo{}
|
||||
err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("While scanning type information: %w", err)
|
||||
}
|
||||
var type_ *pgtype.Type
|
||||
switch ti.Typtype {
|
||||
case "b": // array
|
||||
dt, ok := m.TypeForOID(ti.Typelem)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Array element OID %v not registered while loading pgtype %q", ti.Typelem, ti.TypeName)
|
||||
}
|
||||
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt}}
|
||||
case "c": // composite
|
||||
var fields []pgtype.CompositeCodecField
|
||||
for i, fieldName := range ti.Attnames {
|
||||
dt, ok := m.TypeForOID(ti.Atttypids[i])
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Unknown field for composite type %q: field %q (OID %v) is not already registered.", ti.TypeName, fieldName, ti.Atttypids[i])
|
||||
}
|
||||
fields = append(fields, pgtype.CompositeCodecField{Name: fieldName, Type: dt})
|
||||
}
|
||||
|
||||
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.CompositeCodec{Fields: fields}}
|
||||
case "d": // domain
|
||||
dt, ok := m.TypeForOID(ti.Typbasetype)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Domain base type OID %v was not already registered, needed for %q", ti.Typbasetype, ti.TypeName)
|
||||
}
|
||||
|
||||
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: dt.Codec}
|
||||
case "e": // enum
|
||||
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.EnumCodec{}}
|
||||
case "r": // range
|
||||
dt, ok := m.TypeForOID(ti.Rngsubtype)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Range element OID %v was not already registered, needed for %q", ti.Rngsubtype, ti.TypeName)
|
||||
}
|
||||
|
||||
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.RangeCodec{ElementType: dt}}
|
||||
case "m": // multirange
|
||||
dt, ok := m.TypeForOID(ti.Rngtypid)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Multirange element OID %v was not already registered, needed for %q", ti.Rngtypid, ti.TypeName)
|
||||
}
|
||||
|
||||
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.MultirangeCodec{ElementType: dt}}
|
||||
default:
|
||||
return nil, fmt.Errorf("Unknown typtype %q was found while registering %q", ti.Typtype, ti.TypeName)
|
||||
}
|
||||
if type_ != nil {
|
||||
m.RegisterType(type_)
|
||||
if ti.NspName != "" {
|
||||
nspType := &pgtype.Type{Name: ti.NspName + "." + type_.Name, OID: type_.OID, Codec: type_.Codec}
|
||||
m.RegisterType(nspType)
|
||||
result = append(result, nspType)
|
||||
}
|
||||
result = append(result, type_)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// serverVersion returns the postgresql server version.
|
||||
func serverVersion(c *Conn) (int64, error) {
|
||||
serverVersionStr := c.PgConn().ParameterStatus("server_version")
|
||||
serverVersionStr = regexp.MustCompile(`^[0-9]+`).FindString(serverVersionStr)
|
||||
// if not PostgreSQL do nothing
|
||||
if serverVersionStr == "" {
|
||||
return 0, fmt.Errorf("Cannot identify server version in %q", serverVersionStr)
|
||||
}
|
||||
|
||||
version, err := strconv.ParseInt(serverVersionStr, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("postgres version parsing failed: %w", err)
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
// Package pgx is a PostgreSQL database driver.
|
||||
/*
|
||||
pgx provides a native PostgreSQL driver and can act as a database/sql driver. The native PostgreSQL interface is similar
|
||||
to the database/sql interface while providing better speed and access to PostgreSQL specific features. Use
|
||||
github.com/jackc/pgx/v5/stdlib to use pgx as a database/sql compatible driver. See that package's documentation for
|
||||
details.
|
||||
|
||||
Establishing a Connection
|
||||
|
||||
The primary way of establishing a connection is with [pgx.Connect]:
|
||||
|
||||
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
|
||||
|
||||
The database connection string can be in URL or key/value format. Both PostgreSQL settings and pgx settings can be
|
||||
specified here. In addition, a config struct can be created by [ParseConfig] and modified before establishing the
|
||||
connection with [ConnectConfig] to configure settings such as tracing that cannot be configured with a connection
|
||||
string.
|
||||
|
||||
Connection Pool
|
||||
|
||||
[*pgx.Conn] represents a single connection to the database and is not concurrency safe. Use package
|
||||
github.com/jackc/pgx/v5/pgxpool for a concurrency safe connection pool.
|
||||
|
||||
Query Interface
|
||||
|
||||
pgx implements Query in the familiar database/sql style. However, pgx provides generic functions such as CollectRows and
|
||||
ForEachRow that are a simpler and safer way of processing rows than manually calling defer rows.Close(), rows.Next(),
|
||||
rows.Scan, and rows.Err().
|
||||
|
||||
CollectRows can be used collect all returned rows into a slice.
|
||||
|
||||
rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 5)
|
||||
numbers, err := pgx.CollectRows(rows, pgx.RowTo[int32])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// numbers => [1 2 3 4 5]
|
||||
|
||||
ForEachRow can be used to execute a callback function for every row. This is often easier than iterating over rows
|
||||
directly.
|
||||
|
||||
var sum, n int32
|
||||
rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 10)
|
||||
_, err := pgx.ForEachRow(rows, []any{&n}, func() error {
|
||||
sum += n
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pgx also implements QueryRow in the same style as database/sql.
|
||||
|
||||
var name string
|
||||
var weight int64
|
||||
err := conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Use Exec to execute a query that does not return a result set.
|
||||
|
||||
commandTag, err := conn.Exec(context.Background(), "delete from widgets where id=$1", 42)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if commandTag.RowsAffected() != 1 {
|
||||
return errors.New("No row found to delete")
|
||||
}
|
||||
|
||||
PostgreSQL Data Types
|
||||
|
||||
pgx uses the pgtype package to converting Go values to and from PostgreSQL values. It supports many PostgreSQL types
|
||||
directly and is customizable and extendable. User defined data types such as enums, domains, and composite types may
|
||||
require type registration. See that package's documentation for details.
|
||||
|
||||
Transactions
|
||||
|
||||
Transactions are started by calling Begin.
|
||||
|
||||
tx, err := conn.Begin(context.Background())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Rollback is safe to call even if the tx is already closed, so if
|
||||
// the tx commits successfully, this is a no-op
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
_, err = tx.Exec(context.Background(), "insert into foo(id) values (1)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Commit(context.Background())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
The Tx returned from Begin also implements the Begin method. This can be used to implement pseudo nested transactions.
|
||||
These are internally implemented with savepoints.
|
||||
|
||||
Use BeginTx to control the transaction mode. BeginTx also can be used to ensure a new transaction is created instead of
|
||||
a pseudo nested transaction.
|
||||
|
||||
BeginFunc and BeginTxFunc are functions that begin a transaction, execute a function, and commit or rollback the
|
||||
transaction depending on the return value of the function. These can be simpler and less error prone to use.
|
||||
|
||||
err = pgx.BeginFunc(context.Background(), conn, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(context.Background(), "insert into foo(id) values (1)")
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Prepared Statements
|
||||
|
||||
Prepared statements can be manually created with the Prepare method. However, this is rarely necessary because pgx
|
||||
includes an automatic statement cache by default. Queries run through the normal Query, QueryRow, and Exec functions are
|
||||
automatically prepared on first execution and the prepared statement is reused on subsequent executions. See ParseConfig
|
||||
for information on how to customize or disable the statement cache.
|
||||
|
||||
Copy Protocol
|
||||
|
||||
Use CopyFrom to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. CopyFrom accepts a
|
||||
CopyFromSource interface. If the data is already in a [][]any use CopyFromRows to wrap it in a CopyFromSource interface.
|
||||
Or implement CopyFromSource to avoid buffering the entire data set in memory.
|
||||
|
||||
rows := [][]any{
|
||||
{"John", "Smith", int32(36)},
|
||||
{"Jane", "Doe", int32(29)},
|
||||
}
|
||||
|
||||
copyCount, err := conn.CopyFrom(
|
||||
context.Background(),
|
||||
pgx.Identifier{"people"},
|
||||
[]string{"first_name", "last_name", "age"},
|
||||
pgx.CopyFromRows(rows),
|
||||
)
|
||||
|
||||
When you already have a typed array using CopyFromSlice can be more convenient.
|
||||
|
||||
rows := []User{
|
||||
{"John", "Smith", 36},
|
||||
{"Jane", "Doe", 29},
|
||||
}
|
||||
|
||||
copyCount, err := conn.CopyFrom(
|
||||
context.Background(),
|
||||
pgx.Identifier{"people"},
|
||||
[]string{"first_name", "last_name", "age"},
|
||||
pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) {
|
||||
return []any{rows[i].FirstName, rows[i].LastName, rows[i].Age}, nil
|
||||
}),
|
||||
)
|
||||
|
||||
CopyFrom can be faster than an insert with as few as 5 rows.
|
||||
|
||||
Listen and Notify
|
||||
|
||||
pgx can listen to the PostgreSQL notification system with the `Conn.WaitForNotification` method. It blocks until a
|
||||
notification is received or the context is canceled.
|
||||
|
||||
_, err := conn.Exec(context.Background(), "listen channelname")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
notification, err := conn.WaitForNotification(context.Background())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// do something with notification
|
||||
|
||||
|
||||
Tracing and Logging
|
||||
|
||||
pgx supports tracing by setting ConnConfig.Tracer. To combine several tracers you can use the multitracer.Tracer.
|
||||
|
||||
In addition, the tracelog package provides the TraceLog type which lets a traditional logger act as a Tracer.
|
||||
|
||||
For debug tracing of the actual PostgreSQL wire protocol messages see github.com/jackc/pgx/v5/pgproto3.
|
||||
|
||||
Lower Level PostgreSQL Functionality
|
||||
|
||||
github.com/jackc/pgx/v5/pgconn contains a lower level PostgreSQL driver roughly at the level of libpq. pgx.Conn in
|
||||
implemented on top of pgconn. The Conn.PgConn() method can be used to access this lower layer.
|
||||
|
||||
PgBouncer
|
||||
|
||||
By default pgx automatically uses prepared statements. Prepared statements are incompatible with PgBouncer. This can be
|
||||
disabled by setting a different QueryExecMode in ConnConfig.DefaultQueryExecMode.
|
||||
*/
|
||||
package pgx
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package pgx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
// ExtendedQueryBuilder is used to choose the parameter formats, to format the parameters and to choose the result
|
||||
// formats for an extended query.
|
||||
type ExtendedQueryBuilder struct {
|
||||
ParamValues [][]byte
|
||||
paramValueBytes []byte
|
||||
ParamFormats []int16
|
||||
ResultFormats []int16
|
||||
}
|
||||
|
||||
// Build sets ParamValues, ParamFormats, and ResultFormats for use with *PgConn.ExecParams or *PgConn.ExecPrepared. If
|
||||
// sd is nil then QueryExecModeExec behavior will be used.
|
||||
func (eqb *ExtendedQueryBuilder) Build(m *pgtype.Map, sd *pgconn.StatementDescription, args []any) error {
|
||||
eqb.reset()
|
||||
|
||||
if sd == nil {
|
||||
for i := range args {
|
||||
err := eqb.appendParam(m, 0, pgtype.TextFormatCode, args[i])
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to encode args[%d]: %w", i, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(sd.ParamOIDs) != len(args) {
|
||||
return fmt.Errorf("mismatched param and argument count")
|
||||
}
|
||||
|
||||
for i := range args {
|
||||
err := eqb.appendParam(m, sd.ParamOIDs[i], -1, args[i])
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to encode args[%d]: %w", i, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for i := range sd.Fields {
|
||||
eqb.appendResultFormat(m.FormatCodeForOID(sd.Fields[i].DataTypeOID))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// appendParam appends a parameter to the query. format may be -1 to automatically choose the format. If arg is nil it
|
||||
// must be an untyped nil.
|
||||
func (eqb *ExtendedQueryBuilder) appendParam(m *pgtype.Map, oid uint32, format int16, arg any) error {
|
||||
if format == -1 {
|
||||
preferredFormat := eqb.chooseParameterFormatCode(m, oid, arg)
|
||||
preferredErr := eqb.appendParam(m, oid, preferredFormat, arg)
|
||||
if preferredErr == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var otherFormat int16
|
||||
if preferredFormat == TextFormatCode {
|
||||
otherFormat = BinaryFormatCode
|
||||
} else {
|
||||
otherFormat = TextFormatCode
|
||||
}
|
||||
|
||||
otherErr := eqb.appendParam(m, oid, otherFormat, arg)
|
||||
if otherErr == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return preferredErr // return the error from the preferred format
|
||||
}
|
||||
|
||||
v, err := eqb.encodeExtendedParamValue(m, oid, format, arg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
eqb.ParamFormats = append(eqb.ParamFormats, format)
|
||||
eqb.ParamValues = append(eqb.ParamValues, v)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// appendResultFormat appends a result format to the query.
|
||||
func (eqb *ExtendedQueryBuilder) appendResultFormat(format int16) {
|
||||
eqb.ResultFormats = append(eqb.ResultFormats, format)
|
||||
}
|
||||
|
||||
// reset readies eqb to build another query.
|
||||
func (eqb *ExtendedQueryBuilder) reset() {
|
||||
eqb.ParamValues = eqb.ParamValues[0:0]
|
||||
eqb.paramValueBytes = eqb.paramValueBytes[0:0]
|
||||
eqb.ParamFormats = eqb.ParamFormats[0:0]
|
||||
eqb.ResultFormats = eqb.ResultFormats[0:0]
|
||||
|
||||
if cap(eqb.ParamValues) > 64 {
|
||||
eqb.ParamValues = make([][]byte, 0, 64)
|
||||
}
|
||||
|
||||
if cap(eqb.paramValueBytes) > 256 {
|
||||
eqb.paramValueBytes = make([]byte, 0, 256)
|
||||
}
|
||||
|
||||
if cap(eqb.ParamFormats) > 64 {
|
||||
eqb.ParamFormats = make([]int16, 0, 64)
|
||||
}
|
||||
if cap(eqb.ResultFormats) > 64 {
|
||||
eqb.ResultFormats = make([]int16, 0, 64)
|
||||
}
|
||||
}
|
||||
|
||||
func (eqb *ExtendedQueryBuilder) encodeExtendedParamValue(m *pgtype.Map, oid uint32, formatCode int16, arg any) ([]byte, error) {
|
||||
if eqb.paramValueBytes == nil {
|
||||
eqb.paramValueBytes = make([]byte, 0, 128)
|
||||
}
|
||||
|
||||
pos := len(eqb.paramValueBytes)
|
||||
|
||||
buf, err := m.Encode(oid, formatCode, arg, eqb.paramValueBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if buf == nil {
|
||||
return nil, nil
|
||||
}
|
||||
eqb.paramValueBytes = buf
|
||||
return eqb.paramValueBytes[pos:], nil
|
||||
}
|
||||
|
||||
// chooseParameterFormatCode determines the correct format code for an
|
||||
// argument to a prepared statement. It defaults to TextFormatCode if no
|
||||
// determination can be made.
|
||||
func (eqb *ExtendedQueryBuilder) chooseParameterFormatCode(m *pgtype.Map, oid uint32, arg any) int16 {
|
||||
switch arg.(type) {
|
||||
case string, *string:
|
||||
return TextFormatCode
|
||||
}
|
||||
|
||||
return m.FormatCodeForOID(oid)
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// Package iobufpool implements a global segregated-fit pool of buffers for IO.
|
||||
//
|
||||
// It uses *[]byte instead of []byte to avoid the sync.Pool allocation with Put. Unfortunately, using a pointer to avoid
|
||||
// an allocation is purposely not documented. https://github.com/golang/go/issues/16323
|
||||
package iobufpool
|
||||
|
||||
import "sync"
|
||||
|
||||
const minPoolExpOf2 = 8
|
||||
|
||||
var pools [18]*sync.Pool
|
||||
|
||||
func init() {
|
||||
for i := range pools {
|
||||
bufLen := 1 << (minPoolExpOf2 + i)
|
||||
pools[i] = &sync.Pool{
|
||||
New: func() any {
|
||||
buf := make([]byte, bufLen)
|
||||
return &buf
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get gets a []byte of len size with cap <= size*2.
|
||||
func Get(size int) *[]byte {
|
||||
i := getPoolIdx(size)
|
||||
if i >= len(pools) {
|
||||
buf := make([]byte, size)
|
||||
return &buf
|
||||
}
|
||||
|
||||
ptrBuf := (pools[i].Get().(*[]byte))
|
||||
*ptrBuf = (*ptrBuf)[:size]
|
||||
|
||||
return ptrBuf
|
||||
}
|
||||
|
||||
func getPoolIdx(size int) int {
|
||||
size--
|
||||
size >>= minPoolExpOf2
|
||||
i := 0
|
||||
for size > 0 {
|
||||
size >>= 1
|
||||
i++
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
// Put returns buf to the pool.
|
||||
func Put(buf *[]byte) {
|
||||
i := putPoolIdx(cap(*buf))
|
||||
if i < 0 {
|
||||
return
|
||||
}
|
||||
|
||||
pools[i].Put(buf)
|
||||
}
|
||||
|
||||
func putPoolIdx(size int) int {
|
||||
minPoolSize := 1 << minPoolExpOf2
|
||||
for i := range pools {
|
||||
if size == minPoolSize<<i {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
# pgio
|
||||
|
||||
Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol.
|
||||
|
||||
pgio provides functions for appending integers to a []byte while doing byte
|
||||
order conversion.
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol.
|
||||
/*
|
||||
pgio provides functions for appending integers to a []byte while doing byte
|
||||
order conversion.
|
||||
*/
|
||||
package pgio
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package pgio
|
||||
|
||||
import "encoding/binary"
|
||||
|
||||
func AppendUint16(buf []byte, n uint16) []byte {
|
||||
wp := len(buf)
|
||||
buf = append(buf, 0, 0)
|
||||
binary.BigEndian.PutUint16(buf[wp:], n)
|
||||
return buf
|
||||
}
|
||||
|
||||
func AppendUint32(buf []byte, n uint32) []byte {
|
||||
wp := len(buf)
|
||||
buf = append(buf, 0, 0, 0, 0)
|
||||
binary.BigEndian.PutUint32(buf[wp:], n)
|
||||
return buf
|
||||
}
|
||||
|
||||
func AppendUint64(buf []byte, n uint64) []byte {
|
||||
wp := len(buf)
|
||||
buf = append(buf, 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
binary.BigEndian.PutUint64(buf[wp:], n)
|
||||
return buf
|
||||
}
|
||||
|
||||
func AppendInt16(buf []byte, n int16) []byte {
|
||||
return AppendUint16(buf, uint16(n))
|
||||
}
|
||||
|
||||
func AppendInt32(buf []byte, n int32) []byte {
|
||||
return AppendUint32(buf, uint32(n))
|
||||
}
|
||||
|
||||
func AppendInt64(buf []byte, n int64) []byte {
|
||||
return AppendUint64(buf, uint64(n))
|
||||
}
|
||||
|
||||
func SetInt32(buf []byte, n int32) {
|
||||
binary.BigEndian.PutUint32(buf, uint32(n))
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package sanitize
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Part is either a string or an int. A string is raw SQL. An int is a
|
||||
// argument placeholder.
|
||||
type Part any
|
||||
|
||||
type Query struct {
|
||||
Parts []Part
|
||||
}
|
||||
|
||||
// utf.DecodeRune returns the utf8.RuneError for errors. But that is actually rune U+FFFD -- the unicode replacement
|
||||
// character. utf8.RuneError is not an error if it is also width 3.
|
||||
//
|
||||
// https://github.com/jackc/pgx/issues/1380
|
||||
const replacementcharacterwidth = 3
|
||||
|
||||
func (q *Query) Sanitize(args ...any) (string, error) {
|
||||
argUse := make([]bool, len(args))
|
||||
buf := &bytes.Buffer{}
|
||||
|
||||
for _, part := range q.Parts {
|
||||
var str string
|
||||
switch part := part.(type) {
|
||||
case string:
|
||||
str = part
|
||||
case int:
|
||||
argIdx := part - 1
|
||||
|
||||
if argIdx < 0 {
|
||||
return "", fmt.Errorf("first sql argument must be > 0")
|
||||
}
|
||||
|
||||
if argIdx >= len(args) {
|
||||
return "", fmt.Errorf("insufficient arguments")
|
||||
}
|
||||
arg := args[argIdx]
|
||||
switch arg := arg.(type) {
|
||||
case nil:
|
||||
str = "null"
|
||||
case int64:
|
||||
str = strconv.FormatInt(arg, 10)
|
||||
case float64:
|
||||
str = strconv.FormatFloat(arg, 'f', -1, 64)
|
||||
case bool:
|
||||
str = strconv.FormatBool(arg)
|
||||
case []byte:
|
||||
str = QuoteBytes(arg)
|
||||
case string:
|
||||
str = QuoteString(arg)
|
||||
case time.Time:
|
||||
str = arg.Truncate(time.Microsecond).Format("'2006-01-02 15:04:05.999999999Z07:00:00'")
|
||||
default:
|
||||
return "", fmt.Errorf("invalid arg type: %T", arg)
|
||||
}
|
||||
argUse[argIdx] = true
|
||||
|
||||
// Prevent SQL injection via Line Comment Creation
|
||||
// https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p
|
||||
str = " " + str + " "
|
||||
default:
|
||||
return "", fmt.Errorf("invalid Part type: %T", part)
|
||||
}
|
||||
buf.WriteString(str)
|
||||
}
|
||||
|
||||
for i, used := range argUse {
|
||||
if !used {
|
||||
return "", fmt.Errorf("unused argument: %d", i)
|
||||
}
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
func NewQuery(sql string) (*Query, error) {
|
||||
l := &sqlLexer{
|
||||
src: sql,
|
||||
stateFn: rawState,
|
||||
}
|
||||
|
||||
for l.stateFn != nil {
|
||||
l.stateFn = l.stateFn(l)
|
||||
}
|
||||
|
||||
query := &Query{Parts: l.parts}
|
||||
|
||||
return query, nil
|
||||
}
|
||||
|
||||
func QuoteString(str string) string {
|
||||
return "'" + strings.ReplaceAll(str, "'", "''") + "'"
|
||||
}
|
||||
|
||||
func QuoteBytes(buf []byte) string {
|
||||
return `'\x` + hex.EncodeToString(buf) + "'"
|
||||
}
|
||||
|
||||
type sqlLexer struct {
|
||||
src string
|
||||
start int
|
||||
pos int
|
||||
nested int // multiline comment nesting level.
|
||||
stateFn stateFn
|
||||
parts []Part
|
||||
}
|
||||
|
||||
type stateFn func(*sqlLexer) stateFn
|
||||
|
||||
func rawState(l *sqlLexer) stateFn {
|
||||
for {
|
||||
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
|
||||
switch r {
|
||||
case 'e', 'E':
|
||||
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if nextRune == '\'' {
|
||||
l.pos += width
|
||||
return escapeStringState
|
||||
}
|
||||
case '\'':
|
||||
return singleQuoteState
|
||||
case '"':
|
||||
return doubleQuoteState
|
||||
case '$':
|
||||
nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if '0' <= nextRune && nextRune <= '9' {
|
||||
if l.pos-l.start > 0 {
|
||||
l.parts = append(l.parts, l.src[l.start:l.pos-width])
|
||||
}
|
||||
l.start = l.pos
|
||||
return placeholderState
|
||||
}
|
||||
case '-':
|
||||
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if nextRune == '-' {
|
||||
l.pos += width
|
||||
return oneLineCommentState
|
||||
}
|
||||
case '/':
|
||||
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if nextRune == '*' {
|
||||
l.pos += width
|
||||
return multilineCommentState
|
||||
}
|
||||
case utf8.RuneError:
|
||||
if width != replacementcharacterwidth {
|
||||
if l.pos-l.start > 0 {
|
||||
l.parts = append(l.parts, l.src[l.start:l.pos])
|
||||
l.start = l.pos
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func singleQuoteState(l *sqlLexer) stateFn {
|
||||
for {
|
||||
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
|
||||
switch r {
|
||||
case '\'':
|
||||
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if nextRune != '\'' {
|
||||
return rawState
|
||||
}
|
||||
l.pos += width
|
||||
case utf8.RuneError:
|
||||
if width != replacementcharacterwidth {
|
||||
if l.pos-l.start > 0 {
|
||||
l.parts = append(l.parts, l.src[l.start:l.pos])
|
||||
l.start = l.pos
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func doubleQuoteState(l *sqlLexer) stateFn {
|
||||
for {
|
||||
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
|
||||
switch r {
|
||||
case '"':
|
||||
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if nextRune != '"' {
|
||||
return rawState
|
||||
}
|
||||
l.pos += width
|
||||
case utf8.RuneError:
|
||||
if width != replacementcharacterwidth {
|
||||
if l.pos-l.start > 0 {
|
||||
l.parts = append(l.parts, l.src[l.start:l.pos])
|
||||
l.start = l.pos
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// placeholderState consumes a placeholder value. The $ must have already has
|
||||
// already been consumed. The first rune must be a digit.
|
||||
func placeholderState(l *sqlLexer) stateFn {
|
||||
num := 0
|
||||
|
||||
for {
|
||||
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
|
||||
if '0' <= r && r <= '9' {
|
||||
num *= 10
|
||||
num += int(r - '0')
|
||||
} else {
|
||||
l.parts = append(l.parts, num)
|
||||
l.pos -= width
|
||||
l.start = l.pos
|
||||
return rawState
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func escapeStringState(l *sqlLexer) stateFn {
|
||||
for {
|
||||
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
|
||||
switch r {
|
||||
case '\\':
|
||||
_, width = utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
case '\'':
|
||||
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if nextRune != '\'' {
|
||||
return rawState
|
||||
}
|
||||
l.pos += width
|
||||
case utf8.RuneError:
|
||||
if width != replacementcharacterwidth {
|
||||
if l.pos-l.start > 0 {
|
||||
l.parts = append(l.parts, l.src[l.start:l.pos])
|
||||
l.start = l.pos
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func oneLineCommentState(l *sqlLexer) stateFn {
|
||||
for {
|
||||
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
|
||||
switch r {
|
||||
case '\\':
|
||||
_, width = utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
case '\n', '\r':
|
||||
return rawState
|
||||
case utf8.RuneError:
|
||||
if width != replacementcharacterwidth {
|
||||
if l.pos-l.start > 0 {
|
||||
l.parts = append(l.parts, l.src[l.start:l.pos])
|
||||
l.start = l.pos
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func multilineCommentState(l *sqlLexer) stateFn {
|
||||
for {
|
||||
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
|
||||
switch r {
|
||||
case '/':
|
||||
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if nextRune == '*' {
|
||||
l.pos += width
|
||||
l.nested++
|
||||
}
|
||||
case '*':
|
||||
nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if nextRune != '/' {
|
||||
continue
|
||||
}
|
||||
|
||||
l.pos += width
|
||||
if l.nested == 0 {
|
||||
return rawState
|
||||
}
|
||||
l.nested--
|
||||
|
||||
case utf8.RuneError:
|
||||
if width != replacementcharacterwidth {
|
||||
if l.pos-l.start > 0 {
|
||||
l.parts = append(l.parts, l.src[l.start:l.pos])
|
||||
l.start = l.pos
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SanitizeSQL replaces placeholder values with args. It quotes and escapes args
|
||||
// as necessary. This function is only safe when standard_conforming_strings is
|
||||
// on.
|
||||
func SanitizeSQL(sql string, args ...any) (string, error) {
|
||||
query, err := NewQuery(sql)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return query.Sanitize(args...)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user