Author SHA1 Message Date
GusakDA b94b07654f fix problems
Skeleton contracts / contracts (pull_request) Canceled after 0s
2026-10-30 11:07:02 +03:00
GusakDA e3a6372e91 sulution 2 lab
Skeleton contracts / contracts (pull_request) Canceled after 0s
2026-10-29 20:26:49 +03:00
32 changed files with 1514 additions and 38 deletions
+7
View File
@@ -18,3 +18,10 @@ __pycache__
node_modules
evidence
.DS_Store
target
.idea
.vscode
*.log
.m2
.gradle
build
+11 -5
View File
@@ -4,8 +4,14 @@ APP_HOST=0.0.0.0
APP_PORT=8080
APP_ENV=lab
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
POSTGRES_DB=messenger
POSTGRES_USER=messenger
POSTGRES_PASSWORD=change-me-local-only
REDIS_HOST=redis
REDIS_PORT=6379
DB_POOL_SIZE=4
DB_CONNECTION_TIMEOUT_MS=1000
DB_REQUEST_TIMEOUT_MS=2000
DB_SOCKET_TIMEOUT_SECONDS=1
DB_STATEMENT_TIMEOUT_MS=1000
DB_QUERY_TIMEOUT_SECONDS=1
+1
View File
@@ -14,6 +14,7 @@ volumes/
data/
backups/
# Runtime/build artifacts
.gradle/
.venv/
__pycache__/
*.py[cod]
+20
View File
@@ -0,0 +1,20 @@
FROM eclipse-temurin:21.0.10_7-jdk-jammy@sha256:25d1276565738d3c805e632a4542c3a7598866ef967f4def6544c15de3a74b14 AS build
WORKDIR /build
COPY gradlew build.gradle settings.gradle gradle.properties gradle.lockfile ./
COPY gradle ./gradle
RUN chmod +x gradlew && ./gradlew --no-daemon --console=plain resolveDependencies
COPY src ./src
COPY docker/Healthcheck.java ./docker/Healthcheck.java
RUN ./gradlew --no-daemon --console=plain build && javac -d /healthcheck docker/Healthcheck.java
FROM eclipse-temurin:21.0.10_7-jre-jammy@sha256:fa4854e6057665066cb79953616671c20f32b96a85d6dd8b78db0762203924c4
RUN groupadd --gid 10001 messenger && useradd --uid 10001 --gid messenger --no-create-home --shell /usr/sbin/nologin messenger
WORKDIR /app
COPY --from=build /build/build/libs/messenger.jar /app/messenger.jar
COPY --from=build /healthcheck /app/healthcheck
ENV APP_HOST=0.0.0.0 APP_PORT=8080 JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=60 -XX:+ExitOnOutOfMemoryError"
USER 10001:10001
EXPOSE 8080
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=3 CMD ["java", "-cp", "/app/healthcheck", "Healthcheck"]
ENTRYPOINT ["java", "-jar", "/app/messenger.jar"]
+20 -2
View File
@@ -4,10 +4,10 @@ CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence
.PHONY: help check validate test load test-persistence test-grade4 test-grade4-expiry test-grade4-redis test-grade4-postgres compose-up compose-down
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "check: offline structure; validate: OpenAPI; test: public API; test-persistence: restart persistence; test-grade4: custom lab2 checks"
check:
$(PYTHON) scripts/check_contract.py
@@ -24,3 +24,21 @@ load:
test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-grade4:
$(PYTHON) student-tests/lab2.py --base-url "$(BASE_URL)"
test-grade4-expiry:
$(PYTHON) student-tests/lab2.py --base-url "$(BASE_URL)" --check-expiry
test-grade4-redis:
$(PYTHON) student-tests/lab2.py --base-url "$(BASE_URL)" --check-redis
test-grade4-postgres:
$(PYTHON) student-tests/lab2.py --base-url "$(BASE_URL)" --check-postgres
compose-up:
docker compose --env-file .env up -d --build
compose-down:
docker compose --env-file .env down
+6 -7
View File
@@ -1,8 +1,8 @@
# Лабораторная 2. PostgreSQL, сессии и Redis/Valkey
# Лабораторная 2. PostgreSQL, сессии и Redis
Перенести состояние в постоянное хранилище и связать запросы с аутентифицированным пользователем. Подтверждённые сообщения и действующие сессии переживают перезапуск.
Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен.
Репозиторий начинался как **skeleton** с заданием, контрактом и публичными проверками. В этой рабочей копии реализован Java/Spring Boot вариант уровня 4: PostgreSQL для предметных данных, Redis для TTL-сессий, миграции Flyway и воспроизводимый Compose-стенд. Язык и framework свободные; UI не обязателен.
[Карта курса](COURSE.md) · [Процесс fork/PR](CONTRIBUTING.md) · [OpenAPI](contracts/openapi.json) · [Семантика API](contracts/README.md) · [Проверки](tests/README.md) · [Отчёт](REPORT.md) · [Примеры JSON](contracts/examples.json) · [Памятка преподавателю](MAINTAINERS.md)
@@ -10,7 +10,7 @@
Перенесите собственный минимум lab1. Изменения API: password при регистрации, Basic для создания сессии, Bearer вместо X-User-Id для бизнес-запросов.
**Архитектура:** Клиент → API → PostgreSQL; на 4 появляется Redis ИЛИ Valkey для сессий/кэша.
**Архитектура:** Клиент → API → PostgreSQL; для уровня 4 здесь используется Redis для сессий.
## Что сделать
@@ -18,7 +18,7 @@
2. Перенесите пользователей, чаты, членство и сообщения в PostgreSQL. Не используйте SQLite как замену PostgreSQL в принимаемом стенде.
3. Реализуйте регистрацию с password KDF, вход через Basic, opaque Bearer-сессию, expiry и logout. Действующие сессии тоже должны сохраняться.
4. Подготовьте единый локальный запуск API и БД (Compose рекомендуется уже здесь), подключите именованные volumes.
5. Пройдите smoke и тест полного перезапуска. На 4 добавьте Redis/Valkey с конкретной ролью и повторите эксперимент отказа.
5. Пройдите smoke и тест полного перезапуска. На 4 добавьте Redis с конкретной ролью и повторите эксперимент отказа.
## Оценка «3»: работающий минимум
@@ -31,7 +31,7 @@
Весь уровень 3 **и все** пункты ниже:
- Redis ИЛИ Valkey реально используется для сессий с TTL либо осмысленного кэша. Опишите источник истины, политику expiry и инвалидации. Если это единственное хранилище сессий, включите persistence, выдерживающее проверяемый рестарт; один TTL не сохраняет данные.
- Redis реально используется для сессий с TTL. Источник истины, политику expiry и инвалидации нужно описать. Если Redis — единственное хранилище сессий, включите persistence, выдерживающее проверяемый рестарт; один TTL не сохраняет данные.
- Используются параметризованные запросы/безопасный ORM, ограниченный connection pool и таймауты. Проверены гонка регистрации одинакового username и rollback составной операции.
- Индекс истории обоснован запросом и EXPLAIN (ANALYZE, BUFFERS) на ≥10 000 сообщениях; пагинация не использует полный scan всей истории на каждую страницу.
- Есть автоматическая проверка expiry при коротком SESSION_TTL_SECONDS, logout, неверного пароля и недоступности Redis/БД. При потере сервиса приложение возвращает ограниченную ошибку/корректно обходит кэш, не принимает запрос от анонимного пользователя как доверенный.
@@ -81,7 +81,7 @@ Smoke не выставляет оценку автоматически. Про
1. Применить миграции к пустому volume, создать пользователей, войти, отправить сообщение.
2. Запустить persistence-сценарий: он держит токен только в памяти тестового процесса; action script перезапускает API и все используемые хранилища, сохраняя volumes.
3. После готовности тот же токен читает те же данные; после logout — 401. Повторить с отдельным коротким TTL для проверки expiry.
4. Для 4: показать роль Redis/Valkey, план SQL и ошибку зависимости. Для 5: выполнить выбранный эксперимент.
4. Для 4: показать роль Redis, план SQL и ошибку зависимости. Для 5: выполнить выбранный эксперимент.
## Что должно быть в PR
@@ -100,6 +100,5 @@ Smoke не выставляет оценку автоматически. Про
- [PostgreSQL transactions](https://www.postgresql.org/docs/current/tutorial-transactions.html)
- [PostgreSQL EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html)
- [Valkey persistence](https://valkey.io/topics/persistence/)
- [Redis persistence](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/)
- [Basic authentication](https://www.rfc-editor.org/info/rfc7617/)
+42 -24
View File
@@ -1,37 +1,55 @@
# Отчёт — лабораторная 2
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
```sh
cp .env.example .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build
curl http://localhost:8080/health/ready
make test
make test-grade4
```
Для повторной проверки сохранности:
```sh
chmod +x scripts/restart.sh
make test-persistence ACTION_SCRIPT=scripts/restart.sh
```
Для остановки без удаления данных:
```sh
docker compose --env-file .env down
```
Намеренное удаление учебных данных выполняется отдельно и осознанно командой `docker compose down -v`.
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Spring Boot API работает от имени непривилегированного пользователя `10001`. PostgreSQL является источником истины для таблиц `users`, `chats`, `chat_members` и `messages`. Flyway применяет версионируемую миграцию `V1__messenger.sql` при старте. Создание чата и участников выполняется одной `@Transactional` операцией; уникальность `username` дополнительно гарантируется ограничением PostgreSQL.
Пароль при регистрации не возвращается и хранится как SCrypt-хеш. `POST /api/v1/auth/sessions` принимает только Basic `username:password`, создаёт случайный 256-битный opaque Bearer-токен и сохраняет его в Redis с TTL `SESSION_TTL_SECONDS`. Redis включён с AOF и named volume, поэтому действующие сессии переживают проверяемый рестарт. Logout удаляет ключ сессии. Бизнес-endpoint используют только Bearer; `X-User-Id` игнорируется.
История использует keyset-запрос по `(chat_id, created_at, id)` с индексом `idx_messages_chat_created_id`. Страница получает `limit + 1` строк, а cursor кодируется и подписывается HMAC. PostgreSQL ограничен пулом из 4 соединений; `socketTimeout` и `statement_timeout` ограничены 1 секундой, а серверный deadline DB-операции — 2 секундами. При недоступности PostgreSQL или Redis API возвращает ограниченную ошибку `503 unavailable`.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| Критерий | Команда/сценарий | Наблюдаемый результат | Доказательство |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
| Контракт и структура | `make check` | PASS |
| Публичный API | `make test BASE_URL=http://localhost:8080` | PASS: lab2 public API scenario |
| Сохранность | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS: data and existing session preserved |
| Basic/Bearer, logout, rollback, race | `make test-grade4` | PASS: собственный Python-тест |
| Истечение TTL | `SESSION_TTL_SECONDS=2 docker compose --env-file .env up -d --force-recreate api` + `make test-grade4-expiry` | PASS: expired session returns 401 | `student-tests/lab2.py` |
| Недоступность Redis | `make test-grade4-redis` | PASS: API returns 503 | `student-tests/lab2.py` |
| Недоступность PostgreSQL | `make test-grade4-postgres` | PASS: API returns 503 | `student-tests/lab2.py` |
| PostgreSQL history index | `EXPLAIN (ANALYZE, BUFFERS)` для запроса истории на 10 000 синтетических сообщениях | `Index Scan using idx_messages_chat_created_id`, 50 строк за 0.084 ms | `evidence/index-explain.txt` |
| Непривилегированный контейнер | `docker compose ps`, `docker exec ... id -u` | UID 10001 | `Dockerfile` |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
## Собственные проверки
## Эксперименты и отказы
`student-tests/lab2.py` проверяет неверный пароль и Basic challenge, запрет Basic на бизнес-запросах, игнорирование `X-User-Id`, rollback неудачного создания чата, гонку десяти регистраций одинакового username, logout, короткий TTL и ответы `503` при остановке Redis или PostgreSQL.
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
## Ограничения
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Это учебный локальный стенд с синтетическими данными. TLS, балансировщик и несколько API-реплик относятся к следующим лабораторным. Redis используется только для сессий; PostgreSQL остаётся источником истины предметных данных. `make load` показывает closed-loop HTTP-метрики и не является полноценным capacity benchmark.
+33
View File
@@ -0,0 +1,33 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.16'
}
group = 'ru.mtusi'
version = '2.0.0'
description = 'Lab 2 persistent messenger'
java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }
repositories { mavenCentral() }
dependencies {
implementation platform('org.springframework.boot:spring-boot-dependencies:3.5.16')
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.flywaydb:flyway-core'
implementation 'org.flywaydb:flyway-database-postgresql'
implementation 'org.postgresql:postgresql'
implementation 'org.springframework.security:spring-security-crypto'
implementation 'org.bouncycastle:bcprov-jdk18on:1.80'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
dependencyLocking { lockAllConfigurations(); lockMode = LockMode.STRICT }
tasks.withType(JavaCompile).configureEach { options.release = 21; options.encoding = 'UTF-8'; options.compilerArgs.add('-parameters') }
tasks.withType(AbstractArchiveTask).configureEach { preserveFileTimestamps = false; reproducibleFileOrder = true }
tasks.named('bootJar') { archiveFileName = 'messenger.jar' }
tasks.named('jar') { enabled = false }
tasks.named('test') { useJUnitPlatform(); maxHeapSize = '256m'; testLogging { events 'passed','skipped','failed'; exceptionFormat = 'full' } }
tasks.register('resolveDependencies') { doLast { configurations.findAll { it.canBeResolved }.each { it.resolve() } } }
+57
View File
@@ -0,0 +1,57 @@
services:
api:
build: .
image: mtusi-messenger:lab2
ports:
- "127.0.0.1:${APP_PORT:-8080}:8080"
environment:
APP_HOST: 0.0.0.0
APP_PORT: 8080
DB_HOST: postgres
DB_PORT: 5432
DB_NAME: ${POSTGRES_DB:-messenger}
DB_USERNAME: ${POSTGRES_USER:-messenger}
DB_PASSWORD: ${POSTGRES_PASSWORD:-messenger-dev-only}
REDIS_HOST: redis
REDIS_PORT: 6379
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "java", "-cp", "/app/healthcheck", "Healthcheck"]
interval: 5s
timeout: 3s
start_period: 30s
retries: 3
postgres:
image: postgres:16.4-alpine
environment:
POSTGRES_DB: ${POSTGRES_DB:-messenger}
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger-dev-only}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 5s
timeout: 3s
retries: 10
redis:
image: redis:7.4.2-alpine
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 10
volumes:
postgres_data:
redis_data:
+20
View File
@@ -0,0 +1,20 @@
import java.net.HttpURLConnection;
import java.net.URI;
/** Compiled in the build stage; works in a JRE without curl, shell parsing or extra packages. */
public class Healthcheck {
public static void main(String[] args) {
try {
String port = System.getenv().getOrDefault("APP_PORT", "8080");
HttpURLConnection connection = (HttpURLConnection) URI.create(
"http://127.0.0.1:" + port + "/health/ready").toURL().openConnection();
connection.setConnectTimeout(1000);
connection.setReadTimeout(1000);
int status = connection.getResponseCode();
connection.disconnect();
System.exit(status == 200 ? 0 : 1);
} catch (Exception exception) {
System.exit(1);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
SET
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.29..32.47 rows=50 width=78) (actual time=0.033..0.039 rows=50 loops=1)
Buffers: shared hit=3
-> Index Scan using idx_messages_chat_created_id on messages (cost=0.29..261.01 rows=405 width=78) (actual time=0.032..0.035 rows=50 loops=1)
Index Cond: ((chat_id = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 02:40:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
Buffers: shared hit=3
Planning:
Buffers: shared hit=106
Planning Time: 0.432 ms
Execution Time: 0.084 ms
(9 rows)
+98
View File
@@ -0,0 +1,98 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
ch.qos.logback:logback-classic:1.5.34=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.5.34=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-core:2.21.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-databind:2.21.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.dataformat:jackson-dataformat-toml:2.21.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.21.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.module:jackson-module-parameter-names:2.21.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson:jackson-bom:2.21.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.jayway.jsonpath:json-path:2.9.0=testCompileClasspath,testRuntimeClasspath
com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath
com.zaxxer:HikariCP:6.3.3=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.lettuce:lettuce-core:6.6.0.RELEASE=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-commons:1.15.12=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.15.12=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.netty:netty-buffer:4.1.135.Final=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.netty:netty-codec:4.1.135.Final=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.netty:netty-common:4.1.135.Final=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.netty:netty-handler:4.1.135.Final=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.netty:netty-resolver:4.1.135.Final=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.netty:netty-transport-native-unix-common:4.1.135.Final=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.netty:netty-transport:4.1.135.Final=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.projectreactor:reactor-core:3.7.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:2.1.1=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.18.3=testCompileClasspath,testRuntimeClasspath
net.minidev:accessors-smart:2.5.2=testCompileClasspath,testRuntimeClasspath
net.minidev:json-smart:2.5.2=testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-api:2.24.3=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-to-slf4j:2.24.3=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-core:10.1.55=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-el:10.1.55=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-websocket:10.1.55=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.awaitility:awaitility:4.2.2=testCompileClasspath,testRuntimeClasspath
org.bouncycastle:bcprov-jdk18on:1.80=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.flywaydb:flyway-core:11.7.2=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.flywaydb:flyway-database-postgresql:11.7.2=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:5.12.2=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:5.12.2=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:5.12.2=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:5.12.2=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:1.12.2=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:1.12.2=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:1.12.2=testRuntimeClasspath
org.junit:junit-bom:5.12.2=testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-core:5.17.0=testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-junit-jupiter:5.17.0=testCompileClasspath,testRuntimeClasspath
org.objenesis:objenesis:3.3=testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath
org.postgresql:postgresql:42.7.11=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.reactivestreams:reactive-streams:1.0.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:2.0.18=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-autoconfigure:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-dependencies:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-data-redis:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jdbc:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-json:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-logging:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-test:3.5.16=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-web:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test-autoconfigure:3.5.16=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test:3.5.16=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot:3.5.16=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.data:spring-data-commons:3.5.13=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.data:spring-data-keyvalue:3.5.13=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.data:spring-data-redis:3.5.13=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.security:spring-security-crypto:6.5.11=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aop:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context-support:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-jcl:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-jdbc:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-oxm:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-test:6.2.19=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-tx:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-web:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-webmvc:6.2.19=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath
org.yaml:snakeyaml:2.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
redis.clients.authentication:redis-authx-core:0.1.1-beta2=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
empty=annotationProcessor,developmentOnly,testAndDevelopmentOnly,testAnnotationProcessor
+2
View File
@@ -0,0 +1,2 @@
org.gradle.jvmargs=-Xmx512m -Dfile.encoding=UTF-8
org.gradle.workers.max=2
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip
distributionSha256Sum=f1771298a70f6db5a29daf62378c4e18a17fc33c9ba6b14362e0cdf40610380d
networkTimeout=60000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
# Restart every stateful service without deleting named volumes.
docker compose --env-file .env restart api postgres redis
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'messenger'
@@ -0,0 +1,72 @@
package ru.mtusi.messenger;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.dao.DataAccessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import static ru.mtusi.messenger.Models.*;
@RestControllerAdvice
public class ApiErrors {
private static final Logger LOG = LoggerFactory.getLogger(ApiErrors.class);
@ExceptionHandler(ApiException.class)
ResponseEntity<ErrorBody> application(ApiException error, HttpServletRequest request) {
return response(error.status(), error.code(), error.getMessage(), request);
}
@ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentTypeMismatchException.class})
ResponseEntity<ErrorBody> invalid(Exception error, HttpServletRequest request) {
return response(400, "invalid_request", "Некорректный JSON или параметры запроса", request);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
ResponseEntity<ErrorBody> media(Exception error, HttpServletRequest request) {
return response(415, "unsupported_media_type", "Ожидается Content-Type: application/json", request);
}
@ExceptionHandler(DataAccessException.class)
ResponseEntity<ErrorBody> database(DataAccessException error, HttpServletRequest request) {
LOG.error("request_id={} error_type={}", request.getAttribute(RequestFilter.REQUEST_ID), error.getClass().getSimpleName());
return response(503, "unavailable", "Хранилище данных недоступно", request);
}
@ExceptionHandler({NoResourceFoundException.class, HttpRequestMethodNotSupportedException.class})
ResponseEntity<ErrorBody> missing(Exception error, HttpServletRequest request) {
return response(404, "not_found", "Объект не найден", request);
}
@ExceptionHandler(Exception.class)
ResponseEntity<ErrorBody> unexpected(Exception error, HttpServletRequest request) {
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
if (cause instanceof DataAccessException) {
LOG.error("request_id={} error_type={}", request.getAttribute(RequestFilter.REQUEST_ID), cause.getClass().getSimpleName());
return response(503, "unavailable", "Хранилище данных недоступно", request);
}
}
LOG.error("request_id={} error_type={}", request.getAttribute(RequestFilter.REQUEST_ID),
error.getClass().getSimpleName());
return response(500, "internal_error", "Внутренняя ошибка сервера", request);
}
private ResponseEntity<ErrorBody> response(int status, String code, String message, HttpServletRequest request) {
String id = (String) request.getAttribute(RequestFilter.REQUEST_ID);
ResponseEntity.BodyBuilder builder = ResponseEntity.status(status);
if (status == 401) {
String challenge = request.getRequestURI().equals("/api/v1/auth/sessions")
? "Basic realm=\"messenger\", charset=\"UTF-8\""
: "Bearer realm=\"messenger\"";
builder.header(HttpHeaders.WWW_AUTHENTICATE, challenge);
}
return builder.body(new ErrorBody(new ErrorDetail(code, message, id)));
}
}
@@ -0,0 +1,24 @@
package ru.mtusi.messenger;
public class ApiException extends RuntimeException {
private final int status;
private final String code;
public ApiException(int status, String code, String message) {
super(message);
this.status = status;
this.code = code;
}
public int status() { return status; }
public String code() { return code; }
public static ApiException invalid(String message) {
return new ApiException(400, "invalid_request", message);
}
public static ApiException unauthorized() {
return new ApiException(401, "unauthorized", "Требуется действующая Bearer-сессия");
}
public static ApiException notFound() {
return new ApiException(404, "not_found", "Объект не найден");
}
}
@@ -0,0 +1,54 @@
package ru.mtusi.messenger;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;
@Component
public class CursorCodec {
private final byte[] secret = new byte[32];
private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding();
private static final Base64.Decoder DECODER = Base64.getUrlDecoder();
public CursorCodec() { new SecureRandom().nextBytes(secret); }
public record Position(Instant createdAt, UUID id) {}
public String encode(String scope, Position position) {
String payload = scope + "|" + position.createdAt() + "|" + position.id();
String encoded = ENCODER.encodeToString(payload.getBytes(StandardCharsets.UTF_8));
return encoded + "." + ENCODER.encodeToString(sign(encoded));
}
public Position decode(String cursor, String scope) {
if (cursor == null) return null;
try {
if (cursor.length() > 1024) throw new IllegalArgumentException();
String[] parts = cursor.split("\\.", -1);
if (parts.length != 2 || !MessageDigest.isEqual(sign(parts[0]), DECODER.decode(parts[1]))) {
throw new IllegalArgumentException();
}
String[] fields = new String(DECODER.decode(parts[0]), StandardCharsets.UTF_8).split("\\|", -1);
if (fields.length != 3 || !scope.equals(fields[0])) throw new IllegalArgumentException();
return new Position(Instant.parse(fields[1]), Input.uuid(fields[2]));
} catch (RuntimeException exception) {
throw ApiException.invalid("Некорректный cursor или cursor от другого ресурса");
}
}
private byte[] sign(String payload) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
return mac.doFinal(payload.getBytes(StandardCharsets.UTF_8));
} catch (java.security.GeneralSecurityException exception) {
throw new IllegalStateException("HMAC is unavailable", exception);
}
}
}
@@ -0,0 +1,37 @@
package ru.mtusi.messenger;
import org.springframework.boot.availability.ApplicationAvailability;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class HealthController {
private final ApplicationAvailability availability;
private final JdbcTemplate jdbc;
private final SessionService sessions;
public HealthController(ApplicationAvailability availability, JdbcTemplate jdbc, SessionService sessions) {
this.availability = availability; this.jdbc = jdbc; this.sessions = sessions;
}
@GetMapping("/health/live")
Map<String, String> live() { return Map.of("status", "ok"); }
@GetMapping("/health/ready")
Map<String, String> ready() {
if (availability.getReadinessState() != ReadinessState.ACCEPTING_TRAFFIC) throw unavailable();
try {
jdbc.queryForObject("SELECT 1", Integer.class);
sessions.check();
return Map.of("status", "ok");
} catch (RuntimeException exception) {
throw unavailable();
}
}
private ApiException unavailable() { return new ApiException(503, "unavailable", "Зависимость недоступна"); }
}
@@ -0,0 +1,82 @@
package ru.mtusi.messenger;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
final class Input {
private Input() {}
static void fields(JsonNode body, String... allowed) {
Set<String> names = Set.of(allowed);
if (body == null || !body.isObject() || body.size() != names.size()) {
throw ApiException.invalid("Неверный набор полей JSON");
}
body.fieldNames().forEachRemaining(name -> {
if (!names.contains(name)) throw ApiException.invalid("Неизвестное поле JSON");
});
}
static String text(JsonNode body, String field, int max) {
JsonNode node = body.get(field);
if (node == null || !node.isTextual()) throw ApiException.invalid("Поле должно быть строкой: " + field);
String value = node.textValue();
if (value.codePointCount(0, value.length()) > max || value.codePoints().allMatch(Input::isUnicodeWhitespace)) {
throw ApiException.invalid("Недопустимая длина или пустая строка: " + field);
}
return value;
}
static String password(JsonNode body) {
JsonNode node = body.get("password");
if (node == null || !node.isTextual()) throw ApiException.invalid("Пароль должен быть строкой");
String value = node.textValue();
int length = value.codePointCount(0, value.length());
if (length < 12 || length > 128 || value.codePoints().allMatch(Input::isUnicodeWhitespace)) {
throw ApiException.invalid("Пароль должен содержать от 12 до 128 непробельных символов");
}
return value;
}
private static boolean isUnicodeWhitespace(int codePoint) {
return codePoint == 0x0085
|| Character.isWhitespace(codePoint)
|| Character.isSpaceChar(codePoint);
}
static UUID uuid(String value) {
if (value == null || !value.matches("(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) {
throw ApiException.invalid("Некорректный UUID");
}
return UUID.fromString(value);
}
static List<UUID> members(JsonNode body) {
JsonNode array = body.get("member_ids");
if (array == null || !array.isArray() || array.isEmpty() || array.size() > 100) {
throw ApiException.invalid("member_ids должен содержать от 1 до 100 участников");
}
List<UUID> ids = new ArrayList<>();
for (JsonNode item : array) {
if (!item.isTextual()) throw ApiException.invalid("Участник должен быть UUID-строкой");
ids.add(uuid(item.textValue()));
}
if (new HashSet<>(ids).size() != ids.size()) throw ApiException.invalid("Участники повторяются");
return ids;
}
static int limit(String value) {
if (value == null) return 50;
try {
if (!value.matches("[0-9]{1,3}")) throw new NumberFormatException();
int limit = Integer.parseInt(value);
if (limit < 1 || limit > 100) throw new NumberFormatException();
return limit;
} catch (NumberFormatException exception) {
throw ApiException.invalid("limit должен быть целым числом от 1 до 100");
}
}
}
@@ -0,0 +1,11 @@
package ru.mtusi.messenger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MessengerApplication {
public static void main(String[] args) {
SpringApplication.run(MessengerApplication.class, args);
}
}
@@ -0,0 +1,94 @@
package ru.mtusi.messenger;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
import static ru.mtusi.messenger.Models.*;
@RestController
@RequestMapping("/api/v1")
public class MessengerController {
private final MessengerStore store;
private final SessionService sessions;
public MessengerController(MessengerStore store, SessionService sessions) { this.store = store; this.sessions = sessions; }
@PostMapping(value = "/users", consumes = "application/json")
@ResponseStatus(HttpStatus.CREATED)
User register(@RequestBody JsonNode body) {
Input.fields(body, "username", "display_name", "password");
String username = Input.text(body, "username", 32);
if (!username.matches("[a-z0-9_]{3,32}")) throw ApiException.invalid("Некорректный username");
return store.createUser(username, Input.text(body, "display_name", 100), sessions.hash(Input.password(body)));
}
@PostMapping(value = "/auth/sessions", consumes = "*/*")
@ResponseStatus(HttpStatus.CREATED)
Session login(HttpServletRequest request) throws java.io.IOException {
if (request.getInputStream().read() != -1) {
throw ApiException.invalid("Вход не принимает тело запроса");
}
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Basic ")) throw ApiException.unauthorized();
try {
String decoded = new String(Base64.getDecoder().decode(header.substring(6)), StandardCharsets.UTF_8);
int colon = decoded.indexOf(':');
if (colon <= 0) throw new IllegalArgumentException();
String username = decoded.substring(0, colon);
String password = decoded.substring(colon + 1);
if (!username.matches("[a-z0-9_]{3,32}") || password.codePointCount(0, password.length()) < 12
|| password.codePointCount(0, password.length()) > 128) throw new IllegalArgumentException();
return sessions.login(username, password);
} catch (IllegalArgumentException exception) {
throw ApiException.unauthorized();
}
}
@DeleteMapping("/auth/sessions/current")
@ResponseStatus(HttpStatus.NO_CONTENT)
void logout(@RequestAttribute(RequestFilter.TOKEN) String token) { sessions.revoke(token); }
@GetMapping("/users/me")
User me(@RequestAttribute(RequestFilter.ACTOR) User actor) { return actor; }
@PostMapping(value = "/chats", consumes = "application/json")
@ResponseStatus(HttpStatus.CREATED)
Chat createChat(@RequestAttribute(RequestFilter.ACTOR) User actor, @RequestBody JsonNode body) {
Input.fields(body, "title", "member_ids");
return store.createChat(actor.id(), Input.text(body, "title", 100), Input.members(body));
}
@GetMapping("/chats")
Page<Chat> chats(@RequestAttribute(RequestFilter.ACTOR) User actor,
@RequestParam(required = false) String limit, @RequestParam(required = false) String cursor) {
return store.chats(actor.id(), Input.limit(limit), cursor);
}
@GetMapping("/chats/{chatId}")
Chat chat(@RequestAttribute(RequestFilter.ACTOR) User actor, @PathVariable String chatId) {
return store.chat(actor.id(), Input.uuid(chatId));
}
@PostMapping(value = "/chats/{chatId}/messages", consumes = "application/json")
@ResponseStatus(HttpStatus.CREATED)
Message send(@RequestAttribute(RequestFilter.ACTOR) User actor, @PathVariable String chatId,
@RequestBody JsonNode body) {
UUID id = Input.uuid(chatId);
store.chat(actor.id(), id);
Input.fields(body, "text");
return store.send(actor.id(), id, Input.text(body, "text", 4000));
}
@GetMapping("/chats/{chatId}/messages")
Page<Message> history(@RequestAttribute(RequestFilter.ACTOR) User actor, @PathVariable String chatId,
@RequestParam(required = false) String limit, @RequestParam(required = false) String cursor) {
UUID id = Input.uuid(chatId);
return store.history(actor.id(), id, Input.limit(limit), cursor);
}
}
@@ -0,0 +1,140 @@
package ru.mtusi.messenger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static ru.mtusi.messenger.Models.*;
@Service
public class MessengerStore {
private final JdbcTemplate jdbc;
private final CursorCodec cursors;
public MessengerStore(JdbcTemplate jdbc, CursorCodec cursors) { this.jdbc = jdbc; this.cursors = cursors; }
@Transactional
public User createUser(String username, String displayName, String passwordHash) {
UUID id = UUID.randomUUID();
Instant created = Instant.now();
try {
jdbc.update("INSERT INTO users(id, username, display_name, password_hash, created_at) VALUES (?, ?, ?, ?, ?)",
id, username, displayName, passwordHash, Timestamp.from(created));
} catch (DuplicateKeyException exception) {
throw new ApiException(409, "conflict", "username уже занят");
}
return findUser(id);
}
public Credentials credentials(String username) {
try {
return jdbc.queryForObject("SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = ?",
(rs, row) -> new Credentials(new User(rs.getObject("id", UUID.class), rs.getString("username"),
rs.getString("display_name"), rs.getTimestamp("created_at").toInstant()),
rs.getString("password_hash")), username);
} catch (EmptyResultDataAccessException exception) { return null; }
}
public User findUser(UUID id) {
try {
return jdbc.queryForObject("SELECT id, username, display_name, created_at FROM users WHERE id = ?",
(rs, row) -> user(rs), id);
} catch (EmptyResultDataAccessException exception) { return null; }
}
@Transactional
public Chat createChat(UUID actor, String title, List<UUID> memberIds) {
if (!memberIds.contains(actor)) throw ApiException.invalid("Участники должны существовать и включать создателя");
for (UUID member : memberIds) {
if (findUser(member) == null) throw ApiException.invalid("Участники должны существовать и включать создателя");
}
UUID id = UUID.randomUUID();
Instant created = Instant.now();
jdbc.update("INSERT INTO chats(id, title, created_at) VALUES (?, ?, ?)", id, title, Timestamp.from(created));
for (UUID member : memberIds) jdbc.update("INSERT INTO chat_members(chat_id, user_id) VALUES (?, ?)", id, member);
return chat(actor, id);
}
public Chat chat(UUID actor, UUID id) {
try {
Chat chat = jdbc.queryForObject("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=?",
(rs, row) -> new Chat(rs.getObject("id", UUID.class), rs.getString("title"),
loadMembers(rs.getObject("id", UUID.class)), rs.getTimestamp("created_at").toInstant()), id, actor);
if (chat == null) throw ApiException.notFound();
return chat;
} catch (EmptyResultDataAccessException exception) { throw ApiException.notFound(); }
}
@Transactional
public Message send(UUID actor, UUID chatId, String text) {
chat(actor, chatId);
UUID id = UUID.randomUUID();
Instant created = Instant.now();
jdbc.update("INSERT INTO messages(id, chat_id, sender_id, text, created_at) VALUES (?, ?, ?, ?, ?)",
id, chatId, actor, text, Timestamp.from(created));
return findMessage(id);
}
public Page<Chat> chats(UUID actor, int limit, String cursor) {
CursorCodec.Position after = cursors.decode(cursor, "chats:" + actor);
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=?";
List<Object> args = new ArrayList<>(List.of(actor));
if (after != null) { sql += " AND (c.created_at, c.id) > (?, ?)"; args.add(Timestamp.from(after.createdAt())); args.add(after.id()); }
sql += " ORDER BY c.created_at, c.id LIMIT ?";
args.add(limit + 1);
List<Chat> rows = jdbc.query(sql, (rs, row) -> {
UUID id = rs.getObject("id", UUID.class);
return new Chat(id, rs.getString("title"), loadMembers(id), rs.getTimestamp("created_at").toInstant());
}, args.toArray());
return page(rows, limit, "chats:" + actor, c -> new CursorCodec.Position(c.createdAt(), c.id()));
}
public Page<Message> history(UUID actor, UUID chatId, int limit, String cursor) {
chat(actor, chatId);
CursorCodec.Position after = cursors.decode(cursor, "messages:" + chatId);
String sql = "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id=?";
List<Object> args = new ArrayList<>(List.of(chatId));
if (after != null) { sql += " AND (created_at, id) > (?, ?)"; args.add(Timestamp.from(after.createdAt())); args.add(after.id()); }
sql += " ORDER BY created_at, id LIMIT ?";
args.add(limit + 1);
List<Message> rows = jdbc.query(sql, (rs, row) -> new Message(rs.getObject("id", UUID.class),
rs.getObject("chat_id", UUID.class), rs.getObject("sender_id", UUID.class), rs.getString("text"),
rs.getTimestamp("created_at").toInstant()), args.toArray());
return page(rows, limit, "messages:" + chatId, m -> new CursorCodec.Position(m.createdAt(), m.id()));
}
private List<UUID> loadMembers(UUID chatId) {
return jdbc.query("SELECT user_id FROM chat_members WHERE chat_id=? ORDER BY user_id",
(rs, row) -> rs.getObject("user_id", UUID.class), chatId);
}
private Message findMessage(UUID id) {
try {
return jdbc.queryForObject("SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE id=?",
(rs, row) -> new Message(rs.getObject("id", UUID.class), rs.getObject("chat_id", UUID.class),
rs.getObject("sender_id", UUID.class), rs.getString("text"), rs.getTimestamp("created_at").toInstant()), id);
} catch (EmptyResultDataAccessException exception) {
throw new ApiException(500, "internal_error", "Созданное сообщение не найдено");
}
}
private User user(java.sql.ResultSet rs) throws java.sql.SQLException {
return new User(rs.getObject("id", UUID.class), rs.getString("username"), rs.getString("display_name"),
rs.getTimestamp("created_at").toInstant());
}
private <T> Page<T> page(List<T> rows, int limit, String scope, java.util.function.Function<T, CursorCodec.Position> position) {
boolean more = rows.size() > limit;
List<T> result = more ? rows.subList(0, limit) : rows;
String next = more ? cursors.encode(scope, position.apply(result.getLast())) : null;
return new Page<>(result, next);
}
}
@@ -0,0 +1,22 @@
package ru.mtusi.messenger;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public final class Models {
private Models() {}
public record User(UUID id, String username, String displayName, Instant createdAt) {}
public record Chat(UUID id, String title, List<UUID> memberIds, Instant createdAt) {
public Chat { memberIds = List.copyOf(memberIds); }
}
public record Message(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) {}
public record Credentials(User user, String passwordHash) {}
public record Session(String token, String tokenType, Instant expiresAt, User user) {}
public record Page<T>(List<T> items, String nextCursor) {
public Page { items = List.copyOf(items); }
}
public record ErrorBody(ErrorDetail error) {}
public record ErrorDetail(String code, String message, String requestId) {}
}
@@ -0,0 +1,95 @@
package ru.mtusi.messenger;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerMapping;
import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;
import org.springframework.dao.DataAccessException;
import static ru.mtusi.messenger.Models.*;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter extends OncePerRequestFilter {
public static final String ACTOR = "messenger.actor";
public static final String REQUEST_ID = "messenger.requestId";
public static final String TOKEN = "messenger.token";
private static final Logger LOG = LoggerFactory.getLogger(RequestFilter.class);
private final SessionService sessions;
private final ObjectMapper mapper;
public RequestFilter(SessionService sessions, ObjectMapper mapper) {
this.sessions = sessions;
this.mapper = mapper;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String requestId = UUID.randomUUID().toString();
request.setAttribute(REQUEST_ID, requestId);
response.setHeader("X-Request-Id", requestId);
long start = System.nanoTime();
try {
String path = request.getRequestURI();
boolean publicEndpoint = (path.equals("/api/v1/users") && request.getMethod().equals("POST"))
|| (path.equals("/api/v1/auth/sessions") && request.getMethod().equals("POST"));
if (path.startsWith("/api/v1/") && !publicEndpoint) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) throw ApiException.unauthorized();
String token = header.substring("Bearer ".length()).trim();
request.setAttribute(TOKEN, token);
request.setAttribute(ACTOR, sessions.authenticate(token));
}
chain.doFilter(request, response);
} catch (ApiException exception) {
writeError(response, exception.status(), exception.code(), exception.getMessage(), requestId, request);
} catch (Exception exception) {
if (unavailable(exception)) {
writeError(response, 503, "unavailable", "Хранилище данных недоступно", requestId, request);
} else if (exception instanceof ServletException servlet) {
throw servlet;
} else if (exception instanceof IOException io) {
throw io;
} else {
throw new ServletException(exception);
}
} finally {
Object route = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
LOG.info("request_id={} method={} route={} status={} duration_ms={}", requestId,
request.getMethod(), route == null ? "unmapped" : route, response.getStatus(),
(System.nanoTime() - start) / 1_000_000);
}
}
private void writeError(HttpServletResponse response, int status, String code, String message,
String requestId, HttpServletRequest request) throws IOException {
response.setStatus(status);
if (status == 401) {
String challenge = request.getRequestURI().equals("/api/v1/auth/sessions")
? "Basic realm=\"messenger\", charset=\"UTF-8\""
: "Bearer realm=\"messenger\"";
response.setHeader("WWW-Authenticate", challenge);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
mapper.writeValue(response.getOutputStream(), new ErrorBody(new ErrorDetail(code, message, requestId)));
}
private boolean unavailable(Throwable error) {
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
if (cause instanceof DataAccessException || cause instanceof SQLException) return true;
}
return false;
}
}
@@ -0,0 +1,102 @@
package ru.mtusi.messenger;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static ru.mtusi.messenger.Models.*;
@Service
public class SessionService {
private static final Base64.Encoder TOKEN_ENCODER = Base64.getUrlEncoder().withoutPadding();
private final MessengerStore store;
private final StringRedisTemplate redis;
private final SCryptPasswordEncoder passwords = SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8();
private final SecureRandom random = new SecureRandom();
private final long ttlSeconds;
private final long databaseTimeoutMillis;
private final ExecutorService databaseExecutor = Executors.newFixedThreadPool(4);
public SessionService(MessengerStore store, StringRedisTemplate redis,
@Value("${SESSION_TTL_SECONDS:3600}") long ttlSeconds,
@Value("${DB_REQUEST_TIMEOUT_MS:2000}") long databaseTimeoutMillis) {
this.store = store;
this.redis = redis;
this.ttlSeconds = Math.max(2, ttlSeconds);
this.databaseTimeoutMillis = Math.max(250, databaseTimeoutMillis);
}
public String hash(String password) { return passwords.encode(password); }
public Session login(String username, String password) {
Credentials credentials = database(() -> store.credentials(username));
if (credentials == null || !passwords.matches(password, credentials.passwordHash())) throw ApiException.unauthorized();
byte[] bytes = new byte[32];
random.nextBytes(bytes);
String token = TOKEN_ENCODER.encodeToString(bytes);
Instant expires = Instant.now().plusSeconds(ttlSeconds);
try {
redis.opsForValue().set(key(token), credentials.user().id().toString(), Duration.ofSeconds(ttlSeconds));
} catch (RuntimeException exception) {
throw new ApiException(503, "unavailable", "Сервис сессий недоступен");
}
return new Session(token, "Bearer", expires, credentials.user());
}
public User authenticate(String token) {
if (token == null || token.isBlank()) throw ApiException.unauthorized();
String value;
try { value = redis.opsForValue().get(key(token)); }
catch (RuntimeException exception) { throw new ApiException(503, "unavailable", "Сервис сессий недоступен"); }
if (value == null) throw ApiException.unauthorized();
User user = database(() -> store.findUser(UUID.fromString(value)));
if (user == null) throw ApiException.unauthorized();
return user;
}
public void revoke(String token) {
if (token == null) throw ApiException.unauthorized();
try { redis.delete(key(token)); }
catch (RuntimeException exception) { throw new ApiException(503, "unavailable", "Сервис сессий недоступен"); }
}
public void check() { redis.opsForValue().get("messenger:readiness"); }
private String key(String token) { return "messenger:session:" + token; }
private <T> T database(java.util.concurrent.Callable<T> operation) {
Future<T> future = databaseExecutor.submit(operation);
try {
return future.get(databaseTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (TimeoutException exception) {
future.cancel(true);
throw new ApiException(503, "unavailable", "Хранилище данных недоступно");
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new ApiException(503, "unavailable", "Хранилище данных недоступно");
} catch (ExecutionException exception) {
Throwable cause = exception.getCause();
if (cause instanceof RuntimeException runtime) throw runtime;
throw new IllegalStateException(cause);
}
}
@PreDestroy
void shutdownDatabaseExecutor() {
databaseExecutor.shutdownNow();
}
}
+32
View File
@@ -0,0 +1,32 @@
spring.application.name=messenger-lab2
server.address=${APP_HOST:0.0.0.0}
server.port=${APP_PORT:8080}
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=5s
spring.datasource.url=${DATABASE_URL:jdbc:postgresql://${DB_HOST:postgres}:${DB_PORT:5432}/${DB_NAME:messenger}?socketTimeout=1&options=-c%20statement_timeout%3D1000}
spring.datasource.username=${DB_USERNAME:messenger}
spring.datasource.password=${DB_PASSWORD:messenger}
spring.datasource.hikari.maximum-pool-size=${DB_POOL_SIZE:4}
spring.datasource.hikari.connection-timeout=${DB_CONNECTION_TIMEOUT_MS:1000}
spring.datasource.hikari.validation-timeout=250
spring.datasource.hikari.transaction-isolation=TRANSACTION_READ_COMMITTED
# Connection timeout only limits waiting for a free pool slot. These settings
# also bound an already running PostgreSQL statement and socket read.
spring.datasource.hikari.data-source-properties.[socketTimeout]=${DB_SOCKET_TIMEOUT_SECONDS:1}
spring.datasource.hikari.data-source-properties.[options]=-c statement_timeout=${DB_STATEMENT_TIMEOUT_MS:1000}
spring.jdbc.template.query-timeout=${DB_QUERY_TIMEOUT_SECONDS:1}s
spring.data.redis.host=${REDIS_HOST:redis}
spring.data.redis.port=${REDIS_PORT:6379}
spring.data.redis.timeout=${REDIS_TIMEOUT:2s}
spring.data.redis.connect-timeout=${REDIS_CONNECT_TIMEOUT:2s}
spring.flyway.enabled=true
spring.jackson.property-naming-strategy=SNAKE_CASE
spring.jackson.deserialization.fail-on-trailing-tokens=true
spring.jackson.parser.strict-duplicate-detection=true
server.error.include-message=never
server.error.include-stacktrace=never
spring.main.banner-mode=off
logging.level.root=INFO
@@ -0,0 +1,30 @@
CREATE TABLE users (
id UUID PRIMARY KEY,
username VARCHAR(32) NOT NULL UNIQUE,
display_name VARCHAR(100) NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE chats (
id UUID PRIMARY KEY,
title VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) 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
);
CREATE INDEX idx_messages_chat_created_id ON messages(chat_id, created_at, id);
CREATE INDEX idx_chat_members_user_chat ON chat_members(user_id, chat_id);
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Own lab2 checks: authentication, logout, atomic chat creation and registration race."""
import argparse
import base64
import sys
import subprocess
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check
def basic(username, password):
value = base64.b64encode((username + ":" + password).encode()).decode()
return {"Authorization": "Basic " + value}
def wait_ready(client):
for _ in range(40):
try:
client.call("GET", "/health/ready", schema="Health")
return
except Exception:
time.sleep(0.25)
raise AssertionError("dependencies did not become ready")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--check-expiry", action="store_true")
parser.add_argument("--check-redis", action="store_true")
parser.add_argument("--check-postgres", action="store_true")
args = parser.parse_args()
c = Client(args.base_url)
alice = c.user("grade4_alice")
bob = c.user("grade4_bob")
# Basic is only for login; business endpoints require the returned Bearer token.
c.call("POST", "/api/v1/users", 400, body={
"username": "spaces_" + uuid.uuid4().hex[:16],
"display_name": "Whitespace",
"password": "\u0085" * 12,
})
c.call("POST", "/api/v1/auth/sessions", 400,
headers={**basic(alice["registration"]["username"], alice["registration"]["password"]),
"Content-Type": "application/json"}, raw=b"{}")
wrong = c.call("POST", "/api/v1/auth/sessions", 401,
headers=basic(alice["registration"]["username"], "wrong-password-123"))
check(wrong["headers"].get("WWW-Authenticate", "").startswith("Basic"),
"wrong password must challenge with Basic")
c.call("GET", "/api/v1/users/me", 401,
headers=basic(alice["registration"]["username"], alice["registration"]["password"]))
me = c.call("GET", "/api/v1/users/me", actor=alice,
headers={"X-User-Id": bob["id"]}, schema="User")["json"]
check(me["id"] == alice["id"], "X-User-Id changed Bearer identity")
if args.check_redis:
subprocess.run(["docker", "compose", "--env-file", ".env", "stop", "redis"], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
time.sleep(1)
c.call("GET", "/api/v1/users/me", 503, actor=bob)
finally:
subprocess.run(["docker", "compose", "--env-file", ".env", "start", "redis"], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wait_ready(c)
print("PASS: Redis outage returns 503")
if args.check_postgres:
subprocess.run(["docker", "compose", "--env-file", ".env", "stop", "postgres"], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
time.sleep(1)
c.call("GET", "/api/v1/users/me", 503, actor=bob)
finally:
subprocess.run(["docker", "compose", "--env-file", ".env", "start", "postgres"], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wait_ready(c)
print("PASS: PostgreSQL outage returns 503")
# Creating a chat with an unknown member must leave no half-created chat.
title = "rollback-check-" + uuid.uuid4().hex
c.call("POST", "/api/v1/chats", 400, actor=alice,
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
chats = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]["items"]
check(all(chat["title"] != title for chat in chats), "failed chat creation was not rolled back")
# Database UNIQUE(username) must decide a concurrent registration race.
username = "race_" + uuid.uuid4().hex[:20]
body = {"username": username, "display_name": "Race", "password": "race-password-123"}
def register_once():
return Client(args.base_url).call("POST", "/api/v1/users", [201, 409], body=body)["status"]
with ThreadPoolExecutor(max_workers=10) as pool:
statuses = list(pool.map(lambda _: register_once(), range(10)))
check(statuses.count(201) == 1 and statuses.count(409) == 9,
"concurrent username registration must produce one 201 and nine 409")
# Logout revokes the exact token; a second logout is unauthorized.
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
c.call("GET", "/api/v1/users/me", 401, actor=alice)
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=alice)
if args.check_expiry:
short = c.user("grade4_expiry")
time.sleep(3)
c.call("GET", "/api/v1/users/me", 401, actor=short)
print("PASS: expiry with short SESSION_TTL_SECONDS")
print("PASS: wrong password, Basic/Bearer separation, X-User-Id isolation, rollback, race and logout")
if __name__ == "__main__":
try:
main()
except Exception as error:
print("FAIL:", error)
raise SystemExit(1)