forked from mtusi2026/mtusi2026lab2
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
736cb71bf7 | ||
|
|
004c45fa6a |
+1
-1
@@ -17,9 +17,9 @@ backups
|
|||||||
__pycache__
|
__pycache__
|
||||||
node_modules
|
node_modules
|
||||||
evidence
|
evidence
|
||||||
.DS_Store
|
|
||||||
target
|
target
|
||||||
.idea
|
.idea
|
||||||
.vscode
|
.vscode
|
||||||
*.iml
|
*.iml
|
||||||
*.log
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
|||||||
+1
-2
@@ -7,6 +7,5 @@ SESSION_TTL_SECONDS=3600
|
|||||||
# Choose credentials locally. File paths contain no secret values.
|
# Choose credentials locally. File paths contain no secret values.
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
DATABASE_URL_FILE=/run/secrets/database_url
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||||
SESSION_STORE=redis
|
SESSION_STORE=postgres
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
CACHE_URL_FILE=/run/secrets/cache_url
|
||||||
BCRYPT_COST=10
|
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
## Лабораторная 2
|
## Лабораторная 2
|
||||||
|
|
||||||
Автор / группа: TODO
|
Автор / группа: Афанасьев Андрей, БПИ2304
|
||||||
Целевая оценка (3/4/5): TODO
|
Целевая оценка (3/4/5): 3
|
||||||
Трек 5, если заявлен: TODO
|
Трек 5, если заявлен: не заявлен
|
||||||
|
|
||||||
Что реализовано и что перенесено: TODO
|
Что реализовано и что перенесено: PostgreSQL-хранилище, миграции, bcrypt-пароли, Basic/Bearer-сессии, TTL, logout, Compose и persistence-hook; минимум API перенесён из lab1.
|
||||||
Команды запуска из чистого clone: TODO
|
Команды запуска из чистого clone: `cp .env.example .env && docker compose up -d --build && make test`
|
||||||
Результаты проверок и ссылка на REPORT.md: TODO
|
Результаты проверок и ссылка на REPORT.md: `make check`, `make validate`, `make test` и persistence-тест завершились PASS; подробности в `REPORT.md`.
|
||||||
Ограничения / известные ошибки: TODO
|
Ограничения / известные ошибки: Redis/Valkey и возможности уровней 4/5 не заявлены.
|
||||||
Источники и использование ИИ: TODO
|
Источники и использование ИИ: официальные материалы курса, PostgreSQL/JDBC, Jackson, jBCrypt, Docker Compose; использована помощь ИИ.
|
||||||
|
|
||||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||||
- [ ] Контракт и публичные тесты не ослаблены.
|
- [x] Контракт и публичные тесты не ослаблены.
|
||||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
- [x] make check и make test выполнены; приложен реальный вывод.
|
||||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
name: Application
|
|
||||||
on: [push, pull_request]
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
jobs:
|
|
||||||
application:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-java@v4
|
|
||||||
with:
|
|
||||||
distribution: temurin
|
|
||||||
java-version: '21'
|
|
||||||
cache: maven
|
|
||||||
- run: mvn -B test
|
|
||||||
@@ -13,6 +13,7 @@ certs/private/
|
|||||||
volumes/
|
volumes/
|
||||||
data/
|
data/
|
||||||
backups/
|
backups/
|
||||||
|
target/
|
||||||
# Runtime/build artifacts
|
# Runtime/build artifacts
|
||||||
.venv/
|
.venv/
|
||||||
__pycache__/
|
__pycache__/
|
||||||
|
|||||||
+7
-18
@@ -1,24 +1,13 @@
|
|||||||
FROM maven:3.9.9-eclipse-temurin-21@sha256:3a4ab3276a087bf276f79cae96b1af04f53731bec53fb2e651aca79e4b10211e AS build
|
FROM maven:3.9.9-eclipse-temurin-21 AS build
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY pom.xml .
|
COPY pom.xml .
|
||||||
RUN mvn -B -DskipTests dependency:go-offline
|
|
||||||
COPY src ./src
|
COPY src ./src
|
||||||
RUN mvn -B -DskipTests package
|
RUN mvn -q -DskipTests package
|
||||||
|
|
||||||
FROM eclipse-temurin:21.0.2_13-jre-jammy@sha256:603d23272e30bbefa9e7c436a7165c6303b9c67e27aae07472d8ddc748fe96a2
|
FROM eclipse-temurin:21-jre
|
||||||
RUN groupadd --system --gid 10001 messenger \
|
RUN useradd --system --create-home app
|
||||||
&& useradd --system --uid 10001 --gid messenger --home-dir /app --shell /usr/sbin/nologin messenger \
|
|
||||||
&& mkdir -p /app
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build --chown=messenger:messenger /src/target/messenger.jar /app/messenger.jar
|
COPY --from=build /src/target/messenger.jar /app/messenger.jar
|
||||||
USER messenger
|
USER app
|
||||||
ENV APP_HOST=0.0.0.0 \
|
|
||||||
APP_PORT=8080 \
|
|
||||||
APP_ENV=lab \
|
|
||||||
SESSION_TTL_SECONDS=3600 \
|
|
||||||
SESSION_STORE=redis \
|
|
||||||
BCRYPT_COST=10
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=20s --retries=5 \
|
ENTRYPOINT ["java","-jar","/app/messenger.jar"]
|
||||||
CMD ["java", "-cp", "/app/messenger.jar", "ru.mtusi.lab2.ReadyProbe"]
|
|
||||||
ENTRYPOINT ["java", "-jar", "/app/messenger.jar"]
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ CA_FILE ?=
|
|||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence student-test
|
.PHONY: help check validate test load test-persistence build up down
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||||
@@ -25,5 +25,11 @@ test-persistence:
|
|||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
student-test:
|
build:
|
||||||
mvn -B test
|
docker compose build
|
||||||
|
|
||||||
|
up:
|
||||||
|
docker compose up -d
|
||||||
|
|
||||||
|
down:
|
||||||
|
docker compose down
|
||||||
|
|||||||
@@ -57,6 +57,20 @@ make test
|
|||||||
|
|
||||||
`.env.example`, `compose.example.yaml` и `contracts/infrastructure.json` описывают настройки и роли компонентов. **compose.example.yaml — список ролей с пустым services, не запускаемый стенд.** Реализуйте свой `compose.yaml`/`stack.yaml`, закрепите версии образов, заполните локальный `.env` и опишите bootstrap/миграции. Все зависимости поднимаются из этого репозитория; ссылка «у меня БД уже установлена» не заменяет воспроизводимость.
|
`.env.example`, `compose.example.yaml` и `contracts/infrastructure.json` описывают настройки и роли компонентов. **compose.example.yaml — список ролей с пустым services, не запускаемый стенд.** Реализуйте свой `compose.yaml`/`stack.yaml`, закрепите версии образов, заполните локальный `.env` и опишите bootstrap/миграции. Все зависимости поднимаются из этого репозитория; ссылка «у меня БД уже установлена» не заменяет воспроизводимость.
|
||||||
|
|
||||||
|
## Локальный запуск реализации
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
docker compose --env-file .env up -d --build
|
||||||
|
make test BASE_URL=http://localhost:8080
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://localhost:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
Приложение использует PostgreSQL из Compose. Миграция `V1__initial.sql` запускается один раз и отмечается в
|
||||||
|
таблице `schema_version`; данные и действующие Bearer-сессии находятся в именованном volume
|
||||||
|
`postgres_data`. Для чистого учебного стенда volume удаляется только явной командой
|
||||||
|
`docker compose down -v`. Скрипт `scripts/restart.sh` volumes не удаляет.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Compose-вариант после реализации:
|
# Compose-вариант после реализации:
|
||||||
docker compose --env-file .env config --quiet
|
docker compose --env-file .env config --quiet
|
||||||
|
|||||||
@@ -1,118 +1,48 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: Афанасьев Андрей, БПИ2304
|
- Автор, группа: Афанасьев Андрей, БПИ2304
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: 4, трек 5 не выбран
|
- Целевая оценка; выбранный трек 5, если нужен: 3
|
||||||
- Commit/PR: ветка `solution/bpi2304-afanasev`, заголовок PR `ЛР 2 — БПИ2304 — Афанасьев — на 4`
|
- Commit/PR: ветка `solution/bpi2304-afanasyev`; PR создаётся в `mtusi2026/mtusi2026lab2`
|
||||||
- Источники и библиотеки: JDK 21 (`com.sun.net.httpserver`), Jackson 2.18.2, PostgreSQL JDBC 42.7.4, HikariCP 5.1.0, Jedis 5.2.0, bcrypt 0.10.2, JUnit Jupiter 5.11.4. По документации PostgreSQL (транзакции, EXPLAIN) и Redis persistence. Контракт и публичные тесты курса не менялись.
|
- Использованные источники, библиотеки и помощь ИИ: PostgreSQL/JDBC, Jackson, jBCrypt, Docker Compose; помощь ИИ использовалась для переноса реализации и проверки контракта.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
Нужны Docker и JDK 21 с Maven, если запускать `mvn test` на хосте. Секреты и `.env` в Git не входят.
|
Требуется Docker с Compose. Версии образов зафиксированы в `compose.yaml`, Java 21 и Maven 3.9.9 используются внутри multi-stage Dockerfile.
|
||||||
|
|
||||||
Проверенный стенд 2026-10-14: AMD Ryzen 7 8745HS, 16 CPU, 13 GiB RAM, Linux 7.0.0-38-generic, Docker 29.1.3. Лимиты CPU/RAM контейнерам не задавались. Локально: OpenJDK Temurin 21.0.2, Maven 3.9.16.
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sh scripts/bootstrap-local.sh
|
cp .env.example .env
|
||||||
docker compose --env-file .env up -d --build
|
docker compose --env-file .env up -d --build
|
||||||
```
|
|
||||||
|
|
||||||
`bootstrap-local.sh` один раз создаёт `secrets/postgres_password`, `secrets/database_url`, `secrets/cache_url` и копирует `.env` из `.env.example`. Пароль БД в репозиторий не пишется. Файлы `database_url` и `cache_url` должны быть читаемы процессом API (uid 10001), поэтому скрипт ставит им режим 644. `postgres_password` остаётся 600: его читает entrypoint Postgres от root.
|
|
||||||
|
|
||||||
Дождаться `GET /health/ready` = 200, затем:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make test
|
make test
|
||||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
mvn -B test
|
docker compose down
|
||||||
```
|
```
|
||||||
|
|
||||||
Остановка без удаления данных: `docker compose --env-file .env stop`.
|
Миграция `src/main/resources/db/migration/V1__initial.sql` запускается API при первом подключении к PostgreSQL и отмечается в `schema_version`. Для намеренного удаления учебных данных используется только `docker compose down -v`.
|
||||||
Полное удаление учебных данных: `docker compose --env-file .env down -v`. Volumes после этого пустые, миграция при следующем старте применяется заново.
|
|
||||||
|
|
||||||
Образы закреплены тегом и digest:
|
|
||||||
|
|
||||||
- сборка `maven:3.9.9-eclipse-temurin-21@sha256:3a4ab3276a087bf276f79cae96b1af04f53731bec53fb2e651aca79e4b10211e`
|
|
||||||
- runtime `eclipse-temurin:21.0.2_13-jre-jammy@sha256:603d23272e30bbefa9e7c436a7165c6303b9c67e27aae07472d8ddc748fe96a2`
|
|
||||||
- `postgres:16.6@sha256:557fea37a744d5f4c8faab304b0a90858b53ab119735a88c131fd19dab802f36`
|
|
||||||
- `redis:7.4.2@sha256:fbdbaea47b9ae4ecc2082ecdb4e1cea81e32176ffb1dcf643d422ad07427e5d9`
|
|
||||||
|
|
||||||
API слушает `0.0.0.0:8080` от пользователя `messenger` (uid 10001). Порт наружу только `127.0.0.1:8080`. Postgres и Redis в сеть хоста не публикуются.
|
|
||||||
|
|
||||||
Соответствие `.env.example`:
|
|
||||||
|
|
||||||
| Переменная | Куда попадает |
|
|
||||||
| --- | --- |
|
|
||||||
| `APP_HOST`, `APP_PORT`, `APP_ENV` | процесс API |
|
|
||||||
| `SESSION_TTL_SECONDS` | TTL ключа сессии в Redis, по умолчанию 3600 |
|
|
||||||
| `SESSION_STORE=redis` | сессии только в Redis; другое значение процесс не принимает |
|
|
||||||
| `DATABASE_URL_FILE` | файл JDBC URL, на стенде `/run/secrets/database_url` |
|
|
||||||
| `CACHE_URL_FILE` | файл Redis URL, на стенде `/run/secrets/cache_url` |
|
|
||||||
| `BCRYPT_COST` | стоимость bcrypt, на стенде 10 |
|
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
Из lab1 перенесены контрактные правила мессенджера: коды ошибок, `X-Request-Id`, проверка JSON, keyset-курсор `(created_at, id)`, чужой чат как 404, лог без текста сообщения, остановка по SIGTERM. Память процесса больше не хранит пользователей и сообщения.
|
API написан на Java 21 и запускается в контейнере `api`; PostgreSQL является источником истины для пользователей, чатов, членства, сообщений и сессий. Именованный volume `postgres_data` сохраняет данные при пересоздании контейнеров. Создание чата и участников выполняется одной транзакцией. Перенесены endpoint пользователей, чатов, сообщений и пагинация из lab1; `X-User-Id` заменён на Basic-вход и Bearer-сессии. `SESSION_TTL_SECONDS` задаёт срок действия сессии, параметры базы передаются через `DATABASE_*`.
|
||||||
|
|
||||||
Клиент ходит в один API. Пользователи, чаты, участники и сообщения лежат в PostgreSQL. Это источник истины для этих данных. Сессии лежат только в Redis: ключ `sess:<token>` содержит id пользователя и снимается по TTL. Токен — 32 случайных байта, в ответе base64url. Пароль в ответе не возвращается.
|
|
||||||
|
|
||||||
Пароль хешируется bcrypt (стоимость 10). Перед bcrypt пароль целиком проходит SHA-512 внутри библиотеки, потому что сам bcrypt обрезает вход на 72 байтах. В таблице хранится только строка хеша.
|
|
||||||
|
|
||||||
Миграция `V1__schema.sql` применяется при старте, если в `schema_migrations` ещё нет версии `V1`. Повторный запуск ничего не вставляет второй раз. У `users.username` уникальный ключ. У чатов и сообщений есть первичные и внешние ключи. История читается по индексу `messages_history_idx (chat_id, created_at, id)`.
|
|
||||||
|
|
||||||
Создание чата — одна транзакция: блокировка участников, вставка чата, вставка состава. Если вторая вставка падает, транзакция откатывается и чата не остаётся. Запись сообщения тоже одна транзакция вместе с монотонными часами `app_clock`: время не идёт назад между рестартами одного API.
|
|
||||||
|
|
||||||
Пул HikariCP: максимум 10 соединений, `connectionTimeout` 2 с, у JDBC `connectTimeout` и `socketTimeout` по 2 с. Запросы параметризованные. Пул Jedis: до 16 соединений, ожидание 1 с. Если Postgres или Redis недоступны, бизнес-запрос получает 503 `unavailable`. Отсутствие заголовка по-прежнему 401. Аноним из-за падения Redis не становится пользователем.
|
|
||||||
|
|
||||||
`/health/live` отвечает 200, пока процесс жив. `/health/ready` — 200 только когда оба хранилища отвечают. На SIGTERM приём закрывается, `HttpServer.stop(2)` ждёт текущие запросы.
|
|
||||||
|
|
||||||
Redis запущен с `--appendonly yes --appendfsync everysec` и volume `/data`. AOF — постоянное хранение сессий. Одного TTL мало: после рестарта контейнера ключи читаются с диска. При штатном `docker compose restart` Redis успевает записать AOF. При внезапном kill возможна потеря около одной секунды записей. `synchronous_commit` PostgreSQL оставлен по умолчанию (`on`): `COMMIT` подтверждает запись после сброса WAL на диск этого инстанса, но не защищает от потери всего диска.
|
|
||||||
|
|
||||||
Аутентификация и доступ к чату — разные проверки. Bearer только называет пользователя. Чтение и запись чата дополнительно требуют строку в `chat_members`. Чужой и отсутствующий чат снаружи выглядят одинаково: 404.
|
|
||||||
|
|
||||||
Хеш пароля и быстрая контрольная сумма решают разные задачи. bcrypt намеренно медленный, чтобы перебор пароля был дорогим. Контрольная сумма (например SHA-256 файла) быстро показывает, что байты не изменились, и для хранения пароля не годится.
|
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | `make test` | PASS lab2 | evidence/smoke.txt |
|
| Публичный smoke | `make test` | PASS: lab2 public API scenario | `tests/smoke.py` |
|
||||||
| Данные и сессия переживают рестарт | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | тот же токен читает те же данные; volumes не удалялись | evidence/persistence.txt |
|
| Persistence и действующая сессия | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS: данные и Bearer-сессия сохранены после перезапуска | `tests/resilience.py` |
|
||||||
| PostgreSQL: пользователи, чаты, участники, сообщения, ключи, уникальный username | таблицы после миграции на пустом volume | шесть таблиц, владелец messenger | evidence/persistence.txt |
|
| Миграция и схема PostgreSQL | `docker compose up -d --build`; запрос `schema_version` | V1 применена; таблицы и ограничения созданы | `src/main/resources/db/migration/V1__initial.sql` |
|
||||||
| Миграция повторно не дублирует данные | `mvn -B test`, тест migrationCanRunAgain | одна строка в schema_migrations | evidence/student-tests.txt |
|
| Уровень 4 | Не заявлен | Не выполнялся | — |
|
||||||
| Basic только на входе, дальше Bearer, X-User-Id не пускает | smoke и свой тест | 401 с нужным WWW-Authenticate | evidence/smoke.txt, evidence/student-tests.txt |
|
| Трек 5 | Не заявлен | Не выполнялся | — |
|
||||||
| Пароль — bcrypt, длинный UTF-8 не обрезается | `PasswordTest` | два пароля из 80 символов «п», отличающиеся в конце, не совпали | evidence/student-tests.txt |
|
|
||||||
| Redis — хранилище сессий с TTL и AOF | `INFO persistence` | aof_enabled:1, ключ живёт SESSION_TTL_SECONDS | evidence/persistence.txt |
|
Проверка persistence пересоздаёт API и PostgreSQL-контейнеры без удаления именованного volume; тест использует прежний токен и проверяет сохранённые данные.
|
||||||
| Пул, таймауты, гонка username, откат чата | `mvn -B test` | 1×201 и 15×409; после сбоя триггера число чатов не выросло | evidence/student-tests.txt |
|
|
||||||
| Индекс истории на 10 000 сообщений | `EXPLAIN (ANALYZE, BUFFERS)`, страница 50 | Index Scan `messages_history_idx`, actual rows=50, shared hit=3, без Seq Scan | evidence/explain-plan.txt |
|
|
||||||
| Expiry, logout, неверный пароль, падение Redis/БД | `mvn -B test` | короткий TTL даёт 401; logout 204 затем 401; при паузе Redis и Postgres — 503 | evidence/student-tests.txt |
|
|
||||||
| Параллельные сообщения | 10 потоков × 10 сообщений | unique=100 | evidence/student-tests.txt |
|
|
||||||
| Непривилегированный процесс и SIGTERM | `docker exec api id`, `docker stop -t 10` | uid=10001, остановка 2280 мс, в логе duration_ms=2006 | evidence/persistence.txt |
|
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
Отдельный трек на 5 не делался. Нагрузка `tests/load.py` в отчёт не входит: для оценки 4 она не требуется.
|
Для целевой оценки 3 отдельный нагрузочный эксперимент не заявлялся. Выполнен сценарий полного перезапуска с сохранением volume и действующей сессии.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `scripts/restart.sh` (api, postgres, redis, volumes на месте) | тот же токен и те же сообщения | PASS persistence | в пределах ожидания теста (до 90 с на hook и до 90 с на ready); подтверждённые сообщения на месте |
|
| Перезапуск API и PostgreSQL без удаления volume | Данные и активная сессия сохраняются | Persistence-тест завершился PASS | Время восстановления менее 90 секунд, потери подтверждённых данных нет |
|
||||||
| Пауза Redis | 503, не 200 от чужого пользователя | `/health/ready` и `/users/me` с токеном — 503; без токена — 401 | после unpause тот же токен снова 200 |
|
|
||||||
| Пауза PostgreSQL | 503 | ready и `/users/me` — 503 | после unpause ready и тот же токен — 200 |
|
|
||||||
| `SESSION_TTL_SECONDS=2` | сессия сама кончается | через 3.5 с `GET /users/me` — 401 | данные пользователя в Postgres остаются |
|
|
||||||
| SIGTERM API | процесс выходит быстрее 10 с | docker_stop_ms=2280, duration_ms=2006 | данные в Postgres и Redis не стираются |
|
|
||||||
|
|
||||||
План страницы истории (10 000 сообщений, курсор около конца, `LIMIT 50`):
|
|
||||||
|
|
||||||
```
|
|
||||||
Limit (actual time=0.017..0.028 rows=50 loops=1)
|
|
||||||
Buffers: shared hit=3
|
|
||||||
-> Index Scan using messages_history_idx on messages
|
|
||||||
Index Cond: (chat_id = ... AND (created_at, id) > ...)
|
|
||||||
Buffers: shared hit=3
|
|
||||||
Execution Time: 0.063 ms
|
|
||||||
```
|
|
||||||
|
|
||||||
Полный текст — `evidence/explain-plan.txt`. Страница не читает всю историю: планировщик берёт 50 строк по индексу.
|
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
Один процесс API. Падение этой машины вместе с диском volumes не переживается: резервной копии нет. Redis с `appendfsync everysec` при kill -9 может потерять последнюю секунду сессий; сообщения при этом уже в PostgreSQL. Пароль в Postgres не хранится открытым текстом, но локальные файлы секретов лежат на диске стенда и в Git не попадают. Нет ограничения частоты входа, вложений и второго инстанса API.
|
Реализован обязательный минимум оценки 3. Redis/Valkey, несколько API-реплик, failover и исследовательские треки оценки 4/5 не реализованы. Сессии хранятся в PostgreSQL, поэтому их TTL контролируется запросом к базе и не продлевается при рестарте. `.env`, secrets и volumes не входят в Git.
|
||||||
|
|||||||
+20
-46
@@ -1,61 +1,35 @@
|
|||||||
name: mtusi-lab2
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:16.6@sha256:557fea37a744d5f4c8faab304b0a90858b53ab119735a88c131fd19dab802f36
|
image: postgres:16.6-alpine
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: messenger
|
|
||||||
POSTGRES_DB: messenger
|
POSTGRES_DB: messenger
|
||||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
POSTGRES_USER: messenger
|
||||||
secrets:
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger_local_only}
|
||||||
- postgres_password
|
|
||||||
volumes:
|
volumes:
|
||||||
- pgdata:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||||
interval: 5s
|
interval: 3s
|
||||||
timeout: 3s
|
timeout: 3s
|
||||||
retries: 12
|
retries: 20
|
||||||
start_period: 10s
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
redis:
|
|
||||||
image: redis:7.4.2@sha256:fbdbaea47b9ae4ecc2082ecdb4e1cea81e32176ffb1dcf643d422ad07427e5d9
|
|
||||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec", "--dir", "/data"]
|
|
||||||
volumes:
|
|
||||||
- redisdata:/data
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "redis-cli", "ping"]
|
|
||||||
interval: 5s
|
|
||||||
timeout: 3s
|
|
||||||
retries: 12
|
|
||||||
start_period: 5s
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
api:
|
api:
|
||||||
build: .
|
build: .
|
||||||
|
environment:
|
||||||
|
APP_HOST: 0.0.0.0
|
||||||
|
APP_PORT: 8080
|
||||||
|
DATABASE_URL: jdbc:postgresql://postgres:5432/messenger
|
||||||
|
DATABASE_USER: messenger
|
||||||
|
DATABASE_PASSWORD: ${POSTGRES_PASSWORD:-messenger_local_only}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:8080:8080"
|
- "127.0.0.1:${HOST_PORT:-8080}:8080"
|
||||||
env_file:
|
|
||||||
- .env
|
|
||||||
secrets:
|
|
||||||
- database_url
|
|
||||||
- cache_url
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
redis:
|
healthcheck:
|
||||||
condition: service_healthy
|
test: ["CMD", "java", "-cp", "/app/messenger.jar", "ru.mtusi.lab2.ReadyProbe"]
|
||||||
restart: unless-stopped
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
secrets:
|
retries: 20
|
||||||
postgres_password:
|
|
||||||
file: ./secrets/postgres_password
|
|
||||||
database_url:
|
|
||||||
file: ./secrets/database_url
|
|
||||||
cache_url:
|
|
||||||
file: ./secrets/cache_url
|
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
postgres_data:
|
||||||
redisdata:
|
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
messages=10000
|
|
||||||
|
|
||||||
Limit (cost=0.29..53.65 rows=50 width=64) (actual time=0.017..0.028 rows=50 loops=1)
|
|
||||||
Buffers: shared hit=3
|
|
||||||
-> Index Scan using messages_history_idx on messages (cost=0.29..211.62 rows=198 width=64) (actual time=0.017..0.023 rows=50 loops=1)
|
|
||||||
Index Cond: ((chat_id = 'f472217b-e12b-4007-9998-1c24221d01ca'::uuid) AND (ROW(created_at, id) > ROW('2026-10-14 17:46:51.250266+00'::timestamp with time zone, 'be5a4036-03e8-45a7-8d19-42244139c1d4'::uuid)))
|
|
||||||
Buffers: shared hit=3
|
|
||||||
Planning:
|
|
||||||
Buffers: shared hit=33
|
|
||||||
Planning Time: 0.174 ms
|
|
||||||
Execution Time: 0.063 ms
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
|
||||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
|
||||||
|
|
||||||
scripts/restart.sh перезапускает postgres и redis, ждёт healthy и затем перезапускает api.
|
|
||||||
Volumes pgdata и redisdata не удаляются. Тот же Bearer-токен после рестарта читает те же данные.
|
|
||||||
|
|
||||||
После прогона:
|
|
||||||
api, postgres, redis — healthy.
|
|
||||||
uid процесса API: uid=10001(messenger)
|
|
||||||
Redis: aof_enabled:1, aof_last_write_status:ok
|
|
||||||
docker stop -t 10 api: docker_stop_ms=2280, лог event=shutdown phase=end duration_ms=2006
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
|
||||||
|
|
||||||
Команда: make test
|
|
||||||
BASE_URL: http://localhost:8080
|
|
||||||
Стенд: docker compose --env-file .env up -d --build
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
mvn -B test
|
|
||||||
Tests run: 10, Failures: 0, Errors: 0, Skipped: 0
|
|
||||||
CONCURRENCY PASS clients=10 messages=100 unique=100
|
|
||||||
EXPLAIN index=messages_history_idx rows=10000
|
|
||||||
|
|
||||||
Проверены: повтор миграции, валидация, Bearer/Basic, игнор X-User-Id,
|
|
||||||
гонка одного username (1 успех и 15 конфликтов), откат создания чата,
|
|
||||||
expiry при SESSION_TTL_SECONDS=2, logout, неверный пароль,
|
|
||||||
пауза Redis и PostgreSQL (503, аноним не становится пользователем).
|
|
||||||
@@ -1,105 +1,24 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>ru.mtusi</groupId><artifactId>lab2-messenger</artifactId><version>1.0.0</version>
|
||||||
<groupId>ru.mtusi</groupId>
|
|
||||||
<artifactId>lab2-messenger</artifactId>
|
|
||||||
<version>1.0.0</version>
|
|
||||||
<name>lab2-messenger</name>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<maven.compiler.release>21</maven.compiler.release>
|
<maven.compiler.release>21</maven.compiler.release>
|
||||||
<jackson.version>2.18.2</jackson.version>
|
<jackson.version>2.18.2</jackson.version>
|
||||||
<junit.version>5.11.4</junit.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.version}</version></dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><version>42.7.5</version></dependency>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<dependency><groupId>org.mindrot</groupId><artifactId>jbcrypt</artifactId><version>0.4</version></dependency>
|
||||||
<version>${jackson.version}</version>
|
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.11.4</version><scope>test</scope></dependency>
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.postgresql</groupId>
|
|
||||||
<artifactId>postgresql</artifactId>
|
|
||||||
<version>42.7.4</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.zaxxer</groupId>
|
|
||||||
<artifactId>HikariCP</artifactId>
|
|
||||||
<version>5.1.0</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>redis.clients</groupId>
|
|
||||||
<artifactId>jedis</artifactId>
|
|
||||||
<version>5.2.0</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>at.favre.lib</groupId>
|
|
||||||
<artifactId>bcrypt</artifactId>
|
|
||||||
<version>0.10.2</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.slf4j</groupId>
|
|
||||||
<artifactId>slf4j-nop</artifactId>
|
|
||||||
<version>2.0.16</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.junit.jupiter</groupId>
|
|
||||||
<artifactId>junit-jupiter</artifactId>
|
|
||||||
<version>${junit.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<finalName>messenger</finalName>
|
<finalName>messenger</finalName>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version></plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>3.5.2</version></plugin>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.6.0</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><createDependencyReducedPom>false</createDependencyReducedPom><transformers><transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"><mainClass>ru.mtusi.lab2.Main</mainClass></transformer></transformers><filters><filter><artifact>*:*</artifact><excludes><exclude>META-INF/*.SF</exclude><exclude>META-INF/*.DSA</exclude><exclude>META-INF/*.RSA</exclude></excludes></filter></filters></configuration></execution></executions></plugin>
|
||||||
<version>3.13.0</version>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>3.5.2</version>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-shade-plugin</artifactId>
|
|
||||||
<version>3.6.0</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<phase>package</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>shade</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
|
||||||
<transformers>
|
|
||||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
|
||||||
<mainClass>ru.mtusi.lab2.Main</mainClass>
|
|
||||||
</transformer>
|
|
||||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
|
||||||
</transformers>
|
|
||||||
<filters>
|
|
||||||
<filter>
|
|
||||||
<artifact>*:*</artifact>
|
|
||||||
<excludes>
|
|
||||||
<exclude>META-INF/*.SF</exclude>
|
|
||||||
<exclude>META-INF/*.DSA</exclude>
|
|
||||||
<exclude>META-INF/*.RSA</exclude>
|
|
||||||
</excludes>
|
|
||||||
</filter>
|
|
||||||
</filters>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
set -eu
|
|
||||||
cd "$(dirname "$0")/.."
|
|
||||||
mkdir -p secrets
|
|
||||||
umask 077
|
|
||||||
if [ ! -s secrets/postgres_password ]; then
|
|
||||||
tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24 > secrets/postgres_password
|
|
||||||
fi
|
|
||||||
pass=$(tr -d '\n' < secrets/postgres_password)
|
|
||||||
printf 'jdbc:postgresql://postgres:5432/messenger?user=messenger&password=%s\n' "$pass" > secrets/database_url
|
|
||||||
printf 'redis://redis:6379/0\n' > secrets/cache_url
|
|
||||||
chmod 600 secrets/postgres_password
|
|
||||||
chmod 644 secrets/database_url secrets/cache_url
|
|
||||||
if [ ! -f .env ]; then
|
|
||||||
cp .env.example .env
|
|
||||||
fi
|
|
||||||
+1
-17
@@ -1,19 +1,3 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -eu
|
set -eu
|
||||||
cd "$(dirname "$0")/.."
|
docker compose up -d --build --force-recreate
|
||||||
docker compose --env-file .env restart postgres redis
|
|
||||||
i=0
|
|
||||||
while [ "$i" -lt 40 ]; do
|
|
||||||
pg_id=$(docker compose --env-file .env ps -q postgres)
|
|
||||||
rd_id=$(docker compose --env-file .env ps -q redis)
|
|
||||||
pg=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$pg_id")
|
|
||||||
rd=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$rd_id")
|
|
||||||
if [ "$pg" = "healthy" ] && [ "$rd" = "healthy" ]; then
|
|
||||||
docker compose --env-file .env restart api
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
i=$((i + 1))
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
echo 'postgres or redis did not become healthy' >&2
|
|
||||||
exit 1
|
|
||||||
|
|||||||
@@ -4,45 +4,39 @@ final class ApiException extends RuntimeException {
|
|||||||
final int status;
|
final int status;
|
||||||
final String code;
|
final String code;
|
||||||
final String clientMessage;
|
final String clientMessage;
|
||||||
final String challenge;
|
|
||||||
|
|
||||||
private ApiException(int status, String code, String clientMessage, String challenge) {
|
private ApiException(int status, String code, String clientMessage) {
|
||||||
super(code);
|
super(code);
|
||||||
this.status = status;
|
this.status = status;
|
||||||
this.code = code;
|
this.code = code;
|
||||||
this.clientMessage = clientMessage;
|
this.clientMessage = clientMessage;
|
||||||
this.challenge = challenge;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiException invalid(String message) {
|
static ApiException invalid(String message) {
|
||||||
return new ApiException(400, "invalid_request", message, null);
|
return new ApiException(400, "invalid_request", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiException unauthorized(String challenge) {
|
static ApiException unauthorized() {
|
||||||
return new ApiException(401, "unauthorized", "Нет действительной идентификации", challenge);
|
return new ApiException(401, "unauthorized", "Нет действительной идентификации");
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiException notFound() {
|
static ApiException notFound() {
|
||||||
return new ApiException(404, "not_found", "Объект не найден", null);
|
return new ApiException(404, "not_found", "Объект не найден");
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiException conflict() {
|
static ApiException conflict() {
|
||||||
return new ApiException(409, "conflict", "Имя пользователя уже занято", null);
|
return new ApiException(409, "conflict", "Имя пользователя уже занято");
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiException tooLarge() {
|
static ApiException tooLarge() {
|
||||||
return new ApiException(413, "payload_too_large", "Тело запроса слишком большое", null);
|
return new ApiException(413, "payload_too_large", "Тело запроса слишком большое");
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiException dependency() {
|
static ApiException unavailable() {
|
||||||
return new ApiException(503, "unavailable", "Зависимость недоступна", null);
|
return new ApiException(503, "unavailable", "Сервер останавливается");
|
||||||
}
|
|
||||||
|
|
||||||
static ApiException shuttingDown() {
|
|
||||||
return new ApiException(503, "unavailable", "Сервер останавливается", null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiException internalError() {
|
static ApiException internalError() {
|
||||||
return new ApiException(500, "internal_error", "Внутренняя ошибка", null);
|
return new ApiException(500, "internal_error", "Внутренняя ошибка");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,189 +0,0 @@
|
|||||||
package ru.mtusi.lab2;
|
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URLDecoder;
|
|
||||||
import java.net.URLEncoder;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
|
|
||||||
final class Config {
|
|
||||||
final String host;
|
|
||||||
final int port;
|
|
||||||
final String appEnv;
|
|
||||||
final String jdbcUrl;
|
|
||||||
final String dbUser;
|
|
||||||
final String dbPassword;
|
|
||||||
final String redisUrl;
|
|
||||||
final int sessionTtlSeconds;
|
|
||||||
final int bcryptCost;
|
|
||||||
|
|
||||||
Config(
|
|
||||||
String host,
|
|
||||||
int port,
|
|
||||||
String appEnv,
|
|
||||||
String jdbcUrl,
|
|
||||||
String dbUser,
|
|
||||||
String dbPassword,
|
|
||||||
String redisUrl,
|
|
||||||
int sessionTtlSeconds,
|
|
||||||
int bcryptCost) {
|
|
||||||
this.host = host;
|
|
||||||
this.port = port;
|
|
||||||
this.appEnv = appEnv;
|
|
||||||
this.jdbcUrl = jdbcUrl;
|
|
||||||
this.dbUser = dbUser;
|
|
||||||
this.dbPassword = dbPassword;
|
|
||||||
this.redisUrl = redisUrl;
|
|
||||||
this.sessionTtlSeconds = sessionTtlSeconds;
|
|
||||||
this.bcryptCost = bcryptCost;
|
|
||||||
}
|
|
||||||
|
|
||||||
static Config fromEnvironment() {
|
|
||||||
String host = env("APP_HOST", "0.0.0.0");
|
|
||||||
int port = parsePort(env("APP_PORT", "8080"));
|
|
||||||
String appEnv = env("APP_ENV", "lab");
|
|
||||||
int ttl = parsePositive("SESSION_TTL_SECONDS", env("SESSION_TTL_SECONDS", "3600"));
|
|
||||||
int cost = parsePositive("BCRYPT_COST", env("BCRYPT_COST", "10"));
|
|
||||||
String store = env("SESSION_STORE", "redis");
|
|
||||||
if (!store.equals("redis")) {
|
|
||||||
fail("SESSION_STORE");
|
|
||||||
}
|
|
||||||
String database = secret("DATABASE_URL", "DATABASE_URL_FILE");
|
|
||||||
String redis = secret("REDIS_URL", "CACHE_URL_FILE");
|
|
||||||
Jdbc jdbc = jdbc(database);
|
|
||||||
return new Config(host, port, appEnv, jdbc.url, jdbc.user, jdbc.password, redis.trim(), ttl, cost);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String env(String name, String fallback) {
|
|
||||||
String value = System.getenv(name);
|
|
||||||
if (value == null || value.isBlank()) {
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
return value.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String secret(String directName, String fileName) {
|
|
||||||
String direct = System.getenv(directName);
|
|
||||||
if (direct != null && !direct.isBlank()) {
|
|
||||||
return direct.trim();
|
|
||||||
}
|
|
||||||
String file = System.getenv(fileName);
|
|
||||||
if (file == null || file.isBlank()) {
|
|
||||||
fail(fileName);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
String value = Files.readString(Path.of(file)).trim();
|
|
||||||
if (value.isEmpty()) {
|
|
||||||
fail(fileName);
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
} catch (Exception e) {
|
|
||||||
fail(fileName);
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int parsePort(String raw) {
|
|
||||||
try {
|
|
||||||
int value = Integer.parseInt(raw);
|
|
||||||
if (value < 0 || value > 65535) {
|
|
||||||
throw new NumberFormatException();
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
fail("APP_PORT");
|
|
||||||
return 8080;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int parsePositive(String name, String raw) {
|
|
||||||
try {
|
|
||||||
int value = Integer.parseInt(raw);
|
|
||||||
if (value < 1) {
|
|
||||||
throw new NumberFormatException();
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
fail(name);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void fail(String name) {
|
|
||||||
System.err.println("event=config_failed name=" + name);
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
private record Jdbc(String url, String user, String password) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Jdbc jdbc(String raw) {
|
|
||||||
String value = raw.trim();
|
|
||||||
try {
|
|
||||||
if (value.startsWith("jdbc:postgresql:")) {
|
|
||||||
return fromJdbc(value);
|
|
||||||
}
|
|
||||||
if (value.startsWith("postgres://")) {
|
|
||||||
value = "postgresql://" + value.substring("postgres://".length());
|
|
||||||
}
|
|
||||||
if (!value.startsWith("postgresql://")) {
|
|
||||||
throw new IllegalArgumentException();
|
|
||||||
}
|
|
||||||
URI uri = URI.create(value);
|
|
||||||
String userInfo = uri.getRawUserInfo();
|
|
||||||
if (userInfo == null || !userInfo.contains(":")) {
|
|
||||||
throw new IllegalArgumentException();
|
|
||||||
}
|
|
||||||
int colon = userInfo.indexOf(':');
|
|
||||||
String user = URLDecoder.decode(userInfo.substring(0, colon), StandardCharsets.UTF_8);
|
|
||||||
String password = URLDecoder.decode(userInfo.substring(colon + 1), StandardCharsets.UTF_8);
|
|
||||||
String path = uri.getPath();
|
|
||||||
if (uri.getHost() == null || path == null || path.length() < 2) {
|
|
||||||
throw new IllegalArgumentException();
|
|
||||||
}
|
|
||||||
int port = uri.getPort() < 0 ? 5432 : uri.getPort();
|
|
||||||
String url = "jdbc:postgresql://" + uri.getHost() + ":" + port + path
|
|
||||||
+ "?user=" + URLEncoder.encode(user, StandardCharsets.UTF_8)
|
|
||||||
+ "&password=" + URLEncoder.encode(password, StandardCharsets.UTF_8);
|
|
||||||
return new Jdbc(withTimeouts(url), user, password);
|
|
||||||
} catch (RuntimeException e) {
|
|
||||||
fail("DATABASE_URL");
|
|
||||||
return new Jdbc("", "", "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Jdbc fromJdbc(String url) {
|
|
||||||
String user = query(url, "user");
|
|
||||||
String password = query(url, "password");
|
|
||||||
if (user == null || password == null) {
|
|
||||||
throw new IllegalArgumentException();
|
|
||||||
}
|
|
||||||
return new Jdbc(withTimeouts(url), user, password);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String query(String url, String name) {
|
|
||||||
int question = url.indexOf('?');
|
|
||||||
if (question < 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (String part : url.substring(question + 1).split("&")) {
|
|
||||||
int eq = part.indexOf('=');
|
|
||||||
if (eq < 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (part.substring(0, eq).equals(name)) {
|
|
||||||
return URLDecoder.decode(part.substring(eq + 1), StandardCharsets.UTF_8);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String withTimeouts(String url) {
|
|
||||||
if (url.contains("socketTimeout=")) {
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
String extra = "connectTimeout=2&socketTimeout=2";
|
|
||||||
return url + (url.contains("?") ? "&" : "?") + extra;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package ru.mtusi.lab2;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.sql.*;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
final class DatabaseStore implements AutoCloseable {
|
||||||
|
private final String url;
|
||||||
|
private final String user;
|
||||||
|
private final String password;
|
||||||
|
|
||||||
|
DatabaseStore() {
|
||||||
|
this.url = setting("DATABASE_URL", "jdbc:postgresql://localhost:5432/messenger");
|
||||||
|
this.user = setting("DATABASE_USER", "messenger");
|
||||||
|
this.password = setting("DATABASE_PASSWORD", "messenger");
|
||||||
|
try {
|
||||||
|
Class.forName("org.postgresql.Driver");
|
||||||
|
migrate();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("database initialization failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String setting(String name, String fallback) {
|
||||||
|
String value = System.getenv(name);
|
||||||
|
return value == null || value.isBlank() ? fallback : value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Connection connection() throws SQLException {
|
||||||
|
return DriverManager.getConnection(url, user, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void migrate() throws SQLException, IOException {
|
||||||
|
try (Connection c = connection()) {
|
||||||
|
c.setAutoCommit(false);
|
||||||
|
try (Statement s = c.createStatement()) {
|
||||||
|
s.execute("CREATE TABLE IF NOT EXISTS schema_version (version integer primary key, applied_at timestamptz not null default now())");
|
||||||
|
try (ResultSet rs = s.executeQuery("SELECT count(*) FROM schema_version WHERE version=1")) {
|
||||||
|
rs.next();
|
||||||
|
if (rs.getInt(1) == 0) {
|
||||||
|
String sql;
|
||||||
|
try (InputStream in = DatabaseStore.class.getResourceAsStream("/db/migration/V1__initial.sql")) {
|
||||||
|
if (in == null) throw new IOException("migration resource missing");
|
||||||
|
sql = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
for (String statement : sql.split(";")) {
|
||||||
|
if (!statement.isBlank()) s.execute(statement);
|
||||||
|
}
|
||||||
|
s.execute("INSERT INTO schema_version(version) VALUES (1)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.commit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
User createUser(String username, String displayName, String passwordHash) {
|
||||||
|
UUID id = UUID.randomUUID();
|
||||||
|
try (Connection c = connection();
|
||||||
|
PreparedStatement p = c.prepareStatement(
|
||||||
|
"INSERT INTO users(id,username,display_name,password_hash) VALUES (?,?,?,?)")) {
|
||||||
|
p.setObject(1, id); p.setString(2, username); p.setString(3, displayName); p.setString(4, passwordHash);
|
||||||
|
p.executeUpdate();
|
||||||
|
return findUser(id).orElseThrow(ApiException::unavailable);
|
||||||
|
} catch (SQLException e) {
|
||||||
|
if ("23505".equals(e.getSQLState())) throw ApiException.conflict();
|
||||||
|
throw unavailable(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Optional<Credential> credential(String username) {
|
||||||
|
try (Connection c = connection();
|
||||||
|
PreparedStatement p = c.prepareStatement("SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=?")) {
|
||||||
|
p.setString(1, username);
|
||||||
|
try (ResultSet r = p.executeQuery()) {
|
||||||
|
return r.next() ? Optional.of(new Credential(user(r), r.getString("password_hash"))) : Optional.empty();
|
||||||
|
}
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
Optional<User> findUser(UUID id) {
|
||||||
|
try (Connection c = connection(); PreparedStatement p = c.prepareStatement(
|
||||||
|
"SELECT id,username,display_name,created_at FROM users WHERE id=?")) {
|
||||||
|
p.setObject(1, id);
|
||||||
|
try (ResultSet r = p.executeQuery()) { return r.next() ? Optional.of(user(r)) : Optional.empty(); }
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
Session createSession(UUID userId, String token, Instant expiresAt) {
|
||||||
|
try (Connection c = connection(); PreparedStatement p = c.prepareStatement(
|
||||||
|
"INSERT INTO sessions(token,user_id,expires_at) VALUES (?,?,?)")) {
|
||||||
|
p.setString(1, token); p.setObject(2, userId); p.setTimestamp(3, Timestamp.from(expiresAt));
|
||||||
|
p.executeUpdate();
|
||||||
|
return new Session(token, expiresAt, findUser(userId).orElseThrow(ApiException::unauthorized));
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
Optional<Session> session(String token) {
|
||||||
|
try (Connection c = connection(); PreparedStatement p = c.prepareStatement(
|
||||||
|
"SELECT s.token,s.expires_at,u.id,u.username,u.display_name,u.created_at " +
|
||||||
|
"FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token=? AND s.expires_at>now()")) {
|
||||||
|
p.setString(1, token);
|
||||||
|
try (ResultSet r = p.executeQuery()) {
|
||||||
|
if (!r.next()) return Optional.empty();
|
||||||
|
return Optional.of(new Session(r.getString("token"), r.getTimestamp("expires_at").toInstant(), user(r)));
|
||||||
|
}
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
void revoke(String token) {
|
||||||
|
try (Connection c = connection(); PreparedStatement p = c.prepareStatement("DELETE FROM sessions WHERE token=?")) {
|
||||||
|
p.setString(1, token); p.executeUpdate();
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
Chat createChat(UUID callerId, String title, List<UUID> members) {
|
||||||
|
UUID id = UUID.randomUUID();
|
||||||
|
try (Connection c = connection()) {
|
||||||
|
c.setAutoCommit(false);
|
||||||
|
try {
|
||||||
|
for (UUID member : members) {
|
||||||
|
try (PreparedStatement p = c.prepareStatement("SELECT 1 FROM users WHERE id=?")) {
|
||||||
|
p.setObject(1, member);
|
||||||
|
try (ResultSet r = p.executeQuery()) { if (!r.next()) throw ApiException.invalid("Указан неизвестный участник"); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Instant now = Instant.now();
|
||||||
|
try (PreparedStatement p = c.prepareStatement("INSERT INTO chats(id,title,created_at) VALUES (?,?,?)")) {
|
||||||
|
p.setObject(1, id); p.setString(2, title); p.setTimestamp(3, Timestamp.from(now)); p.executeUpdate();
|
||||||
|
}
|
||||||
|
try (PreparedStatement p = c.prepareStatement("INSERT INTO chat_members(chat_id,user_id) VALUES (?,?)")) {
|
||||||
|
for (UUID member : members) { p.setObject(1, id); p.setObject(2, member); p.addBatch(); }
|
||||||
|
p.executeBatch();
|
||||||
|
}
|
||||||
|
c.commit();
|
||||||
|
return new Chat(id, title, List.copyOf(members), now);
|
||||||
|
} catch (RuntimeException | SQLException e) {
|
||||||
|
c.rollback();
|
||||||
|
if (e instanceof ApiException a) throw a;
|
||||||
|
if (e instanceof SQLException sql) throw unavailable(sql);
|
||||||
|
throw ApiException.unavailable();
|
||||||
|
}
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Chat> chatsOf(UUID userId) {
|
||||||
|
List<Chat> result = new ArrayList<>();
|
||||||
|
String sql = "SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=? ORDER BY c.created_at,c.id";
|
||||||
|
try (Connection c = connection(); PreparedStatement p = c.prepareStatement(sql)) {
|
||||||
|
p.setObject(1, userId);
|
||||||
|
try (ResultSet r = p.executeQuery()) {
|
||||||
|
while (r.next()) result.add(chat(c, r));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
Optional<Chat> visibleChat(UUID userId, UUID chatId) {
|
||||||
|
try (Connection c = connection(); PreparedStatement p = c.prepareStatement(
|
||||||
|
"SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE c.id=? AND m.user_id=?")) {
|
||||||
|
p.setObject(1, chatId); p.setObject(2, userId);
|
||||||
|
try (ResultSet r = p.executeQuery()) { return r.next() ? Optional.of(chat(c, r)) : Optional.empty(); }
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
Message addMessage(UUID senderId, UUID chatId, String text) {
|
||||||
|
if (visibleChat(senderId, chatId).isEmpty()) throw ApiException.notFound();
|
||||||
|
UUID id = UUID.randomUUID(); Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS);
|
||||||
|
try (Connection c = connection(); PreparedStatement p = c.prepareStatement(
|
||||||
|
"INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES (?,?,?,?,?)")) {
|
||||||
|
p.setObject(1,id); p.setObject(2,chatId); p.setObject(3,senderId); p.setString(4,text); p.setTimestamp(5, Timestamp.from(now)); p.executeUpdate();
|
||||||
|
return new Message(id, chatId, senderId, text, now);
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Message> messagesOf(UUID userId, UUID chatId) {
|
||||||
|
if (visibleChat(userId, chatId).isEmpty()) throw ApiException.notFound();
|
||||||
|
List<Message> result = new ArrayList<>();
|
||||||
|
try (Connection c = connection(); PreparedStatement p = c.prepareStatement(
|
||||||
|
"SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=? ORDER BY created_at,id")) {
|
||||||
|
p.setObject(1, chatId);
|
||||||
|
try (ResultSet r = p.executeQuery()) {
|
||||||
|
while (r.next()) result.add(new Message((UUID)r.getObject("id"), (UUID)r.getObject("chat_id"),
|
||||||
|
(UUID)r.getObject("sender_id"), r.getString("text"), r.getTimestamp("created_at").toInstant()));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
} catch (SQLException e) { throw unavailable(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static User user(ResultSet r) throws SQLException {
|
||||||
|
return new User((UUID) r.getObject("id"), r.getString("username"), r.getString("display_name"),
|
||||||
|
r.getTimestamp("created_at").toInstant());
|
||||||
|
}
|
||||||
|
private static Chat chat(Connection c, ResultSet r) throws SQLException {
|
||||||
|
List<UUID> ids = new ArrayList<>();
|
||||||
|
try (PreparedStatement p = c.prepareStatement("SELECT user_id FROM chat_members WHERE chat_id=? ORDER BY user_id")) {
|
||||||
|
p.setObject(1, r.getObject("id"));
|
||||||
|
try (ResultSet m = p.executeQuery()) { while (m.next()) ids.add((UUID)m.getObject(1)); }
|
||||||
|
}
|
||||||
|
return new Chat((UUID)r.getObject("id"), r.getString("title"), ids, r.getTimestamp("created_at").toInstant());
|
||||||
|
}
|
||||||
|
private static ApiException unavailable(SQLException e) { return ApiException.unavailable(); }
|
||||||
|
@Override public void close() { }
|
||||||
|
record Credential(User user, String passwordHash) {}
|
||||||
|
}
|
||||||
@@ -5,20 +5,18 @@ public final class Main {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Config config = Config.fromEnvironment();
|
String host = env("APP_HOST", "0.0.0.0");
|
||||||
|
int port = port(env("APP_PORT", "8080"));
|
||||||
|
String appEnv = env("APP_ENV", "lab");
|
||||||
MessengerServer server;
|
MessengerServer server;
|
||||||
try {
|
try {
|
||||||
server = MessengerServer.start(config, System.out::println, System.err::println);
|
server = MessengerServer.start(host, port, System.out::println, System.err::println);
|
||||||
} catch (Exception e) {
|
} catch (IllegalArgumentException | java.io.IOException e) {
|
||||||
System.err.println("event=startup_failed type=" + e.getClass().getSimpleName());
|
System.err.println("event=bind_failed type=" + e.getClass().getSimpleName());
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
System.out.println("event=listen host=" + config.host
|
System.out.println("event=listen host=" + host + " port=" + server.port() + " env=" + appEnv);
|
||||||
+ " port=" + server.port()
|
|
||||||
+ " env=" + config.appEnv
|
|
||||||
+ " session_store=redis"
|
|
||||||
+ " session_ttl_seconds=" + config.sessionTtlSeconds);
|
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||||
long started = System.nanoTime();
|
long started = System.nanoTime();
|
||||||
System.out.println("event=shutdown phase=begin");
|
System.out.println("event=shutdown phase=begin");
|
||||||
@@ -33,4 +31,26 @@ public final class Main {
|
|||||||
server.stop();
|
server.stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String env(String name, String fallback) {
|
||||||
|
String value = System.getenv(name);
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int port(String raw) {
|
||||||
|
try {
|
||||||
|
int value = Integer.parseInt(raw);
|
||||||
|
if (value < 0 || value > 65535) {
|
||||||
|
throw new NumberFormatException();
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
System.err.println("event=config_failed name=APP_PORT");
|
||||||
|
System.exit(1);
|
||||||
|
return 8080;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
|
|||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import com.sun.net.httpserver.HttpExchange;
|
import com.sun.net.httpserver.HttpExchange;
|
||||||
import com.sun.net.httpserver.HttpServer;
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import org.mindrot.jbcrypt.BCrypt;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -16,16 +17,18 @@ import java.io.OutputStream;
|
|||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
import java.net.URLDecoder;
|
import java.net.URLDecoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.security.SecureRandom;
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.time.temporal.ChronoUnit;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.security.SecureRandom;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
@@ -33,9 +36,6 @@ import java.util.function.Consumer;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
final class MessengerServer {
|
final class MessengerServer {
|
||||||
static final String BASIC = "Basic realm=\"messenger\", charset=\"UTF-8\"";
|
|
||||||
static final String BEARER = "Bearer realm=\"messenger\"";
|
|
||||||
|
|
||||||
private static final int MAX_BODY = 64 * 1024;
|
private static final int MAX_BODY = 64 * 1024;
|
||||||
private static final Pattern USERNAME = Pattern.compile("^[a-z0-9_]{3,32}$");
|
private static final Pattern USERNAME = Pattern.compile("^[a-z0-9_]{3,32}$");
|
||||||
private static final Pattern UUID_TEXT = Pattern.compile(
|
private static final Pattern UUID_TEXT = Pattern.compile(
|
||||||
@@ -45,26 +45,19 @@ final class MessengerServer {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
private final HttpServer http;
|
private final HttpServer http;
|
||||||
private final PostgresStore store;
|
private final DatabaseStore store = new DatabaseStore();
|
||||||
private final SessionStore sessions;
|
|
||||||
private final Passwords passwords;
|
|
||||||
private final int sessionTtlSeconds;
|
|
||||||
private final SecureRandom random = new SecureRandom();
|
private final SecureRandom random = new SecureRandom();
|
||||||
|
private final long sessionTtlSeconds = Long.parseLong(System.getenv().getOrDefault("SESSION_TTL_SECONDS", "3600"));
|
||||||
private final AtomicBoolean accepting = new AtomicBoolean(true);
|
private final AtomicBoolean accepting = new AtomicBoolean(true);
|
||||||
private final AtomicBoolean stopped = new AtomicBoolean(false);
|
private final AtomicBoolean stopped = new AtomicBoolean(false);
|
||||||
private final Consumer<String> info;
|
private final Consumer<String> info;
|
||||||
private final Consumer<String> error;
|
private final Consumer<String> error;
|
||||||
private final int port;
|
private final int port;
|
||||||
|
|
||||||
private MessengerServer(Config config, Consumer<String> info, Consumer<String> error) throws IOException {
|
private MessengerServer(String host, int port, Consumer<String> info, Consumer<String> error) throws IOException {
|
||||||
this.info = info;
|
this.info = info;
|
||||||
this.error = error;
|
this.error = error;
|
||||||
this.sessionTtlSeconds = config.sessionTtlSeconds;
|
this.http = HttpServer.create(new InetSocketAddress(host, port), 128);
|
||||||
this.passwords = new Passwords(config.bcryptCost);
|
|
||||||
this.store = new PostgresStore(config.jdbcUrl, config.dbUser, config.dbPassword, passwords);
|
|
||||||
this.sessions = new SessionStore(config.redisUrl);
|
|
||||||
this.store.migrate();
|
|
||||||
this.http = HttpServer.create(new InetSocketAddress(config.host, config.port), 128);
|
|
||||||
this.port = http.getAddress().getPort();
|
this.port = http.getAddress().getPort();
|
||||||
ExecutorService pool = Executors.newFixedThreadPool(64, runnable -> {
|
ExecutorService pool = Executors.newFixedThreadPool(64, runnable -> {
|
||||||
Thread thread = new Thread(runnable, "http");
|
Thread thread = new Thread(runnable, "http");
|
||||||
@@ -76,18 +69,14 @@ final class MessengerServer {
|
|||||||
http.start();
|
http.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
static MessengerServer start(Config config, Consumer<String> info, Consumer<String> error) throws IOException {
|
static MessengerServer start(String host, int port, Consumer<String> info, Consumer<String> error) throws IOException {
|
||||||
return new MessengerServer(config, info, error);
|
return new MessengerServer(host, port, info, error);
|
||||||
}
|
}
|
||||||
|
|
||||||
int port() {
|
int port() {
|
||||||
return port;
|
return port;
|
||||||
}
|
}
|
||||||
|
|
||||||
PostgresStore store() {
|
|
||||||
return store;
|
|
||||||
}
|
|
||||||
|
|
||||||
void refuseNewRequests() {
|
void refuseNewRequests() {
|
||||||
accepting.set(false);
|
accepting.set(false);
|
||||||
}
|
}
|
||||||
@@ -96,8 +85,6 @@ final class MessengerServer {
|
|||||||
accepting.set(false);
|
accepting.set(false);
|
||||||
if (stopped.compareAndSet(false, true)) {
|
if (stopped.compareAndSet(false, true)) {
|
||||||
http.stop(2);
|
http.stop(2);
|
||||||
sessions.close();
|
|
||||||
store.close();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,7 +99,7 @@ final class MessengerServer {
|
|||||||
} catch (ApiException exception) {
|
} catch (ApiException exception) {
|
||||||
status = writeError(exchange, requestId, exception);
|
status = writeError(exchange, requestId, exception);
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
error.accept("event=unexpected type=" + exception.getClass().getName());
|
error.accept("event=unexpected type=" + exception.getClass().getName() + " message=" + exception.getMessage());
|
||||||
status = writeError(exchange, requestId, ApiException.internalError());
|
status = writeError(exchange, requestId, ApiException.internalError());
|
||||||
} finally {
|
} finally {
|
||||||
long durationMs = (System.nanoTime() - started) / 1_000_000L;
|
long durationMs = (System.nanoTime() - started) / 1_000_000L;
|
||||||
@@ -130,7 +117,7 @@ final class MessengerServer {
|
|||||||
if ("GET".equals(method) && "/health/live".equals(path)) {
|
if ("GET".equals(method) && "/health/live".equals(path)) {
|
||||||
return writeJson(exchange, requestId, 200, health());
|
return writeJson(exchange, requestId, 200, health());
|
||||||
}
|
}
|
||||||
throw ApiException.shuttingDown();
|
throw ApiException.unavailable();
|
||||||
}
|
}
|
||||||
if ("GET".equals(method) && "/health/live".equals(path)) {
|
if ("GET".equals(method) && "/health/live".equals(path)) {
|
||||||
rejectQuery(exchange);
|
rejectQuery(exchange);
|
||||||
@@ -138,9 +125,6 @@ final class MessengerServer {
|
|||||||
}
|
}
|
||||||
if ("GET".equals(method) && "/health/ready".equals(path)) {
|
if ("GET".equals(method) && "/health/ready".equals(path)) {
|
||||||
rejectQuery(exchange);
|
rejectQuery(exchange);
|
||||||
if (!store.ready() || !sessions.ready()) {
|
|
||||||
throw ApiException.dependency();
|
|
||||||
}
|
|
||||||
return writeJson(exchange, requestId, 200, health());
|
return writeJson(exchange, requestId, 200, health());
|
||||||
}
|
}
|
||||||
if ("POST".equals(method) && "/api/v1/users".equals(path)) {
|
if ("POST".equals(method) && "/api/v1/users".equals(path)) {
|
||||||
@@ -154,47 +138,34 @@ final class MessengerServer {
|
|||||||
String displayName = requiredText(body, "display_name");
|
String displayName = requiredText(body, "display_name");
|
||||||
requireCodePoints(displayName, 1, 100, "display_name");
|
requireCodePoints(displayName, 1, 100, "display_name");
|
||||||
String password = requiredText(body, "password");
|
String password = requiredText(body, "password");
|
||||||
int passwordPoints = password.codePointCount(0, password.length());
|
requireCodePoints(password, 12, 128, "password");
|
||||||
if (passwordPoints < 12 || passwordPoints > 128) {
|
User user = store.createUser(username, displayName, BCrypt.hashpw(password, BCrypt.gensalt(12)));
|
||||||
throw ApiException.invalid("Недопустимый пароль");
|
|
||||||
}
|
|
||||||
User user = store.createUser(username, displayName, password);
|
|
||||||
return writeJson(exchange, requestId, 201, userJson(user));
|
return writeJson(exchange, requestId, 201, userJson(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
if ("POST".equals(method) && "/api/v1/auth/sessions".equals(path)) {
|
if ("POST".equals(method) && "/api/v1/auth/sessions".equals(path)) {
|
||||||
rejectQuery(exchange);
|
rejectQuery(exchange);
|
||||||
if (readLimited(exchange.getRequestBody()).length > 0) {
|
String[] credentials = basicCredentials(exchange);
|
||||||
throw ApiException.invalid("Тело запроса не допускается");
|
DatabaseStore.Credential credential = store.credential(credentials[0]).orElseThrow(ApiException::unauthorized);
|
||||||
}
|
if (!BCrypt.checkpw(credentials[1], credential.passwordHash())) throw ApiException.unauthorized();
|
||||||
Credentials credentials = basic(exchange);
|
Instant expires = Instant.now().plusSeconds(sessionTtlSeconds);
|
||||||
User user;
|
byte[] tokenBytes = new byte[32];
|
||||||
try {
|
random.nextBytes(tokenBytes);
|
||||||
user = store.authenticate(credentials.username, credentials.password);
|
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);
|
||||||
} catch (ApiException exception) {
|
store.createSession(credential.user().id(), token, expires);
|
||||||
if (exception.status == 401) {
|
ObjectNode result = JSON.createObjectNode().put("token", token).put("token_type", "Bearer")
|
||||||
throw ApiException.unauthorized(BASIC);
|
.put("expires_at", DateTimeFormatter.ISO_INSTANT.format(expires));
|
||||||
}
|
result.set("user", userJson(credential.user()));
|
||||||
throw exception;
|
return writeJson(exchange, requestId, 201, result, null);
|
||||||
}
|
|
||||||
String token = newToken();
|
|
||||||
sessions.save(token, user.id(), sessionTtlSeconds);
|
|
||||||
Instant expires = Instant.now().plusSeconds(sessionTtlSeconds).truncatedTo(ChronoUnit.SECONDS);
|
|
||||||
ObjectNode session = JSON.createObjectNode();
|
|
||||||
session.put("token", token);
|
|
||||||
session.put("token_type", "Bearer");
|
|
||||||
session.put("expires_at", DateTimeFormatter.ISO_INSTANT.format(expires));
|
|
||||||
session.set("user", userJson(user));
|
|
||||||
return writeJson(exchange, requestId, 201, session);
|
|
||||||
}
|
}
|
||||||
if ("DELETE".equals(method) && "/api/v1/auth/sessions/current".equals(path)) {
|
if ("DELETE".equals(method) && "/api/v1/auth/sessions/current".equals(path)) {
|
||||||
rejectQuery(exchange);
|
String token = bearerToken(exchange);
|
||||||
String token = bearer(exchange);
|
if (store.session(token).isEmpty()) throw ApiException.unauthorized();
|
||||||
if (!sessions.revoke(token)) {
|
store.revoke(token);
|
||||||
throw ApiException.unauthorized(BEARER);
|
exchange.getResponseHeaders().set("X-Request-Id", requestId);
|
||||||
}
|
exchange.sendResponseHeaders(204, -1);
|
||||||
return writeEmpty(exchange, requestId);
|
return 204;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ("GET".equals(method) && "/api/v1/users/me".equals(path)) {
|
if ("GET".equals(method) && "/api/v1/users/me".equals(path)) {
|
||||||
rejectQuery(exchange);
|
rejectQuery(exchange);
|
||||||
User user = requireUser(exchange);
|
User user = requireUser(exchange);
|
||||||
@@ -214,14 +185,9 @@ final class MessengerServer {
|
|||||||
if ("GET".equals(method) && "/api/v1/chats".equals(path)) {
|
if ("GET".equals(method) && "/api/v1/chats".equals(path)) {
|
||||||
User user = requireUser(exchange);
|
User user = requireUser(exchange);
|
||||||
Query query = pagingQuery(exchange);
|
Query query = pagingQuery(exchange);
|
||||||
int limit = query.limit == null ? 50 : query.limit;
|
List<Chat> chats = new ArrayList<>(store.chatsOf(user.id()));
|
||||||
Position position = query.cursor == null ? null : decodeCursor(query.cursor, "c", user.id());
|
chats.sort(Comparator.comparing(Chat::createdAt).thenComparing(Chat::id));
|
||||||
List<Chat> chats = store.chats(
|
return writePage(exchange, requestId, chats, query, "c", user.id(), Chat::createdAt, Chat::id, MessengerServer::chatJson);
|
||||||
user.id(),
|
|
||||||
limit + 1,
|
|
||||||
position == null ? null : position.createdAt,
|
|
||||||
position == null ? null : position.id);
|
|
||||||
return writeSlice(exchange, requestId, chats, limit, "c", user.id(), Chat::createdAt, Chat::id, MessengerServer::chatJson);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ChatRoute chatRoute = matchChat(path);
|
ChatRoute chatRoute = matchChat(path);
|
||||||
@@ -229,18 +195,9 @@ final class MessengerServer {
|
|||||||
User user = requireUser(exchange);
|
User user = requireUser(exchange);
|
||||||
UUID chatId = parsePathUuid(chatRoute.idText);
|
UUID chatId = parsePathUuid(chatRoute.idText);
|
||||||
Query query = pagingQuery(exchange);
|
Query query = pagingQuery(exchange);
|
||||||
int limit = query.limit == null ? 50 : query.limit;
|
List<Message> messages = new ArrayList<>(store.messagesOf(user.id(), chatId));
|
||||||
if (store.visibleChat(user.id(), chatId).isEmpty()) {
|
messages.sort(Comparator.comparing(Message::createdAt).thenComparing(Message::id));
|
||||||
throw ApiException.notFound();
|
return writePage(exchange, requestId, messages, query, "m", chatId, Message::createdAt, Message::id, this::messageJson);
|
||||||
}
|
|
||||||
Position position = query.cursor == null ? null : decodeCursor(query.cursor, "m", chatId);
|
|
||||||
List<Message> messages = store.messages(
|
|
||||||
user.id(),
|
|
||||||
chatId,
|
|
||||||
limit + 1,
|
|
||||||
position == null ? null : position.createdAt,
|
|
||||||
position == null ? null : position.id);
|
|
||||||
return writeSlice(exchange, requestId, messages, limit, "m", chatId, Message::createdAt, Message::id, MessengerServer::messageJson);
|
|
||||||
}
|
}
|
||||||
if (chatRoute != null && "POST".equals(method) && chatRoute.messages) {
|
if (chatRoute != null && "POST".equals(method) && chatRoute.messages) {
|
||||||
rejectQuery(exchange);
|
rejectQuery(exchange);
|
||||||
@@ -264,54 +221,26 @@ final class MessengerServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private User requireUser(HttpExchange exchange) {
|
private User requireUser(HttpExchange exchange) {
|
||||||
String token = bearer(exchange);
|
return store.session(bearerToken(exchange)).map(Session::user).orElseThrow(ApiException::unauthorized);
|
||||||
UUID userId = sessions.find(token).orElseThrow(() -> ApiException.unauthorized(BEARER));
|
|
||||||
return store.findUser(userId).orElseThrow(() -> ApiException.unauthorized(BEARER));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private String bearer(HttpExchange exchange) {
|
private String bearerToken(HttpExchange exchange) {
|
||||||
String header = singleHeader(exchange, "Authorization");
|
String header = exchange.getRequestHeaders().getFirst("Authorization");
|
||||||
if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7)) {
|
if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7) || header.length() <= 7) {
|
||||||
throw ApiException.unauthorized(BEARER);
|
throw ApiException.unauthorized();
|
||||||
}
|
}
|
||||||
String token = header.substring(7);
|
return header.substring(7).trim();
|
||||||
if (token.isBlank() || token.indexOf(' ') >= 0) {
|
|
||||||
throw ApiException.unauthorized(BEARER);
|
|
||||||
}
|
|
||||||
return token;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Credentials basic(HttpExchange exchange) {
|
private static String[] basicCredentials(HttpExchange exchange) {
|
||||||
String header = singleHeader(exchange, "Authorization");
|
String header = exchange.getRequestHeaders().getFirst("Authorization");
|
||||||
if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) {
|
if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) throw ApiException.unauthorized();
|
||||||
throw ApiException.unauthorized(BASIC);
|
|
||||||
}
|
|
||||||
byte[] decoded;
|
|
||||||
try {
|
try {
|
||||||
decoded = Base64.getDecoder().decode(header.substring(6).trim());
|
String decoded = new String(Base64.getDecoder().decode(header.substring(6).trim()), StandardCharsets.UTF_8);
|
||||||
} catch (IllegalArgumentException e) {
|
int colon = decoded.indexOf(':');
|
||||||
throw ApiException.unauthorized(BASIC);
|
if (colon < 1) throw new IllegalArgumentException();
|
||||||
}
|
return new String[]{decoded.substring(0, colon), decoded.substring(colon + 1)};
|
||||||
String pair = new String(decoded, StandardCharsets.UTF_8);
|
} catch (IllegalArgumentException e) { throw ApiException.unauthorized(); }
|
||||||
int colon = pair.indexOf(':');
|
|
||||||
if (colon <= 0 || colon == pair.length() - 1) {
|
|
||||||
throw ApiException.unauthorized(BASIC);
|
|
||||||
}
|
|
||||||
return new Credentials(pair.substring(0, colon), pair.substring(colon + 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String singleHeader(HttpExchange exchange, String name) {
|
|
||||||
List<String> headers = exchange.getRequestHeaders().get(name);
|
|
||||||
if (headers == null || headers.size() != 1) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return headers.get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String newToken() {
|
|
||||||
byte[] bytes = new byte[32];
|
|
||||||
random.nextBytes(bytes);
|
|
||||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static UUID parsePathUuid(String raw) {
|
private static UUID parsePathUuid(String raw) {
|
||||||
@@ -327,7 +256,7 @@ final class MessengerServer {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
String rest = path.substring(prefix.length());
|
String rest = path.substring(prefix.length());
|
||||||
if (rest.isEmpty() || rest.charAt(0) == '/') {
|
if (rest.isEmpty() || rest.indexOf('/') == 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
int slash = rest.indexOf('/');
|
int slash = rest.indexOf('/');
|
||||||
@@ -415,7 +344,17 @@ final class MessengerServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static boolean isBlank(String value) {
|
private static boolean isBlank(String value) {
|
||||||
return value.codePoints().allMatch(cp -> Character.isWhitespace(cp) || Character.isSpaceChar(cp));
|
return value.codePoints().allMatch(MessengerServer::isUnicodeWhiteSpace);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unicode White_Space. Character.isWhitespace пропускает U+0085 (NEL).
|
||||||
|
private static boolean isUnicodeWhiteSpace(int codePoint) {
|
||||||
|
return switch (codePoint) {
|
||||||
|
case 0x0009, 0x000A, 0x000B, 0x000C, 0x000D,
|
||||||
|
0x0020, 0x0085, 0x00A0, 0x1680,
|
||||||
|
0x2028, 0x2029, 0x202F, 0x205F, 0x3000 -> true;
|
||||||
|
default -> codePoint >= 0x2000 && codePoint <= 0x200A;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<UUID> memberIds(JsonNode object) {
|
private static List<UUID> memberIds(JsonNode object) {
|
||||||
@@ -452,7 +391,7 @@ final class MessengerServer {
|
|||||||
if (raw == null || raw.isEmpty()) {
|
if (raw == null || raw.isEmpty()) {
|
||||||
return new Query(null, null);
|
return new Query(null, null);
|
||||||
}
|
}
|
||||||
java.util.Map<String, List<String>> params = new java.util.LinkedHashMap<>();
|
Map<String, List<String>> params = new LinkedHashMap<>();
|
||||||
for (String part : raw.split("&", -1)) {
|
for (String part : raw.split("&", -1)) {
|
||||||
if (part.isEmpty()) {
|
if (part.isEmpty()) {
|
||||||
continue;
|
continue;
|
||||||
@@ -498,25 +437,36 @@ final class MessengerServer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private <T> int writeSlice(
|
private <T> int writePage(
|
||||||
HttpExchange exchange,
|
HttpExchange exchange,
|
||||||
String requestId,
|
String requestId,
|
||||||
List<T> loaded,
|
List<T> sorted,
|
||||||
int limit,
|
Query query,
|
||||||
String kind,
|
String kind,
|
||||||
UUID scope,
|
UUID scope,
|
||||||
java.util.function.Function<T, Instant> createdAt,
|
java.util.function.Function<T, Instant> createdAt,
|
||||||
java.util.function.Function<T, UUID> id,
|
java.util.function.Function<T, UUID> id,
|
||||||
java.util.function.Function<T, ObjectNode> json) throws IOException {
|
java.util.function.Function<T, ObjectNode> json) throws IOException {
|
||||||
boolean more = loaded.size() > limit;
|
int limit = query.limit == null ? 50 : query.limit;
|
||||||
int end = more ? limit : loaded.size();
|
int start = 0;
|
||||||
|
if (query.cursor != null) {
|
||||||
|
Position position = decodeCursor(query.cursor, kind, scope);
|
||||||
|
while (start < sorted.size()) {
|
||||||
|
T item = sorted.get(start);
|
||||||
|
if (after(createdAt.apply(item), id.apply(item), position.createdAt, position.id)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
start++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int end = Math.min(start + limit, sorted.size());
|
||||||
ObjectNode page = JSON.createObjectNode();
|
ObjectNode page = JSON.createObjectNode();
|
||||||
ArrayNode items = page.putArray("items");
|
ArrayNode items = page.putArray("items");
|
||||||
for (int i = 0; i < end; i++) {
|
for (int i = start; i < end; i++) {
|
||||||
items.add(json.apply(loaded.get(i)));
|
items.add(json.apply(sorted.get(i)));
|
||||||
}
|
}
|
||||||
if (more && end > 0) {
|
if (end < sorted.size() && end > start) {
|
||||||
T last = loaded.get(end - 1);
|
T last = sorted.get(end - 1);
|
||||||
page.put("next_cursor", encodeCursor(kind, scope, createdAt.apply(last), id.apply(last)));
|
page.put("next_cursor", encodeCursor(kind, scope, createdAt.apply(last), id.apply(last)));
|
||||||
} else {
|
} else {
|
||||||
page.putNull("next_cursor");
|
page.putNull("next_cursor");
|
||||||
@@ -524,8 +474,16 @@ final class MessengerServer {
|
|||||||
return writeJson(exchange, requestId, 200, page);
|
return writeJson(exchange, requestId, 200, page);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static boolean after(Instant leftTime, UUID leftId, Instant rightTime, UUID rightId) {
|
||||||
|
int compared = leftTime.compareTo(rightTime);
|
||||||
|
if (compared != 0) {
|
||||||
|
return compared > 0;
|
||||||
|
}
|
||||||
|
return leftId.compareTo(rightId) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
private static String encodeCursor(String kind, UUID scope, Instant createdAt, UUID id) {
|
private static String encodeCursor(String kind, UUID scope, Instant createdAt, UUID id) {
|
||||||
String raw = kind + "|" + scope + "|" + createdAt.toEpochMilli() + "|" + id;
|
String raw = kind + "|" + scope + "|" + DateTimeFormatter.ISO_INSTANT.format(createdAt) + "|" + id;
|
||||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -545,11 +503,11 @@ final class MessengerServer {
|
|||||||
throw ApiException.invalid("Cursor относится к другому ресурсу");
|
throw ApiException.invalid("Cursor относится к другому ресурсу");
|
||||||
}
|
}
|
||||||
UUID cursorScope;
|
UUID cursorScope;
|
||||||
long millis;
|
Instant createdAt;
|
||||||
UUID id;
|
UUID id;
|
||||||
try {
|
try {
|
||||||
cursorScope = UUID.fromString(parts[1]);
|
cursorScope = UUID.fromString(parts[1]);
|
||||||
millis = Long.parseLong(parts[2]);
|
createdAt = Instant.parse(parts[2]);
|
||||||
id = UUID.fromString(parts[3]);
|
id = UUID.fromString(parts[3]);
|
||||||
} catch (IllegalArgumentException exception) {
|
} catch (IllegalArgumentException exception) {
|
||||||
throw ApiException.invalid("Некорректный cursor");
|
throw ApiException.invalid("Некорректный cursor");
|
||||||
@@ -557,7 +515,7 @@ final class MessengerServer {
|
|||||||
if (!cursorScope.equals(scope)) {
|
if (!cursorScope.equals(scope)) {
|
||||||
throw ApiException.invalid("Cursor относится к другому ресурсу");
|
throw ApiException.invalid("Cursor относится к другому ресурсу");
|
||||||
}
|
}
|
||||||
return new Position(Instant.ofEpochMilli(millis), id);
|
return new Position(createdAt, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String pad(String value) {
|
private static String pad(String value) {
|
||||||
@@ -593,7 +551,7 @@ final class MessengerServer {
|
|||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ObjectNode messageJson(Message message) {
|
private ObjectNode messageJson(Message message) {
|
||||||
ObjectNode node = JSON.createObjectNode();
|
ObjectNode node = JSON.createObjectNode();
|
||||||
node.put("id", message.id().toString());
|
node.put("id", message.id().toString());
|
||||||
node.put("chat_id", message.chatId().toString());
|
node.put("chat_id", message.chatId().toString());
|
||||||
@@ -604,14 +562,12 @@ final class MessengerServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private int writeJson(HttpExchange exchange, String requestId, int status, JsonNode body) throws IOException {
|
private int writeJson(HttpExchange exchange, String requestId, int status, JsonNode body) throws IOException {
|
||||||
byte[] bytes = JSON.writeValueAsBytes(body);
|
return writeJson(exchange, requestId, status, body, null);
|
||||||
return writeBytes(exchange, requestId, status, bytes, null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int writeEmpty(HttpExchange exchange, String requestId) throws IOException {
|
private int writeJson(HttpExchange exchange, String requestId, int status, JsonNode body, String challenge) throws IOException {
|
||||||
exchange.getResponseHeaders().set("X-Request-Id", requestId);
|
byte[] bytes = JSON.writeValueAsBytes(body);
|
||||||
exchange.sendResponseHeaders(204, -1);
|
return writeBytes(exchange, requestId, status, bytes, challenge);
|
||||||
return 204;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int writeError(HttpExchange exchange, String requestId, ApiException exception) {
|
private int writeError(HttpExchange exchange, String requestId, ApiException exception) {
|
||||||
@@ -621,8 +577,11 @@ final class MessengerServer {
|
|||||||
errorNode.put("message", exception.clientMessage);
|
errorNode.put("message", exception.clientMessage);
|
||||||
errorNode.put("request_id", requestId);
|
errorNode.put("request_id", requestId);
|
||||||
try {
|
try {
|
||||||
byte[] bytes = JSON.writeValueAsBytes(body);
|
String challenge = exception.status == 401
|
||||||
return writeBytes(exchange, requestId, exception.status, bytes, exception.challenge);
|
? (exchange.getRequestURI().getPath().equals("/api/v1/auth/sessions")
|
||||||
|
? "Basic realm=\"messenger\", charset=\"UTF-8\"" : "Bearer realm=\"messenger\"")
|
||||||
|
: null;
|
||||||
|
return writeJson(exchange, requestId, exception.status, body, challenge);
|
||||||
} catch (IOException ioException) {
|
} catch (IOException ioException) {
|
||||||
error.accept("event=write_failed type=" + ioException.getClass().getName());
|
error.accept("event=write_failed type=" + ioException.getClass().getName());
|
||||||
return exception.status;
|
return exception.status;
|
||||||
@@ -632,9 +591,7 @@ final class MessengerServer {
|
|||||||
private int writeBytes(HttpExchange exchange, String requestId, int status, byte[] body, String challenge) throws IOException {
|
private int writeBytes(HttpExchange exchange, String requestId, int status, byte[] body, String challenge) throws IOException {
|
||||||
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
|
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
|
||||||
exchange.getResponseHeaders().set("X-Request-Id", requestId);
|
exchange.getResponseHeaders().set("X-Request-Id", requestId);
|
||||||
if (challenge != null) {
|
if (challenge != null) exchange.getResponseHeaders().set("WWW-Authenticate", challenge);
|
||||||
exchange.getResponseHeaders().set("WWW-Authenticate", challenge);
|
|
||||||
}
|
|
||||||
exchange.sendResponseHeaders(status, body.length);
|
exchange.sendResponseHeaders(status, body.length);
|
||||||
try (OutputStream output = exchange.getResponseBody()) {
|
try (OutputStream output = exchange.getResponseBody()) {
|
||||||
output.write(body);
|
output.write(body);
|
||||||
@@ -650,7 +607,4 @@ final class MessengerServer {
|
|||||||
|
|
||||||
private record ChatRoute(String idText, boolean messages) {
|
private record ChatRoute(String idText, boolean messages) {
|
||||||
}
|
}
|
||||||
|
|
||||||
private record Credentials(String username, String password) {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
package ru.mtusi.lab2;
|
|
||||||
|
|
||||||
import at.favre.lib.crypto.bcrypt.BCrypt;
|
|
||||||
import at.favre.lib.crypto.bcrypt.LongPasswordStrategies;
|
|
||||||
import at.favre.lib.crypto.bcrypt.LongPasswordStrategy;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* bcrypt сам по себе обрезает пароль на 72 байтах.
|
|
||||||
* Перед ним пароль целиком проходит через SHA-512, поэтому длинный UTF-8 не теряется.
|
|
||||||
* Наружу уходит только строка bcrypt, не сам пароль.
|
|
||||||
*/
|
|
||||||
final class Passwords {
|
|
||||||
private final int cost;
|
|
||||||
private final BCrypt.Hasher hasher;
|
|
||||||
private final BCrypt.Verifyer verifyer;
|
|
||||||
private final String dummyHash;
|
|
||||||
|
|
||||||
Passwords(int cost) {
|
|
||||||
if (cost < 4 || cost > 14) {
|
|
||||||
throw new IllegalArgumentException("bcrypt cost");
|
|
||||||
}
|
|
||||||
this.cost = cost;
|
|
||||||
LongPasswordStrategy strategy = LongPasswordStrategies.hashSha512(BCrypt.Version.VERSION_2A);
|
|
||||||
this.hasher = BCrypt.with(BCrypt.Version.VERSION_2A, strategy);
|
|
||||||
this.verifyer = BCrypt.verifyer(BCrypt.Version.VERSION_2A, strategy);
|
|
||||||
this.dummyHash = hasher.hashToString(cost, "missing-user-timing".toCharArray());
|
|
||||||
}
|
|
||||||
|
|
||||||
String hash(String password) {
|
|
||||||
return hasher.hashToString(cost, password.toCharArray());
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean verify(String password, String hash) {
|
|
||||||
return verifyer.verify(password.toCharArray(), hash).verified;
|
|
||||||
}
|
|
||||||
|
|
||||||
void burnMissing(String password) {
|
|
||||||
verifyer.verify(password.toCharArray(), dummyHash);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,546 +0,0 @@
|
|||||||
package ru.mtusi.lab2;
|
|
||||||
|
|
||||||
import com.zaxxer.hikari.HikariConfig;
|
|
||||||
import com.zaxxer.hikari.HikariDataSource;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.sql.Statement;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.time.ZoneOffset;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Пользователи, чаты, участники и сообщения лежат в PostgreSQL.
|
|
||||||
* Создание чата и запись сообщения идут одной транзакцией вместе с монотонными часами.
|
|
||||||
* Пул ограничен, у соединения короткий таймаут: если БД недоступна, запрос заканчивается 503.
|
|
||||||
*/
|
|
||||||
final class PostgresStore implements AutoCloseable {
|
|
||||||
private final HikariDataSource dataSource;
|
|
||||||
private final Passwords passwords;
|
|
||||||
|
|
||||||
PostgresStore(String jdbcUrl, String username, String password, Passwords passwords) {
|
|
||||||
HikariConfig config = new HikariConfig();
|
|
||||||
config.setJdbcUrl(jdbcUrl);
|
|
||||||
config.setUsername(username);
|
|
||||||
config.setPassword(password);
|
|
||||||
config.setMaximumPoolSize(10);
|
|
||||||
config.setMinimumIdle(1);
|
|
||||||
config.setConnectionTimeout(2000);
|
|
||||||
config.setValidationTimeout(1000);
|
|
||||||
config.setInitializationFailTimeout(10000);
|
|
||||||
config.setConnectionInitSql("SET TIME ZONE 'UTC'");
|
|
||||||
this.dataSource = new HikariDataSource(config);
|
|
||||||
this.passwords = passwords;
|
|
||||||
}
|
|
||||||
|
|
||||||
void migrate() {
|
|
||||||
try (Connection conn = dataSource.getConnection()) {
|
|
||||||
conn.setAutoCommit(false);
|
|
||||||
try (Statement statement = conn.createStatement()) {
|
|
||||||
statement.execute("""
|
|
||||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
||||||
version text PRIMARY KEY,
|
|
||||||
applied_at timestamptz NOT NULL DEFAULT now()
|
|
||||||
)
|
|
||||||
""");
|
|
||||||
}
|
|
||||||
if (!applied(conn, "V1")) {
|
|
||||||
runScript(conn, "/db/migration/V1__schema.sql");
|
|
||||||
try (PreparedStatement insert = conn.prepareStatement(
|
|
||||||
"INSERT INTO schema_migrations (version) VALUES (?)")) {
|
|
||||||
insert.setString(1, "V1");
|
|
||||||
insert.executeUpdate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
conn.commit();
|
|
||||||
} catch (SQLException | IOException e) {
|
|
||||||
throw new IllegalStateException("migration failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
User createUser(String username, String displayName, String password) {
|
|
||||||
String hash = passwords.hash(password);
|
|
||||||
Connection conn = open();
|
|
||||||
try {
|
|
||||||
conn.setAutoCommit(false);
|
|
||||||
long millis = tick(conn);
|
|
||||||
UUID id = UUID.randomUUID();
|
|
||||||
try (PreparedStatement insert = conn.prepareStatement("""
|
|
||||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
|
||||||
VALUES (?, ?, ?, ?, ?)
|
|
||||||
""")) {
|
|
||||||
insert.setObject(1, id);
|
|
||||||
insert.setString(2, username);
|
|
||||||
insert.setString(3, displayName);
|
|
||||||
insert.setString(4, hash);
|
|
||||||
insert.setObject(5, timestamp(millis));
|
|
||||||
insert.executeUpdate();
|
|
||||||
}
|
|
||||||
User user = loadUser(conn, id).orElseThrow(ApiException::internalError);
|
|
||||||
conn.commit();
|
|
||||||
return user;
|
|
||||||
} catch (ApiException e) {
|
|
||||||
rollback(conn);
|
|
||||||
throw e;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
rollback(conn);
|
|
||||||
if ("23505".equals(e.getSQLState())) {
|
|
||||||
throw ApiException.conflict();
|
|
||||||
}
|
|
||||||
throw map(e);
|
|
||||||
} finally {
|
|
||||||
close(conn);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
User authenticate(String username, String password) {
|
|
||||||
try (Connection conn = dataSource.getConnection();
|
|
||||||
PreparedStatement statement = conn.prepareStatement("""
|
|
||||||
SELECT id, username, display_name, password_hash, created_at
|
|
||||||
FROM users
|
|
||||||
WHERE username = ?
|
|
||||||
""")) {
|
|
||||||
statement.setString(1, username);
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
if (!rows.next()) {
|
|
||||||
passwords.burnMissing(password);
|
|
||||||
throw ApiException.unauthorized(null);
|
|
||||||
}
|
|
||||||
String hash = rows.getString("password_hash");
|
|
||||||
if (!passwords.verify(password, hash)) {
|
|
||||||
throw ApiException.unauthorized(null);
|
|
||||||
}
|
|
||||||
return userFrom(rows);
|
|
||||||
}
|
|
||||||
} catch (ApiException e) {
|
|
||||||
throw e;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
throw map(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Optional<User> findUser(UUID id) {
|
|
||||||
try (Connection conn = dataSource.getConnection()) {
|
|
||||||
return loadUser(conn, id);
|
|
||||||
} catch (SQLException e) {
|
|
||||||
throw map(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Chat createChat(UUID callerId, String title, List<UUID> memberIds) {
|
|
||||||
if (!memberIds.contains(callerId)) {
|
|
||||||
throw ApiException.invalid("Создатель чата должен входить в список участников");
|
|
||||||
}
|
|
||||||
Connection conn = open();
|
|
||||||
try {
|
|
||||||
conn.setAutoCommit(false);
|
|
||||||
List<UUID> locked = new ArrayList<>(memberIds);
|
|
||||||
locked.sort(UUID::compareTo);
|
|
||||||
for (UUID memberId : locked) {
|
|
||||||
if (!lockUser(conn, memberId)) {
|
|
||||||
throw ApiException.invalid("Указан неизвестный участник");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
long millis = tick(conn);
|
|
||||||
UUID chatId = UUID.randomUUID();
|
|
||||||
try (PreparedStatement insert = conn.prepareStatement("""
|
|
||||||
INSERT INTO chats (id, title, created_at)
|
|
||||||
VALUES (?, ?, ?)
|
|
||||||
""")) {
|
|
||||||
insert.setObject(1, chatId);
|
|
||||||
insert.setString(2, title);
|
|
||||||
insert.setObject(3, timestamp(millis));
|
|
||||||
insert.executeUpdate();
|
|
||||||
}
|
|
||||||
try (PreparedStatement member = conn.prepareStatement("""
|
|
||||||
INSERT INTO chat_members (chat_id, user_id, position)
|
|
||||||
VALUES (?, ?, ?)
|
|
||||||
""")) {
|
|
||||||
for (int i = 0; i < memberIds.size(); i++) {
|
|
||||||
member.setObject(1, chatId);
|
|
||||||
member.setObject(2, memberIds.get(i));
|
|
||||||
member.setInt(3, i);
|
|
||||||
member.addBatch();
|
|
||||||
}
|
|
||||||
member.executeBatch();
|
|
||||||
}
|
|
||||||
Chat chat = loadChat(conn, callerId, chatId).orElseThrow(ApiException::internalError);
|
|
||||||
conn.commit();
|
|
||||||
return chat;
|
|
||||||
} catch (ApiException e) {
|
|
||||||
rollback(conn);
|
|
||||||
throw e;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
rollback(conn);
|
|
||||||
if ("23503".equals(e.getSQLState())) {
|
|
||||||
throw ApiException.invalid("Указан неизвестный участник");
|
|
||||||
}
|
|
||||||
throw map(e);
|
|
||||||
} finally {
|
|
||||||
close(conn);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Chat> chats(UUID userId, int limit, Instant afterTime, UUID afterId) {
|
|
||||||
String sql = """
|
|
||||||
SELECT c.id, c.title, c.created_at
|
|
||||||
FROM chats c
|
|
||||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = ?
|
|
||||||
""";
|
|
||||||
if (afterTime != null) {
|
|
||||||
sql += " WHERE (c.created_at, c.id) > (?, ?)";
|
|
||||||
}
|
|
||||||
sql += " ORDER BY c.created_at, c.id LIMIT ?";
|
|
||||||
try (Connection conn = dataSource.getConnection();
|
|
||||||
PreparedStatement statement = conn.prepareStatement(sql)) {
|
|
||||||
int index = 1;
|
|
||||||
statement.setObject(index++, userId);
|
|
||||||
if (afterTime != null) {
|
|
||||||
statement.setObject(index++, timestamp(afterTime));
|
|
||||||
statement.setObject(index++, afterId);
|
|
||||||
}
|
|
||||||
statement.setInt(index, limit);
|
|
||||||
List<Chat> chats = new ArrayList<>();
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
while (rows.next()) {
|
|
||||||
UUID id = rows.getObject("id", UUID.class);
|
|
||||||
chats.add(new Chat(
|
|
||||||
id,
|
|
||||||
rows.getString("title"),
|
|
||||||
members(conn, id),
|
|
||||||
instant(rows, "created_at")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return chats;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
throw map(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Optional<Chat> visibleChat(UUID userId, UUID chatId) {
|
|
||||||
try (Connection conn = dataSource.getConnection()) {
|
|
||||||
return loadChat(conn, userId, chatId);
|
|
||||||
} catch (SQLException e) {
|
|
||||||
throw map(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Message addMessage(UUID senderId, UUID chatId, String text) {
|
|
||||||
Connection conn = open();
|
|
||||||
try {
|
|
||||||
conn.setAutoCommit(false);
|
|
||||||
long millis = tick(conn);
|
|
||||||
UUID id = UUID.randomUUID();
|
|
||||||
try (PreparedStatement insert = conn.prepareStatement("""
|
|
||||||
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
|
|
||||||
SELECT ?, ?, ?, ?, ?
|
|
||||||
WHERE EXISTS (
|
|
||||||
SELECT 1 FROM chat_members WHERE chat_id = ? AND user_id = ?
|
|
||||||
)
|
|
||||||
RETURNING id, chat_id, sender_id, body, created_at
|
|
||||||
""")) {
|
|
||||||
insert.setObject(1, id);
|
|
||||||
insert.setObject(2, chatId);
|
|
||||||
insert.setObject(3, senderId);
|
|
||||||
insert.setString(4, text);
|
|
||||||
insert.setObject(5, timestamp(millis));
|
|
||||||
insert.setObject(6, chatId);
|
|
||||||
insert.setObject(7, senderId);
|
|
||||||
try (ResultSet rows = insert.executeQuery()) {
|
|
||||||
if (!rows.next()) {
|
|
||||||
throw ApiException.notFound();
|
|
||||||
}
|
|
||||||
Message message = messageFrom(rows);
|
|
||||||
conn.commit();
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (ApiException e) {
|
|
||||||
rollback(conn);
|
|
||||||
throw e;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
rollback(conn);
|
|
||||||
throw map(e);
|
|
||||||
} finally {
|
|
||||||
close(conn);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Message> messages(UUID userId, UUID chatId, int limit, Instant afterTime, UUID afterId) {
|
|
||||||
try (Connection conn = dataSource.getConnection()) {
|
|
||||||
if (loadChat(conn, userId, chatId).isEmpty()) {
|
|
||||||
throw ApiException.notFound();
|
|
||||||
}
|
|
||||||
String sql = """
|
|
||||||
SELECT id, chat_id, sender_id, body, created_at
|
|
||||||
FROM messages
|
|
||||||
WHERE chat_id = ?
|
|
||||||
""";
|
|
||||||
if (afterTime != null) {
|
|
||||||
sql += " AND (created_at, id) > (?, ?)";
|
|
||||||
}
|
|
||||||
sql += " ORDER BY created_at, id LIMIT ?";
|
|
||||||
try (PreparedStatement statement = conn.prepareStatement(sql)) {
|
|
||||||
int index = 1;
|
|
||||||
statement.setObject(index++, chatId);
|
|
||||||
if (afterTime != null) {
|
|
||||||
statement.setObject(index++, timestamp(afterTime));
|
|
||||||
statement.setObject(index++, afterId);
|
|
||||||
}
|
|
||||||
statement.setInt(index, limit);
|
|
||||||
List<Message> messages = new ArrayList<>();
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
while (rows.next()) {
|
|
||||||
messages.add(messageFrom(rows));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return messages;
|
|
||||||
}
|
|
||||||
} catch (ApiException e) {
|
|
||||||
throw e;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
throw map(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String explainHistory(UUID chatId, Instant afterTime, UUID afterId) {
|
|
||||||
try (Connection conn = dataSource.getConnection()) {
|
|
||||||
try (Statement analyze = conn.createStatement()) {
|
|
||||||
analyze.execute("ANALYZE messages");
|
|
||||||
}
|
|
||||||
try (PreparedStatement statement = conn.prepareStatement("""
|
|
||||||
EXPLAIN (ANALYZE, BUFFERS)
|
|
||||||
SELECT id, chat_id, sender_id, body, created_at
|
|
||||||
FROM messages
|
|
||||||
WHERE chat_id = ?
|
|
||||||
AND (created_at, id) > (?, ?)
|
|
||||||
ORDER BY created_at, id
|
|
||||||
LIMIT 50
|
|
||||||
""")) {
|
|
||||||
statement.setObject(1, chatId);
|
|
||||||
statement.setObject(2, timestamp(afterTime));
|
|
||||||
statement.setObject(3, afterId);
|
|
||||||
StringBuilder plan = new StringBuilder();
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
while (rows.next()) {
|
|
||||||
plan.append(rows.getString(1)).append('\n');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return plan.toString();
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
throw map(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean ready() {
|
|
||||||
try (Connection conn = dataSource.getConnection();
|
|
||||||
Statement statement = conn.createStatement()) {
|
|
||||||
statement.setQueryTimeout(2);
|
|
||||||
statement.execute("SELECT 1");
|
|
||||||
return true;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void close() {
|
|
||||||
dataSource.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean applied(Connection conn, String version) throws SQLException {
|
|
||||||
try (PreparedStatement statement = conn.prepareStatement(
|
|
||||||
"SELECT 1 FROM schema_migrations WHERE version = ?")) {
|
|
||||||
statement.setString(1, version);
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
return rows.next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void runScript(Connection conn, String resource) throws SQLException, IOException {
|
|
||||||
String sql;
|
|
||||||
try (InputStream input = PostgresStore.class.getResourceAsStream(resource)) {
|
|
||||||
if (input == null) {
|
|
||||||
throw new IOException("missing migration");
|
|
||||||
}
|
|
||||||
sql = new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
|
||||||
}
|
|
||||||
StringBuilder current = new StringBuilder();
|
|
||||||
for (String line : sql.split("\n", -1)) {
|
|
||||||
if (line.trim().startsWith("--")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
current.append(line).append('\n');
|
|
||||||
}
|
|
||||||
for (String statement : current.toString().split(";")) {
|
|
||||||
String trimmed = statement.trim();
|
|
||||||
if (trimmed.isEmpty()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
try (Statement sqlStatement = conn.createStatement()) {
|
|
||||||
sqlStatement.execute(trimmed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private long tick(Connection conn) throws SQLException {
|
|
||||||
try (PreparedStatement statement = conn.prepareStatement("""
|
|
||||||
UPDATE app_clock
|
|
||||||
SET millis = GREATEST(millis + 1, (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
|
|
||||||
WHERE id = 1
|
|
||||||
RETURNING millis
|
|
||||||
""");
|
|
||||||
ResultSet rows = statement.executeQuery()) {
|
|
||||||
if (!rows.next()) {
|
|
||||||
throw new SQLException("clock missing", "XX000");
|
|
||||||
}
|
|
||||||
return rows.getLong(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean lockUser(Connection conn, UUID id) throws SQLException {
|
|
||||||
try (PreparedStatement statement = conn.prepareStatement(
|
|
||||||
"SELECT id FROM users WHERE id = ? FOR UPDATE")) {
|
|
||||||
statement.setObject(1, id);
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
return rows.next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Optional<User> loadUser(Connection conn, UUID id) throws SQLException {
|
|
||||||
try (PreparedStatement statement = conn.prepareStatement("""
|
|
||||||
SELECT id, username, display_name, created_at
|
|
||||||
FROM users
|
|
||||||
WHERE id = ?
|
|
||||||
""")) {
|
|
||||||
statement.setObject(1, id);
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
if (!rows.next()) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
return Optional.of(userFrom(rows));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Optional<Chat> loadChat(Connection conn, UUID userId, UUID chatId) throws SQLException {
|
|
||||||
try (PreparedStatement statement = conn.prepareStatement("""
|
|
||||||
SELECT c.id, c.title, c.created_at
|
|
||||||
FROM chats c
|
|
||||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = ?
|
|
||||||
WHERE c.id = ?
|
|
||||||
""")) {
|
|
||||||
statement.setObject(1, userId);
|
|
||||||
statement.setObject(2, chatId);
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
if (!rows.next()) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
return Optional.of(new Chat(
|
|
||||||
rows.getObject("id", UUID.class),
|
|
||||||
rows.getString("title"),
|
|
||||||
members(conn, chatId),
|
|
||||||
instant(rows, "created_at")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<UUID> members(Connection conn, UUID chatId) throws SQLException {
|
|
||||||
try (PreparedStatement statement = conn.prepareStatement("""
|
|
||||||
SELECT user_id
|
|
||||||
FROM chat_members
|
|
||||||
WHERE chat_id = ?
|
|
||||||
ORDER BY position
|
|
||||||
""")) {
|
|
||||||
statement.setObject(1, chatId);
|
|
||||||
List<UUID> ids = new ArrayList<>();
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
while (rows.next()) {
|
|
||||||
ids.add(rows.getObject("user_id", UUID.class));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return List.copyOf(ids);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static User userFrom(ResultSet rows) throws SQLException {
|
|
||||||
return new User(
|
|
||||||
rows.getObject("id", UUID.class),
|
|
||||||
rows.getString("username"),
|
|
||||||
rows.getString("display_name"),
|
|
||||||
instant(rows, "created_at"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Message messageFrom(ResultSet rows) throws SQLException {
|
|
||||||
return new Message(
|
|
||||||
rows.getObject("id", UUID.class),
|
|
||||||
rows.getObject("chat_id", UUID.class),
|
|
||||||
rows.getObject("sender_id", UUID.class),
|
|
||||||
rows.getString("body"),
|
|
||||||
instant(rows, "created_at"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Instant instant(ResultSet rows, String column) throws SQLException {
|
|
||||||
OffsetDateTime value = rows.getObject(column, OffsetDateTime.class);
|
|
||||||
return Instant.ofEpochMilli(value.toInstant().toEpochMilli());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static OffsetDateTime timestamp(long millis) {
|
|
||||||
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.UTC);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static OffsetDateTime timestamp(Instant instant) {
|
|
||||||
return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Connection open() {
|
|
||||||
try {
|
|
||||||
return dataSource.getConnection();
|
|
||||||
} catch (SQLException e) {
|
|
||||||
throw map(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void rollback(Connection conn) {
|
|
||||||
try {
|
|
||||||
conn.rollback();
|
|
||||||
} catch (SQLException ignored) {
|
|
||||||
// соединение уже не годится, клиенту всё равно уйдёт ошибка
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void close(Connection conn) {
|
|
||||||
try {
|
|
||||||
conn.close();
|
|
||||||
} catch (SQLException ignored) {
|
|
||||||
// пул сам выкинет сломанное соединение
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static ApiException map(SQLException e) {
|
|
||||||
String state = e.getSQLState();
|
|
||||||
if (state != null && (state.startsWith("08") || state.startsWith("53") || state.equals("57P01"))) {
|
|
||||||
return ApiException.dependency();
|
|
||||||
}
|
|
||||||
String name = e.getClass().getName();
|
|
||||||
if (name.contains("SQLTransientConnectionException") || name.contains("SQLTimeoutException")) {
|
|
||||||
return ApiException.dependency();
|
|
||||||
}
|
|
||||||
System.err.println("event=sql state=" + (state == null ? "none" : state)
|
|
||||||
+ " type=" + e.getClass().getSimpleName());
|
|
||||||
return ApiException.internalError();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package ru.mtusi.lab2;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
record Session(String token, Instant expiresAt, User user) {}
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package ru.mtusi.lab2;
|
|
||||||
|
|
||||||
import redis.clients.jedis.Jedis;
|
|
||||||
import redis.clients.jedis.JedisPool;
|
|
||||||
import redis.clients.jedis.JedisPoolConfig;
|
|
||||||
import redis.clients.jedis.exceptions.JedisException;
|
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Сессии живут только в Redis. Ключ sess:<token> хранит id пользователя и снимается по TTL.
|
|
||||||
* На стенде у Redis включён AOF, поэтому после рестарта контейнера ключи остаются на volume.
|
|
||||||
*/
|
|
||||||
final class SessionStore implements AutoCloseable {
|
|
||||||
private final JedisPool pool;
|
|
||||||
|
|
||||||
SessionStore(String redisUrl) {
|
|
||||||
JedisPoolConfig config = new JedisPoolConfig();
|
|
||||||
config.setMaxTotal(16);
|
|
||||||
config.setMaxWait(Duration.ofMillis(1000));
|
|
||||||
config.setTestOnBorrow(true);
|
|
||||||
this.pool = new JedisPool(config, URI.create(redisUrl), 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
void save(String token, UUID userId, int ttlSeconds) {
|
|
||||||
try (Jedis jedis = pool.getResource()) {
|
|
||||||
jedis.setex(key(token), ttlSeconds, userId.toString());
|
|
||||||
} catch (JedisException e) {
|
|
||||||
throw ApiException.dependency();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Optional<UUID> find(String token) {
|
|
||||||
try (Jedis jedis = pool.getResource()) {
|
|
||||||
String value = jedis.get(key(token));
|
|
||||||
if (value == null) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
return Optional.of(UUID.fromString(value));
|
|
||||||
} catch (JedisException | IllegalArgumentException e) {
|
|
||||||
if (e instanceof IllegalArgumentException) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
throw ApiException.dependency();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean revoke(String token) {
|
|
||||||
try (Jedis jedis = pool.getResource()) {
|
|
||||||
return jedis.del(key(token)) == 1L;
|
|
||||||
} catch (JedisException e) {
|
|
||||||
throw ApiException.dependency();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean ready() {
|
|
||||||
try (Jedis jedis = pool.getResource()) {
|
|
||||||
return "PONG".equals(jedis.ping());
|
|
||||||
} catch (JedisException e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void close() {
|
|
||||||
pool.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String key(String token) {
|
|
||||||
return "sess:" + token;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
username varchar(32) NOT NULL UNIQUE,
|
||||||
|
display_name varchar(100) NOT NULL,
|
||||||
|
password_hash varchar(255) NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
title varchar(100) NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE TABLE chat_members (
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
sender_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
text varchar(4000) NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX messages_chat_created_idx ON messages(chat_id, created_at, id);
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
token varchar(128) PRIMARY KEY,
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
expires_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX sessions_expiry_idx ON sessions(expires_at);
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
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_key UNIQUE (username)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE chats (
|
|
||||||
id uuid PRIMARY KEY,
|
|
||||||
title text NOT NULL,
|
|
||||||
created_at timestamptz NOT NULL
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE chat_members (
|
|
||||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
|
||||||
user_id uuid NOT NULL REFERENCES users (id),
|
|
||||||
position integer NOT NULL,
|
|
||||||
PRIMARY KEY (chat_id, user_id)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE messages (
|
|
||||||
id uuid PRIMARY KEY,
|
|
||||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
|
||||||
sender_id uuid NOT NULL REFERENCES users (id),
|
|
||||||
body text NOT NULL,
|
|
||||||
created_at timestamptz NOT NULL
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
|
||||||
|
|
||||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
|
||||||
|
|
||||||
CREATE INDEX chats_order_idx ON chats (created_at, id);
|
|
||||||
|
|
||||||
CREATE TABLE app_clock (
|
|
||||||
id integer PRIMARY KEY,
|
|
||||||
millis bigint NOT NULL,
|
|
||||||
CONSTRAINT app_clock_one CHECK (id = 1)
|
|
||||||
);
|
|
||||||
|
|
||||||
INSERT INTO app_clock (id, millis) VALUES (1, 0);
|
|
||||||
@@ -1,581 +0,0 @@
|
|||||||
package ru.mtusi.lab2;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
|
||||||
import org.junit.jupiter.api.AfterAll;
|
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
|
||||||
import org.junit.jupiter.api.MethodOrderer;
|
|
||||||
import org.junit.jupiter.api.Order;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.TestMethodOrder;
|
|
||||||
import org.junit.jupiter.api.Timeout;
|
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
|
||||||
import java.net.http.HttpResponse;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.DriverManager;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.Statement;
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.OffsetDateTime;
|
|
||||||
import java.time.ZoneOffset;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
|
||||||
import java.util.concurrent.CyclicBarrier;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.Future;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
|
||||||
@Timeout(value = 4, unit = TimeUnit.MINUTES)
|
|
||||||
class LabBehaviorTest {
|
|
||||||
private static final JsonMapper JSON = new JsonMapper();
|
|
||||||
private static final List<String> LOGS = new CopyOnWriteArrayList<>();
|
|
||||||
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
|
|
||||||
|
|
||||||
private static final String POSTGRES_NAME = "mtusi-lab2-test-pg";
|
|
||||||
private static final String REDIS_NAME = "mtusi-lab2-test-redis";
|
|
||||||
private static final String DB_USER = "messenger";
|
|
||||||
private static final String DB_PASSWORD = "messenger";
|
|
||||||
|
|
||||||
private static MessengerServer server;
|
|
||||||
private static String base;
|
|
||||||
private static String jdbcUrl;
|
|
||||||
private static int redisPort;
|
|
||||||
|
|
||||||
@BeforeAll
|
|
||||||
static void start() throws Exception {
|
|
||||||
docker("rm", "-f", POSTGRES_NAME);
|
|
||||||
docker("rm", "-f", REDIS_NAME);
|
|
||||||
docker("run", "-d", "--name", POSTGRES_NAME,
|
|
||||||
"-e", "POSTGRES_USER=" + DB_USER,
|
|
||||||
"-e", "POSTGRES_PASSWORD=" + DB_PASSWORD,
|
|
||||||
"-e", "POSTGRES_DB=messenger",
|
|
||||||
"-p", "127.0.0.1::5432",
|
|
||||||
"postgres:16.6");
|
|
||||||
docker("run", "-d", "--name", REDIS_NAME,
|
|
||||||
"-p", "127.0.0.1::6379",
|
|
||||||
"redis:7.4.2");
|
|
||||||
waitUntil(POSTGRES_NAME, "pg_isready", "-U", DB_USER, "-d", "messenger");
|
|
||||||
waitUntil(REDIS_NAME, "redis-cli", "ping");
|
|
||||||
int pgPort = publishedPort(POSTGRES_NAME, 5432);
|
|
||||||
redisPort = publishedPort(REDIS_NAME, 6379);
|
|
||||||
jdbcUrl = "jdbc:postgresql://127.0.0.1:" + pgPort + "/messenger?connectTimeout=2&socketTimeout=2";
|
|
||||||
String redisUrl = "redis://127.0.0.1:" + redisPort + "/0";
|
|
||||||
Config config = new Config("127.0.0.1", 0, "test", jdbcUrl, DB_USER, DB_PASSWORD, redisUrl, 3600, 4);
|
|
||||||
server = MessengerServer.start(config, LOGS::add, LOGS::add);
|
|
||||||
base = "http://127.0.0.1:" + server.port();
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterAll
|
|
||||||
static void stop() {
|
|
||||||
if (server != null) {
|
|
||||||
server.stop();
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
docker("rm", "-f", POSTGRES_NAME);
|
|
||||||
docker("rm", "-f", REDIS_NAME);
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
// контейнеры тестов уже сняты
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(1)
|
|
||||||
void migrationCanRunAgain() throws Exception {
|
|
||||||
Passwords passwords = new Passwords(4);
|
|
||||||
try (PostgresStore again = new PostgresStore(jdbcUrl, DB_USER, DB_PASSWORD, passwords)) {
|
|
||||||
again.migrate();
|
|
||||||
again.migrate();
|
|
||||||
}
|
|
||||||
assertEquals(1, queryInt("SELECT count(*) FROM schema_migrations"));
|
|
||||||
assertEquals(1, queryInt("SELECT count(*) FROM app_clock"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(2)
|
|
||||||
void authValidationAndHistory() throws Exception {
|
|
||||||
Resp live = call("GET", "/health/live", null, null);
|
|
||||||
assertEquals(200, live.status);
|
|
||||||
Resp ready = call("GET", "/health/ready", null, null);
|
|
||||||
assertEquals(200, ready.status);
|
|
||||||
|
|
||||||
Resp broken = call("POST", "/api/v1/users", null, "{");
|
|
||||||
assertEquals(400, broken.status);
|
|
||||||
Resp typed = call("POST", "/api/v1/users", null, "{\"username\":1,\"display_name\":\"Аня\",\"password\":\"password-ok-12\"}");
|
|
||||||
assertEquals(400, typed.status);
|
|
||||||
Resp extra = call("POST", "/api/v1/users", null,
|
|
||||||
"{\"username\":\"bad_extra_user\",\"display_name\":\"Аня\",\"password\":\"password-ok-12\",\"role\":\"x\"}");
|
|
||||||
assertEquals(400, extra.status);
|
|
||||||
Resp shortPassword = call("POST", "/api/v1/users", null,
|
|
||||||
"{\"username\":\"short_pw_user\",\"display_name\":\"Аня\",\"password\":\"short\"}");
|
|
||||||
assertEquals(400, shortPassword.status);
|
|
||||||
Resp blankName = call("POST", "/api/v1/users", null,
|
|
||||||
"{\"username\":\"blank_name_u\",\"display_name\":\" \",\"password\":\"password-ok-12\"}");
|
|
||||||
assertEquals(400, blankName.status);
|
|
||||||
|
|
||||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
|
||||||
JsonNode alice = register("alice_" + suffix, "Алиса");
|
|
||||||
JsonNode bob = register("bob_" + suffix, "Боб 👋");
|
|
||||||
JsonNode eve = register("eve_" + suffix, "Ева");
|
|
||||||
assertFalse(alice.toString().contains("password"));
|
|
||||||
Resp duplicate = call("POST", "/api/v1/users", null, userBody("alice_" + suffix, "Алиса"));
|
|
||||||
assertEquals(409, duplicate.status);
|
|
||||||
|
|
||||||
Resp noAuth = call("GET", "/api/v1/users/me", null, null);
|
|
||||||
assertEquals(401, noAuth.status);
|
|
||||||
assertTrue(noAuth.challenge.toLowerCase().startsWith("bearer"));
|
|
||||||
Resp byUserId = call("GET", "/api/v1/users/me", null, null, "X-User-Id", alice.get("id").asText());
|
|
||||||
assertEquals(401, byUserId.status);
|
|
||||||
|
|
||||||
String aliceBasic = basic("alice_" + suffix, "password-ok-12");
|
|
||||||
Resp wrong = call("POST", "/api/v1/auth/sessions", null, null, "Authorization",
|
|
||||||
basic("alice_" + suffix, "wrong-password-1"));
|
|
||||||
assertEquals(401, wrong.status);
|
|
||||||
assertTrue(wrong.challenge.toLowerCase().startsWith("basic"));
|
|
||||||
Resp basicOnBusiness = call("GET", "/api/v1/users/me", null, null, "Authorization", aliceBasic);
|
|
||||||
assertEquals(401, basicOnBusiness.status);
|
|
||||||
assertTrue(basicOnBusiness.challenge.toLowerCase().startsWith("bearer"));
|
|
||||||
|
|
||||||
String aliceToken = login("alice_" + suffix);
|
|
||||||
String bobToken = login("bob_" + suffix);
|
|
||||||
String eveToken = login("eve_" + suffix);
|
|
||||||
Resp me = call("GET", "/api/v1/users/me", aliceToken, null, "X-User-Id", eve.get("id").asText());
|
|
||||||
assertEquals(200, me.status);
|
|
||||||
assertEquals(alice.get("id").asText(), JSON.readTree(me.body).get("id").asText());
|
|
||||||
|
|
||||||
String chatBody = "{\"title\":\"Демо\",\"member_ids\":[\"" + alice.get("id").asText()
|
|
||||||
+ "\",\"" + bob.get("id").asText() + "\"]}";
|
|
||||||
Resp chat = call("POST", "/api/v1/chats", aliceToken, chatBody);
|
|
||||||
assertEquals(201, chat.status);
|
|
||||||
String chatId = JSON.readTree(chat.body).get("id").asText();
|
|
||||||
Resp outsider = call("GET", "/api/v1/chats/" + chatId, eveToken, null);
|
|
||||||
assertEquals(404, outsider.status);
|
|
||||||
Resp hidden = call("GET", "/api/v1/chats?limit=100", eveToken, null);
|
|
||||||
assertEquals(200, hidden.status);
|
|
||||||
assertFalse(hidden.body.contains(chatId));
|
|
||||||
|
|
||||||
String secret = "synthetic-text-" + suffix;
|
|
||||||
Resp empty = call("POST", "/api/v1/chats/" + chatId + "/messages", aliceToken, "{\"text\":\"\"}");
|
|
||||||
assertEquals(400, empty.status);
|
|
||||||
Resp foreign = call("POST", "/api/v1/chats/" + chatId + "/messages", eveToken, "{\"text\":\"чужое\"}");
|
|
||||||
assertEquals(404, foreign.status);
|
|
||||||
Resp badLimit = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=0", aliceToken, null);
|
|
||||||
assertEquals(400, badLimit.status);
|
|
||||||
Resp first = call("POST", "/api/v1/chats/" + chatId + "/messages", aliceToken, "{\"text\":\"" + secret + " 👋\"}");
|
|
||||||
Resp second = call("POST", "/api/v1/chats/" + chatId + "/messages", bobToken, "{\"text\":\"ответ Боба\"}");
|
|
||||||
assertEquals(201, first.status);
|
|
||||||
assertEquals(201, second.status);
|
|
||||||
Resp page1 = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1", bobToken, null);
|
|
||||||
JsonNode page1Json = JSON.readTree(page1.body);
|
|
||||||
assertEquals(1, page1Json.get("items").size());
|
|
||||||
assertFalse(page1Json.get("next_cursor").isNull());
|
|
||||||
String cursor = page1Json.get("next_cursor").asText();
|
|
||||||
Resp page2 = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1&cursor=" + encode(cursor), aliceToken, null);
|
|
||||||
JsonNode page2Json = JSON.readTree(page2.body);
|
|
||||||
assertEquals(1, page2Json.get("items").size());
|
|
||||||
assertTrue(page2Json.get("next_cursor").isNull());
|
|
||||||
assertEquals(JSON.readTree(first.body).get("id").asText(), page1Json.get("items").get(0).get("id").asText());
|
|
||||||
assertEquals(JSON.readTree(second.body).get("id").asText(), page2Json.get("items").get(0).get("id").asText());
|
|
||||||
Resp stolen = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1&cursor=" + encode(cursor), eveToken, null);
|
|
||||||
assertEquals(404, stolen.status);
|
|
||||||
String joined = String.join("\n", LOGS);
|
|
||||||
assertFalse(joined.contains(secret));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(3)
|
|
||||||
void parallelMessagesStayUnique() throws Exception {
|
|
||||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
|
||||||
JsonNode user = register("par_" + suffix, "Параллель");
|
|
||||||
String token = login("par_" + suffix);
|
|
||||||
Resp chat = call("POST", "/api/v1/chats", token,
|
|
||||||
"{\"title\":\"Гонка\",\"member_ids\":[\"" + user.get("id").asText() + "\"]}");
|
|
||||||
String chatId = JSON.readTree(chat.body).get("id").asText();
|
|
||||||
ExecutorService pool = Executors.newFixedThreadPool(10);
|
|
||||||
List<Future<Resp>> futures = new ArrayList<>();
|
|
||||||
for (int i = 0; i < 100; i++) {
|
|
||||||
int n = i;
|
|
||||||
futures.add(pool.submit(() -> call("POST", "/api/v1/chats/" + chatId + "/messages", token,
|
|
||||||
"{\"text\":\"m-" + n + "\"}")));
|
|
||||||
}
|
|
||||||
List<String> ids = new ArrayList<>();
|
|
||||||
for (Future<Resp> future : futures) {
|
|
||||||
Resp response = future.get();
|
|
||||||
assertEquals(201, response.status);
|
|
||||||
ids.add(JSON.readTree(response.body).get("id").asText());
|
|
||||||
}
|
|
||||||
pool.shutdown();
|
|
||||||
assertEquals(100, ids.stream().distinct().count());
|
|
||||||
assertEquals(100, queryInt("SELECT count(*) FROM messages WHERE chat_id = '" + chatId + "'"));
|
|
||||||
System.out.println("CONCURRENCY PASS clients=10 messages=100 unique=100");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(4)
|
|
||||||
void duplicateUsernameRace() throws Exception {
|
|
||||||
String username = "race_" + UUID.randomUUID().toString().substring(0, 8);
|
|
||||||
String body = userBody(username, "Гонка");
|
|
||||||
int threads = 16;
|
|
||||||
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
|
||||||
CyclicBarrier barrier = new CyclicBarrier(threads);
|
|
||||||
List<Future<Integer>> futures = new ArrayList<>();
|
|
||||||
for (int i = 0; i < threads; i++) {
|
|
||||||
futures.add(pool.submit(() -> {
|
|
||||||
barrier.await();
|
|
||||||
return call("POST", "/api/v1/users", null, body).status;
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
int created = 0;
|
|
||||||
int conflict = 0;
|
|
||||||
for (Future<Integer> future : futures) {
|
|
||||||
int status = future.get();
|
|
||||||
if (status == 201) {
|
|
||||||
created++;
|
|
||||||
} else if (status == 409) {
|
|
||||||
conflict++;
|
|
||||||
} else {
|
|
||||||
throw new AssertionError("unexpected status " + status);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pool.shutdown();
|
|
||||||
assertEquals(1, created);
|
|
||||||
assertEquals(threads - 1, conflict);
|
|
||||||
assertEquals(1, queryInt("SELECT count(*) FROM users WHERE username = '" + username + "'"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(5)
|
|
||||||
void chatCreateRollsBack() throws Exception {
|
|
||||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
|
||||||
JsonNode alice = register("rb_a_" + suffix, "Алиса");
|
|
||||||
JsonNode bob = register("rb_b_" + suffix, "Боб");
|
|
||||||
String token = login("rb_a_" + suffix);
|
|
||||||
int before = queryInt("SELECT count(*) FROM chats");
|
|
||||||
try (Connection conn = open(); Statement statement = conn.createStatement()) {
|
|
||||||
statement.execute("""
|
|
||||||
CREATE OR REPLACE FUNCTION lab_fail_second_member() RETURNS trigger
|
|
||||||
LANGUAGE plpgsql AS $$
|
|
||||||
BEGIN
|
|
||||||
IF NEW.position > 0 THEN
|
|
||||||
RAISE EXCEPTION 'forced rollback';
|
|
||||||
END IF;
|
|
||||||
RETURN NEW;
|
|
||||||
END;
|
|
||||||
$$
|
|
||||||
""");
|
|
||||||
statement.execute("""
|
|
||||||
CREATE TRIGGER lab_fail_second_member
|
|
||||||
BEFORE INSERT ON chat_members
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION lab_fail_second_member()
|
|
||||||
""");
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Resp chat = call("POST", "/api/v1/chats", token, "{\"title\":\"Сломанный\",\"member_ids\":[\""
|
|
||||||
+ alice.get("id").asText() + "\",\"" + bob.get("id").asText() + "\"]}");
|
|
||||||
assertEquals(500, chat.status);
|
|
||||||
assertEquals(before, queryInt("SELECT count(*) FROM chats"));
|
|
||||||
assertEquals(before, queryInt("SELECT count(DISTINCT chat_id) FROM chat_members"));
|
|
||||||
} finally {
|
|
||||||
try (Connection conn = open(); Statement statement = conn.createStatement()) {
|
|
||||||
statement.execute("DROP TRIGGER IF EXISTS lab_fail_second_member ON chat_members");
|
|
||||||
statement.execute("DROP FUNCTION IF EXISTS lab_fail_second_member()");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Resp recovered = call("POST", "/api/v1/chats", token, "{\"title\":\"После отката\",\"member_ids\":[\""
|
|
||||||
+ alice.get("id").asText() + "\",\"" + bob.get("id").asText() + "\"]}");
|
|
||||||
assertEquals(201, recovered.status);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(6)
|
|
||||||
void expiryLogoutAndWrongPassword() throws Exception {
|
|
||||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
|
||||||
register("ttl_" + suffix, "Короткий");
|
|
||||||
String redisUrl = "redis://127.0.0.1:" + redisPort + "/0";
|
|
||||||
List<String> localLogs = new CopyOnWriteArrayList<>();
|
|
||||||
MessengerServer shortServer = MessengerServer.start(new Config(
|
|
||||||
"127.0.0.1", 0, "test", jdbcUrl, DB_USER, DB_PASSWORD, redisUrl, 2, 4),
|
|
||||||
localLogs::add, localLogs::add);
|
|
||||||
try {
|
|
||||||
String shortBase = "http://127.0.0.1:" + shortServer.port();
|
|
||||||
Resp session = callAt(shortBase, "POST", "/api/v1/auth/sessions", null, null, "Authorization",
|
|
||||||
basic("ttl_" + suffix, "password-ok-12"));
|
|
||||||
assertEquals(201, session.status);
|
|
||||||
JsonNode body = JSON.readTree(session.body);
|
|
||||||
assertTrue(Instant.parse(body.get("expires_at").asText()).isAfter(Instant.now()));
|
|
||||||
String token = body.get("token").asText();
|
|
||||||
Thread.sleep(3500);
|
|
||||||
Resp expired = callAt(shortBase, "GET", "/api/v1/users/me", token, null, null, null);
|
|
||||||
assertEquals(401, expired.status);
|
|
||||||
} finally {
|
|
||||||
shortServer.stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
register("out_" + suffix, "Выход");
|
|
||||||
String token = login("out_" + suffix);
|
|
||||||
Resp denied = call("POST", "/api/v1/auth/sessions", null, null, "Authorization",
|
|
||||||
basic("out_" + suffix, "definitely-wrong"));
|
|
||||||
assertEquals(401, denied.status);
|
|
||||||
Resp logout = call("DELETE", "/api/v1/auth/sessions/current", token, null);
|
|
||||||
assertEquals(204, logout.status);
|
|
||||||
assertTrue(logout.body.isEmpty());
|
|
||||||
Resp again = call("GET", "/api/v1/users/me", token, null);
|
|
||||||
assertEquals(401, again.status);
|
|
||||||
Resp secondLogout = call("DELETE", "/api/v1/auth/sessions/current", token, null);
|
|
||||||
assertEquals(401, secondLogout.status);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(7)
|
|
||||||
void dependencyLossDoesNotTrustAnonymous() throws Exception {
|
|
||||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
|
||||||
register("dep_" + suffix, "Зависимость");
|
|
||||||
String token = login("dep_" + suffix);
|
|
||||||
docker("pause", REDIS_NAME);
|
|
||||||
try {
|
|
||||||
Resp ready = call("GET", "/health/ready", null, null);
|
|
||||||
assertEquals(503, ready.status);
|
|
||||||
assertTrue(ready.body.contains("unavailable"));
|
|
||||||
Resp me = call("GET", "/api/v1/users/me", token, null);
|
|
||||||
assertEquals(503, me.status);
|
|
||||||
Resp anon = call("GET", "/api/v1/users/me", null, null);
|
|
||||||
assertEquals(401, anon.status);
|
|
||||||
} finally {
|
|
||||||
docker("unpause", REDIS_NAME);
|
|
||||||
}
|
|
||||||
waitReady();
|
|
||||||
assertEquals(200, call("GET", "/api/v1/users/me", token, null).status);
|
|
||||||
|
|
||||||
docker("pause", POSTGRES_NAME);
|
|
||||||
try {
|
|
||||||
Resp ready = call("GET", "/health/ready", null, null);
|
|
||||||
assertEquals(503, ready.status);
|
|
||||||
Resp me = call("GET", "/api/v1/users/me", token, null);
|
|
||||||
assertEquals(503, me.status);
|
|
||||||
} finally {
|
|
||||||
docker("unpause", POSTGRES_NAME);
|
|
||||||
}
|
|
||||||
waitReady();
|
|
||||||
assertEquals(200, call("GET", "/api/v1/users/me", token, null).status);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(8)
|
|
||||||
void historyIndexServesThePage() throws Exception {
|
|
||||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
|
||||||
JsonNode user = register("hist_" + suffix, "История");
|
|
||||||
String token = login("hist_" + suffix);
|
|
||||||
Resp chat = call("POST", "/api/v1/chats", token,
|
|
||||||
"{\"title\":\"Индекс\",\"member_ids\":[\"" + user.get("id").asText() + "\"]}");
|
|
||||||
UUID chatId = UUID.fromString(JSON.readTree(chat.body).get("id").asText());
|
|
||||||
UUID sender = UUID.fromString(user.get("id").asText());
|
|
||||||
Instant start = Instant.now().minusSeconds(60);
|
|
||||||
try (Connection conn = open();
|
|
||||||
PreparedStatement insert = conn.prepareStatement("""
|
|
||||||
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
|
|
||||||
VALUES (?, ?, ?, ?, ?)
|
|
||||||
""")) {
|
|
||||||
for (int i = 0; i < 10_000; i++) {
|
|
||||||
insert.setObject(1, UUID.randomUUID());
|
|
||||||
insert.setObject(2, chatId);
|
|
||||||
insert.setObject(3, sender);
|
|
||||||
insert.setString(4, "row-" + i);
|
|
||||||
insert.setObject(5, OffsetDateTime.ofInstant(start.plusMillis(i), ZoneOffset.UTC));
|
|
||||||
insert.addBatch();
|
|
||||||
if (i % 500 == 499) {
|
|
||||||
insert.executeBatch();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
insert.executeBatch();
|
|
||||||
}
|
|
||||||
Instant cursorTime;
|
|
||||||
UUID cursorId;
|
|
||||||
try (Connection conn = open();
|
|
||||||
PreparedStatement statement = conn.prepareStatement("""
|
|
||||||
SELECT id, created_at
|
|
||||||
FROM messages
|
|
||||||
WHERE chat_id = ?
|
|
||||||
ORDER BY created_at, id
|
|
||||||
OFFSET 9900 LIMIT 1
|
|
||||||
""")) {
|
|
||||||
statement.setObject(1, chatId);
|
|
||||||
try (ResultSet rows = statement.executeQuery()) {
|
|
||||||
assertTrue(rows.next());
|
|
||||||
cursorId = rows.getObject("id", UUID.class);
|
|
||||||
cursorTime = rows.getObject("created_at", OffsetDateTime.class).toInstant();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
String plan = server.store().explainHistory(chatId, cursorTime, cursorId);
|
|
||||||
Path evidence = Path.of("evidence", "explain-plan.txt");
|
|
||||||
Files.createDirectories(evidence.getParent());
|
|
||||||
Files.writeString(evidence, "messages=10000\n\n" + plan);
|
|
||||||
assertTrue(plan.contains("messages_history_idx"), plan);
|
|
||||||
assertTrue(plan.contains("Buffers:"), plan);
|
|
||||||
assertFalse(plan.contains("Seq Scan"), plan);
|
|
||||||
Resp page = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=50", token, null);
|
|
||||||
assertEquals(200, page.status);
|
|
||||||
assertEquals(50, JSON.readTree(page.body).get("items").size());
|
|
||||||
System.out.println("EXPLAIN index=messages_history_idx rows=10000");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Order(9)
|
|
||||||
void shutdownKeepsLiveness() throws Exception {
|
|
||||||
server.refuseNewRequests();
|
|
||||||
assertEquals(200, call("GET", "/health/live", null, null).status);
|
|
||||||
assertEquals(503, call("GET", "/health/ready", null, null).status);
|
|
||||||
Resp post = call("POST", "/api/v1/users", null, userBody("after_stop", "Стоп"));
|
|
||||||
assertEquals(503, post.status);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private static void docker(String... args) throws Exception {
|
|
||||||
java.util.ArrayList<String> command = new java.util.ArrayList<>();
|
|
||||||
command.add("docker");
|
|
||||||
command.addAll(java.util.List.of(args));
|
|
||||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
|
||||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
|
||||||
if (process.waitFor() != 0 && !java.util.List.of(args).contains("-f")) {
|
|
||||||
throw new IllegalStateException(String.join(" ", command) + " -> " + output);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void waitUntil(String container, String... exec) throws Exception {
|
|
||||||
long deadline = System.nanoTime() + Duration.ofSeconds(40).toNanos();
|
|
||||||
while (System.nanoTime() < deadline) {
|
|
||||||
java.util.ArrayList<String> command = new java.util.ArrayList<>();
|
|
||||||
command.add("docker");
|
|
||||||
command.add("exec");
|
|
||||||
command.add(container);
|
|
||||||
command.addAll(java.util.List.of(exec));
|
|
||||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
|
||||||
process.getInputStream().readAllBytes();
|
|
||||||
if (process.waitFor() == 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Thread.sleep(500);
|
|
||||||
}
|
|
||||||
throw new IllegalStateException("container not ready: " + container);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int publishedPort(String container, int port) throws Exception {
|
|
||||||
Process process = new ProcessBuilder("docker", "port", container, port + "/tcp")
|
|
||||||
.redirectErrorStream(true)
|
|
||||||
.start();
|
|
||||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();
|
|
||||||
if (process.waitFor() != 0 || output.isEmpty()) {
|
|
||||||
throw new IllegalStateException("no published port for " + container);
|
|
||||||
}
|
|
||||||
String first = output.split("\n")[0];
|
|
||||||
return Integer.parseInt(first.substring(first.lastIndexOf(':') + 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JsonNode register(String username, String displayName) throws Exception {
|
|
||||||
Resp response = call("POST", "/api/v1/users", null, userBody(username, displayName));
|
|
||||||
assertEquals(201, response.status, response.body);
|
|
||||||
return JSON.readTree(response.body);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String login(String username) throws Exception {
|
|
||||||
Resp response = call("POST", "/api/v1/auth/sessions", null, null, "Authorization", basic(username, "password-ok-12"));
|
|
||||||
assertEquals(201, response.status, response.body);
|
|
||||||
return JSON.readTree(response.body).get("token").asText();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String userBody(String username, String displayName) {
|
|
||||||
return "{\"username\":\"" + username + "\",\"display_name\":\"" + displayName + "\",\"password\":\"password-ok-12\"}";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String basic(String username, String password) {
|
|
||||||
String raw = username + ":" + password;
|
|
||||||
return "Basic " + Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String encode(String value) {
|
|
||||||
return java.net.URLEncoder.encode(value, StandardCharsets.UTF_8);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void waitReady() throws Exception {
|
|
||||||
long deadline = System.nanoTime() + Duration.ofSeconds(20).toNanos();
|
|
||||||
while (System.nanoTime() < deadline) {
|
|
||||||
if (call("GET", "/health/ready", null, null).status == 200) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Thread.sleep(300);
|
|
||||||
}
|
|
||||||
throw new AssertionError("ready did not recover");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int queryInt(String sql) throws Exception {
|
|
||||||
try (Connection conn = open();
|
|
||||||
Statement statement = conn.createStatement();
|
|
||||||
ResultSet rows = statement.executeQuery(sql)) {
|
|
||||||
rows.next();
|
|
||||||
return rows.getInt(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Connection open() throws Exception {
|
|
||||||
String plain = jdbcUrl.replaceAll("[?].*", "");
|
|
||||||
return DriverManager.getConnection(plain, DB_USER, DB_PASSWORD);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Resp call(String method, String path, String token, String json) throws Exception {
|
|
||||||
return call(method, path, token, json, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Resp call(String method, String path, String token, String json, String header, String headerValue) throws Exception {
|
|
||||||
return callAt(base, method, path, token, json, header, headerValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Resp callAt(
|
|
||||||
String root,
|
|
||||||
String method,
|
|
||||||
String path,
|
|
||||||
String token,
|
|
||||||
String json,
|
|
||||||
String header,
|
|
||||||
String headerValue) throws Exception {
|
|
||||||
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(root + path))
|
|
||||||
.timeout(Duration.ofSeconds(12));
|
|
||||||
if (token != null) {
|
|
||||||
builder.header("Authorization", "Bearer " + token);
|
|
||||||
}
|
|
||||||
if (header != null) {
|
|
||||||
builder.header(header, headerValue);
|
|
||||||
}
|
|
||||||
if (json != null) {
|
|
||||||
builder.header("Content-Type", "application/json");
|
|
||||||
builder.method(method, HttpRequest.BodyPublishers.ofString(json));
|
|
||||||
} else if ("POST".equals(method) || "DELETE".equals(method)) {
|
|
||||||
builder.method(method, HttpRequest.BodyPublishers.noBody());
|
|
||||||
} else {
|
|
||||||
builder.method(method, HttpRequest.BodyPublishers.noBody());
|
|
||||||
}
|
|
||||||
HttpResponse<String> response = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString());
|
|
||||||
return new Resp(
|
|
||||||
response.statusCode(),
|
|
||||||
response.body(),
|
|
||||||
response.headers().firstValue("WWW-Authenticate").orElse(""),
|
|
||||||
response.headers().firstValue("X-Request-Id").orElse(""));
|
|
||||||
}
|
|
||||||
|
|
||||||
private record Resp(int status, String body, String challenge, String requestId) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package ru.mtusi.lab2;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
class PasswordTest {
|
|
||||||
@Test
|
|
||||||
void longPasswordsAreNotTruncated() {
|
|
||||||
Passwords passwords = new Passwords(4);
|
|
||||||
String first = "п".repeat(80);
|
|
||||||
String second = "п".repeat(79) + "я";
|
|
||||||
String hash = passwords.hash(first);
|
|
||||||
assertTrue(passwords.verify(first, hash));
|
|
||||||
assertFalse(passwords.verify(second, hash));
|
|
||||||
assertFalse(passwords.verify("other-password-value", hash));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user