diff --git a/.dockerignore b/.dockerignore index bc16e556..796eb7ed 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,4 @@ __pycache__ node_modules evidence .DS_Store +!gradle-9.7.1-bin.zip \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..dfc97d67 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary +scripts/*.sh text eol=lf \ No newline at end of file diff --git a/.gitignore b/.gitignore index b5a71896..ccdf7fea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,109 @@ -# Local/private state +### Git ### +*.orig +*.BACKUP.* +*.BASE.* +*.LOCAL.* +*.REMOTE.* +*_BACKUP_*.txt +*_BASE_*.txt +*_LOCAL_*.txt +*_REMOTE_*.txt + +### Java ### +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt +.mtj.tmp/ + +# Package files +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# JVM crash logs +hs_err_pid* +replay_pid* + +### Gradle ### +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar + +### Maven ### +target/ +!.mvn/wrapper/maven-wrapper.jar +dependency-reduced-pom.xml + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr + +### Eclipse / STS ### +.apt_generated +.classpath +.factorypath +.project +.settings/ +.springBeans +.sts4-cache + +### VS Code ### +.vscode/ + +### Windows ### +Thumbs.db +ehthumbs.db +ehthumbs_vista.db +[Dd]esktop.ini +$RECYCLE.BIN/ +*.cab +*.msi +*.msix +*.msm +*.msp +*.lnk + +### macOS ### +.DS_Store +.AppleDouble +.LSOverride + +### Miscellaneous ### +*.sw? +.#* +*# +*~ +bin/ +/scratch +*.sublime-* + +### Environment / Secrets ### .env .env.* !.env.example secrets/ -certs/private/ -*.key -*.p12 -*.pfx -*.jks -*.pem -*.tfstate* -volumes/ -data/ -backups/ -# Runtime/build artifacts -.venv/ +secrets/*.txt +!secrets/.gitkeep + +### Python / venv ### __pycache__/ -*.py[cod] -node_modules/ -dist/ -build/ -target/ -bin/ -obj/ -coverage/ -*.log -.DS_Store -.idea/ -.vscode/ -# Keep small, sanitized evidence summaries in evidence/ under version control. -# Inspect git diff --cached: ignore rules are not a secret scanner. +*.pyc +.venv/ +.venv +venv/ + +### Lab evidence ### +evidence/**/*.dump +evidence/**/*.sql.gz +evidence/**/raw/ +evidence/**/*.raw \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..20085dbd --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM eclipse-temurin:21-jdk-jammy AS builder +WORKDIR /build +RUN apt-get update && apt-get install -y --no-install-recommends unzip \ + && rm -rf /var/lib/apt/lists/* +COPY gradle gradle +COPY gradlew settings.gradle build.gradle ./ +COPY gradle-9.7.1-bin.zip /tmp/gradle.zip +RUN unzip -q /tmp/gradle.zip -d /opt && rm /tmp/gradle.zip +ENV PATH="/opt/gradle-9.7.1/bin:$PATH" +RUN gradle dependencies --no-daemon +COPY contracts contracts +COPY src src +RUN gradle bootJar -x test --no-daemon + +FROM eclipse-temurin:21-jre-jammy AS runner +WORKDIR /app +RUN groupadd --system spring && useradd --system --gid spring --no-create-home spring +COPY --from=builder /build/build/libs/*.jar app.jar +RUN chown spring:spring app.jar +USER spring +EXPOSE 8080 +HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \ + CMD wget -qO- http://127.0.0.1:8080/actuator/health/readiness | grep -q UP || exit 1 +ENV JAVA_OPTS="-XX:MaxRAMPercentage=75 -Xss512k" +ENTRYPOINT ["sh", "-c", "exec java -Dfile.encoding=UTF-8 $JAVA_OPTS -jar app.jar"] \ No newline at end of file diff --git a/REPORT.md b/REPORT.md index e42f2b05..b8a2e4b1 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,189 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Иванов Данил, БВТ2301 +- Целевая оценка: 5, выбранный трек: Трек 2 «План запроса и восстановление» +- Commit/PR: c744ee5 https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/23 +- Использованные источники: документация Spring Boot 4, Spring Data Redis, Lettuce, PostgreSQL (EXPLAIN, pg_dump/pg_restore), Redis persistence. Помощь ИИ: Deep seek — консультации по миграции на Boot 4 (Jackson 3, flyway-starter, starter-aspectj), настройке Lettuce (нативный epoll), keyset-пагинации. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Prerequisites: Docker Desktop с запущенным engine (WSL2-бэкенд), Git, локальный `gradle-9.7.1-bin.zip` в корне проекта (для offline-сборки), Python 3.9+ для тестов. + +Запуск из чистого clone + +git clone url + +Secrets (Linux / macOS / Git Bash): +mkdir -p secrets +printf 'messenger' > secrets/postgres_db.txt +printf 'messenger' > secrets/postgres_user.txt +printf 'change-me-local-only' > secrets/postgres_password.txt + +Secrets (Windows PowerShell): +New-Item -ItemType Directory -Force secrets | Out-Null +[System.IO.File]::WriteAllText("$PWD\secrets\postgres_db.txt", "messenger") +[System.IO.File]::WriteAllText("$PWD\secrets\postgres_user.txt", "messenger") +[System.IO.File]::WriteAllText("$PWD\secrets\postgres_password.txt", "change-me-local-only") + +.env: +cp .env.example .env +Отредактировать .env: APP_ENV=lab, SESSION_TTL_SECONDS=400, SESSION_STORE=postgres + +Gradle offline: +curl -L --retry 5 --retry-delay 10 -o gradle-9.7.1-bin.zip https://services.gradle.org/distributions/gradle-9.7.1-bin.zip + +Python venv (Linux): +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements-dev.txt + +Python venv (Windows): +py -m venv .venv +.venv\Scripts\python.exe -m pip install -r requirements-dev.txt + +Сборка и запуск: +docker compose --env-file .env up -d --build +docker compose --env-file .env ps +curl.exe -s http://localhost:8080/health/ready + +Публичные проверки: +py scripts/check_contract.py +.venv\Scripts\python.exe scripts\validate_openapi.py +py tests/smoke.py --base-url http://localhost:8080 + +Persistence (Linux): +py tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://localhost:8080 + +Persistence (Windows): +py tests/resilience.py --mode persistence --action-script scripts\restart.bat --base-url http://localhost:8080 + +Остановка: +docker compose --env-file .env stop +docker compose --env-file .env down -v + +Трек 2 (опционально): +Get-Content scripts\seed_track2.sql | docker compose --env-file .env exec -T db psql -U messenger -d messenger +docker compose --env-file .env exec db psql -U messenger -d messenger -c "ANALYZE messages;" +docker compose --env-file .env exec db psql -U messenger -d messenger -c "SELECT count(*) FROM messages;" ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Схема процессов/хранилищ: +Клиент → API (Spring Boot 4, Java 21) → PostgreSQL 16. На уровне 4 добавлен Redis 7.4 как кэш активных сессий. Все три сервиса в одном `compose.yaml`, объединены сетью `messenger-net`, volumes — `pgdata` и `redisdata`. + +Источник истины: +PostgreSQL. Пользователи, чаты, участники, сообщения и сессии хранятся в нём. Redis — производное хранилище, кэш. При расхождении верим Postgres. При недоступности Redis приложение продолжает работать через Postgres. + +Транзакционные границы: +- `ChatService.createChat` — `@Transactional`: вставка в `chats` + N вставок в `chat_members`. При ошибке любого INSERT — откат целиком (проверено rollback-сценарием). +- `MessageService.createMessage` — `@Transactional`: ACL-проверка, COUNT лимита, INSERT messages. +- `SessionService.createSession` — `@Transactional`: INSERT sessions + запись в Redis-кэш. +- `requireActive`, `listChats`, `listMessages` — `@Transactional(readOnly = true)`. + +Ограничения: +- Кэш сессий в Redis не инвалидируется по TTL-истечении Postgres-записи — только по `expiresAt` при чтении. При жёстком рассинхроне максимум до `SESSION_TTL_SECONDS` может висеть «протухшая» копия. +- Keyset-пагинация в JPQL транслируется в OR-условие — индекс используется как диапазон только в native-варианте. +- Один узел Postgres, без репликации; RPO = время с последнего `pg_dump`. + +Перенесено из lab1: модель чатов и сообщений, CRUD-эндпоинты, структура DTO. + +Изменено в этой работе: состояние переехало в Postgres (вместо in-memory), добавлены Flyway-миграции, аутентификация переведена с `X-User-Id` на `Basic → Bearer` с opaque-токеном, пароли хешируются BCrypt, на уровне 4 добавлен Redis для кэша сессий, на уровне 5 — исследование плана запроса и восстановления. + +Соответствие `.env` → конфигурации: + +| `.env` | Куда попадает | Роль | +|-------------------------------|------------------------------|-------------------------------| +| `APP_ENV` | `SPRING_PROFILES_ACTIVE` | профиль Spring | +| `SESSION_TTL_SECONDS` | `app.session.ttl` | TTL сессии и кэша | +| `SESSION_STORE` | флаг выбора хранилища сессий | postgres / redis | +| `REDIS_COMMAND_TIMEOUT` | `app.redis.command-timeout` | таймаут команды Lettuce | +| `REDIS_CONNECT_TIMEOUT` | `app.redis.connect-timeout` | таймаут TCP-connect | +| `POSTGRES_*` (secrets) | `SPRING_DATASOURCE_*_FILE` | креды БД через Docker secrets | +| `SPRING_DATA_REDIS_HOST/PORT` | `spring.data.redis.*` | адрес Redis | + +Секреты БД передаются через Docker secrets (`/run/secrets/postgres_*`), не через `.env`; `.env` содержит только неконфиденциальные параметры. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +### Уровень 3 -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Критерий | Команда | Результат | Файл | +|-----------------------------|---------------------------------------------|---------------------|-------------------------------------------------------------| +| Публичный smoke | `py tests/smoke.py` | PASS | `evidence/lab2/level3-/03-smoke.log` | +| Persistence | `py tests/resilience.py --mode persistence` | PASS | `05-persistence.log` + `04/06-compose-ps` | +| Структура и контракт | `check_contract.py`, `validate_openapi.py` | PASS | `01-check.log`, `02-validate.log` | +| Секреты не в Git | `git check-ignore` | 4 пути игнорируются | `07-gitignore.txt` | +| Составная операция атомарна | `@Transactional` в `ChatService` | код в репо | `src/main/java/ru/mtusi/messenger/service/ChatService.java` | + +### Уровень 4 + +| Критерий | Команда | Результат | Файл | +|---------------------------------|------------------------------|-----------------------------------------------------------------|---------------------------------------------------------------| +| Redis с TTL, источник истины | `keys` + `ttl` | ключи `sessions::*`, TTL>0, value JSON `SessionRecord` | `01-redis-keys.txt`, `02-redis-ttl.txt`, `03-redis-value.txt` | +| Graceful degradation Redis | `stop redis` + smoke | PASS, `Cache GET failed` в логах, приложение читает из Postgres | `03-redis-down-smoke.log` | +| Expiry TTL=5 | `SESSION_TTL_SECONDS=5` | 200 → 401 через 6 сек | `04-expiry.log` | +| Readiness 503 при мёртвой БД | `stop db` + curl | live=200, ready=503 `unavailable` | `05-db-down-live.txt`, `06-db-down-ready.txt` | +| Логин 503 при мёртвой БД | `stop db` + login | 503 `unavailable` (не 500) | `07-db-down-login.txt` | +| Восстановление после `start db` | curl `/health/ready` | 200 | `08-db-up-ready.txt` | +| Гонка регистрации | 2× `POST /users` параллельно | 201 + 409 | `09-race.txt` | +| Rollback составной операции | чат с фиктивным `member_id` | 404 + count=0 | `10-rollback.txt` | +| EXPLAIN на 10k+ | `EXPLAIN (ANALYZE, BUFFERS)` | Index Scan, keyset не делает Seq Scan | `11-14-explain-*.txt` | + +### Уровень 5 — Трек 2 + +| Критерий | Команда | Результат | Файл | +|------------------------------|--------------------------------------|------------------------------------------------------------------------------|------------------------------------| +| 100k+ сообщений неравномерно | seed + count + GROUP BY | 116 011 / Huge 50k / Medium 5×5k / Small 250×100 | `track2-/01-seed.log` | +| EXPLAIN на 3 размерах | `EXPLAIN (ANALYZE, BUFFERS)` ×9 | OR деградирует линейно (30 514 буферов на 50k), tuple константен (54 буфера) | `track2-/02-10-explain-*.txt` | +| Сравнение индексов | A / B / C | A (8568 kB) — единственный корректный для tuple-keyset | `track2-/11-14-*.txt` | +| Стоимость записи | 3× INSERT 1000 строк, 4 vs 2 индекса | 4idx ~51 ms, 2idx ~23 ms (медиана) | `track2-/15-16-insert-*.log` | +| Backup → restore | `pg_dump -Fc` → `pg_restore` | RTO 1.98 сек, count и md5 совпали | `track2-/17-22-*.txt` | +| Сводка трека | markdown | гипотеза/методика/результаты/RTO/RPO | `track2-/README.md` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Hardware: Docker Desktop, Windows 11, 4 CPU, 16 GB RAM. Версии: PostgreSQL 16.15, Redis 7.4.11, Java 21, Spring Boot 4.1.1. Объём данных для трека 2: 116 011 сообщений, 263 чата, 49 пользователей. Прогрев: не делался (все измерения на горячем кэше `shared_buffers`). Повторы: 3 прогона для INSERT, взята медиана. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Воздействие | Что ожидали | Что наблюдали | Время восстановления / потеря | +|----------------------------------------|-----------------------------------------------------|---------------------------------------------------|------------------------------------------------| +| `stop redis` + smoke | приложение переживёт, `@Cacheable` уйдёт в Postgres | PASS, `Cache GET failed`, время ответа +0.5 сек | 0 (кэш восстанавливается при следующем чтении) | +| `SESSION_TTL_SECONDS=5`, sleep 6 | сессия истечёт | 200 → 401 | 6 сек — время TTL | +| `stop db` + `/health/live` | 200 (процесс жив) | 200 `{"status":"ok"}` | — | +| `stop db` + `/health/ready` | 503 `unavailable` | 503 `{"error":{"code":"unavailable"}}` | — | +| `stop db` + login | 503 `unavailable`, не 500 | 503 через ~4.2 сек (Hikari timeout 2s + overhead) | — | +| 2× `POST /users` с одинаковым username | 201 + 409 | 201 + 409 | — | +| Чат с несуществующим `member_id` | 404 + откат | 404 + `count(*)=0` | — | +| EXPLAIN keyset-OR на Huge (50k) | линейная деградация по позиции курсора | 30 514 буферов, 30 208 Rows Removed, 15.9 ms | — | +| EXPLAIN keyset-tuple на Huge | константа ~52 буфера | 54 буфера, 0.27 ms | — | +| 4 vs 2 индекса, INSERT 1000 строк | +10-30 ms с лишними индексами | 51 ms vs 23 ms (медиана) | — | +| `pg_dump` 35 МБ → `pg_restore` | RTO в секундах, полная сверка | RTO 1.98 сек, count и md5 совпали | потери = с момента последнего дампа | + +Гипотеза трека: keyset через JPQL-OR деградирует линейно; tuple-синтаксис константен; индекс `(chat_id, created_at, id)` оправдан; `pg_dump` даёт полное восстановление. + +Методика: см. `evidence/lab2/track2-/README.md`. + +Ограничения измерения: медиана по 3 прогонам (грубо); горячий кэш `shared_buffers`; один узел без конкурентной нагрузки; JPQL не генерирует tuple-синтаксис, в текущем коде — OR-вариант. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Что выдерживает приложение: +- Отказ Redis: чтение уходит в Postgres, запись сессий идёт напрямую в БД. Медленнее, но не падает. +- Отказ Postgres: `/health/ready` отдаёт 503, `/health/live` — 200, бизнес-запросы возвращают 503 `unavailable` вместо 500. Hikari `connection-timeout=2000ms` не даёт висеть клиенту 30 секунд. +- Рестарт API и БД без потери volumes: сессии и данные переживают (persistence-тест). +- Гонка регистрации и rollback составной операции: корректная обработка через unique constraint и `@Transactional`. + +Что не реализовано или учебное упрощение: +- Один узел Postgres, без репликации и failover БД. +- Кэш Redis не инвалидируется автоматически при TTL-истечении Postgres-записи — полагается на проверку `expiresAt` в `requireActive`. При жёстком рассинхроне возможно окно до `SESSION_TTL_SECONDS`. +- Keyset-пагинация в коде использует JPQL-трансляцию с OR — деградирует линейно на глубоких страницах. Обходной путь (native SQL с tuple) описан в отчёте трека 2, но в код не внесён: сохраняет совместимость с `@EntityGraph` для `Chat.members` и `@Cacheable` на `SessionService`. +- Backup — логический (`pg_dump`), не физический. Для production: `pg_basebackup` + WAL-архив + PITR. + +Подтверждено (гипотеза → результат): +- Graceful degradation Redis: PASS. +- Keyset OR деградирует линейно, tuple константен: доказано на 50k и 5k. +- Индекс `(chat_id, created_at, id)` оправдан: tuple-keyset за 54 буфера. +- Восстановление из `pg_dump`: count и md5 совпали, RTO 1.98 сек. + +Гипотеза (не проверено в этой лабе): +- На 500k+ сообщениях разница между OR и tuple станет критичной (секунды vs миллисекунды). Требует отдельного эксперимента. +- Параллельный restore (`pg_restore -j 4`) ускорит RTO пропорционально числу воркеров. Требует замера. +- WAL-архивирование даст RPO в секунды. Требует настройки `archive_mode` и хранилища. \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..e28f457d --- /dev/null +++ b/build.gradle @@ -0,0 +1,68 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.1.1' + id 'io.spring.dependency-management' version '1.1.7'} + +group = 'ru.mtusi' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-webmvc' + + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.1.0' + implementation 'com.bucket4j:bucket4j-core:8.10.1' + implementation 'org.mapstruct:mapstruct:1.6.3' + // Source: https://mvnrepository.com/artifact/org.postgresql/postgresql + implementation 'org.postgresql:postgresql:42.7.13' + implementation 'org.springframework.boot:spring-boot-starter-flyway' + runtimeOnly 'org.flywaydb:flyway-database-postgresql' + // Source: https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa + implementation 'org.springframework.boot:spring-boot-starter-data-jpa:4.1.1' + // Source: https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis + implementation 'org.springframework.boot:spring-boot-starter-data-redis:4.1.1' + implementation 'org.springframework.security:spring-security-crypto' + implementation 'org.bouncycastle:bcprov-jdk18on:1.78.1' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' + implementation 'org.springframework.boot:spring-boot-starter-cache' + implementation 'org.springframework.boot:spring-boot-starter-aspectj' + + runtimeOnly 'io.netty:netty-transport-native-epoll::linux-x86_64' + + testImplementation 'org.springframework.boot:spring-boot-starter-test:4.1.1' + + testImplementation 'org.springframework.boot:spring-boot-starter-restclient-test' + testImplementation 'org.springframework.boot:spring-boot-resttestclient' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3' + annotationProcessor 'org.projectlombok:lombok-mapstruct-binding:0.2.0' + annotationProcessor 'org.projectlombok:lombok' + testCompileOnly 'org.projectlombok:lombok' + testAnnotationProcessor 'org.projectlombok:lombok' + + testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test' + testImplementation 'org.springframework.boot:spring-boot-starter-validation-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.withType(JavaCompile).configureEach { + options.compilerArgs << '-parameters' +} + +tasks.named('test') { + useJUnitPlatform() +} \ No newline at end of file diff --git a/contracts/openapi.json b/contracts/openapi.json index 921d32db..7881abba 100644 --- a/contracts/openapi.json +++ b/contracts/openapi.json @@ -16,9 +16,32 @@ "bearerAuth": [] } ], + "tags": [ + { + "name": "Health", + "description": "Проверки живости и готовности процесса. Публичные, без аутентификации." + }, + { + "name": "Users", + "description": "Регистрация пользователей и доступ к профилю текущего пользователя." + }, + { + "name": "Auth", + "description": "Аутентификация: вход по Basic и выдача/отзыв сессионного Bearer-токена." + }, + { + "name": "Chats", + "description": "Управление чатами и доступ к чатам текущего пользователя." + }, + { + "name": "Messages", + "description": "Отправка и чтение сообщений внутри доступного чата." + } + ], "paths": { "/health/live": { "get": { + "tags": ["Health"], "operationId": "liveness", "summary": "Процесс жив", "responses": { @@ -66,6 +89,7 @@ }, "/health/ready": { "get": { + "tags": ["Health"], "operationId": "readiness", "summary": "Готов принимать трафик", "responses": { @@ -132,6 +156,7 @@ }, "/api/v1/users": { "post": { + "tags": ["Users"], "operationId": "registerUser", "summary": "Создать пользователя", "responses": { @@ -272,6 +297,7 @@ }, "/api/v1/users/me": { "get": { + "tags": ["Users"], "operationId": "currentUser", "summary": "Текущий пользователь", "responses": { @@ -445,6 +471,7 @@ }, "/api/v1/chats": { "post": { + "tags": ["Chats"], "operationId": "createChat", "summary": "Создать чат; вызывающий должен входить в member_ids", "responses": { @@ -626,6 +653,7 @@ } }, "get": { + "tags": ["Chats"], "operationId": "listChats", "summary": "Чаты текущего пользователя", "responses": { @@ -819,6 +847,7 @@ }, "/api/v1/chats/{chat_id}": { "get": { + "tags": ["Chats"], "operationId": "getChat", "summary": "Получить доступный чат", "responses": { @@ -1003,6 +1032,7 @@ }, "/api/v1/chats/{chat_id}/messages": { "post": { + "tags": ["Messages"], "operationId": "createMessage", "summary": "Отправить сообщение", "responses": { @@ -1195,6 +1225,7 @@ } }, "get": { + "tags": ["Messages"], "operationId": "listMessages", "summary": "Сообщения по (created_at, id) по возрастанию", "responses": { @@ -1397,6 +1428,7 @@ }, "/api/v1/auth/sessions": { "post": { + "tags": ["Auth"], "operationId": "createSession", "summary": "Вход: Basic username:password; выдаёт сессию", "responses": { @@ -1537,6 +1569,7 @@ }, "/api/v1/auth/sessions/current": { "delete": { + "tags": ["Auth"], "operationId": "revokeSession", "summary": "Отозвать текущую сессию", "responses": { @@ -2023,4 +2056,4 @@ } } } -} +} \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 00000000..9c25cc21 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,93 @@ +services: + db: + image: postgres:16-alpine + container_name: messenger-db + restart: unless-stopped + environment: + POSTGRES_DB_FILE: /run/secrets/postgres_db + POSTGRES_USER_FILE: /run/secrets/postgres_user + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + volumes: + - pgdata:/var/lib/postgresql/data + secrets: + - postgres_db + - postgres_user + - postgres_password + networks: + - messenger-net + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $$(cat /run/secrets/postgres_user) -d $$(cat /run/secrets/postgres_db)"] + interval: 5s + timeout: 5s + retries: 10 + start_period: 10s + + redis: + image: redis:7.4-alpine + container_name: messenger-redis + restart: unless-stopped + command: > + redis-server + --appendonly yes + --appendfsync everysec + --save "" + volumes: + - redisdata:/data + networks: + - messenger-net + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + + api: + build: + context: . + dockerfile: Dockerfile + container_name: messenger-api + restart: unless-stopped + depends_on: + db: + condition: service_healthy + redis: + condition: service_healthy + environment: + SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/messenger + SPRING_DATASOURCE_USERNAME_FILE: /run/secrets/postgres_user + SPRING_DATASOURCE_PASSWORD_FILE: /run/secrets/postgres_password + SPRING_PROFILES_ACTIVE: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-400} + SESSION_STORE: ${SESSION_STORE:-postgres} + SPRING_DATA_REDIS_HOST: redis + SPRING_DATA_REDIS_PORT: 6379 + ports: + - "127.0.0.1:8080:8080" + secrets: + - postgres_user + - postgres_password + networks: + - messenger-net + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/health/ready | grep -q '\"status\":\"ok\"'"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 40s + +volumes: + pgdata: + redisdata: + +networks: + messenger-net: + driver: bridge + +secrets: + postgres_db: + file: ./secrets/postgres_db.txt + postgres_user: + file: ./secrets/postgres_user.txt + postgres_password: + file: ./secrets/postgres_password.txt \ No newline at end of file diff --git a/evidence/lab2/level3-2026-10-08_65bd58c/04-compose-ps-before.txt b/evidence/lab2/level3-2026-10-08_65bd58c/04-compose-ps-before.txt new file mode 100644 index 00000000..518a09fb Binary files /dev/null and b/evidence/lab2/level3-2026-10-08_65bd58c/04-compose-ps-before.txt differ diff --git a/evidence/lab2/level3-2026-10-08_65bd58c/06-compose-ps-after.txt b/evidence/lab2/level3-2026-10-08_65bd58c/06-compose-ps-after.txt new file mode 100644 index 00000000..ab146b9c Binary files /dev/null and b/evidence/lab2/level3-2026-10-08_65bd58c/06-compose-ps-after.txt differ diff --git a/evidence/lab2/level3-2026-10-08_65bd58c/07-gitignore.txt b/evidence/lab2/level3-2026-10-08_65bd58c/07-gitignore.txt new file mode 100644 index 00000000..a341c0f1 Binary files /dev/null and b/evidence/lab2/level3-2026-10-08_65bd58c/07-gitignore.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/01-redis-keys.txt b/evidence/lab2/level4-2026-10-08_e64b104/01-redis-keys.txt new file mode 100644 index 00000000..b89ad8b4 Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/01-redis-keys.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/02-redis-ttl.txt b/evidence/lab2/level4-2026-10-08_e64b104/02-redis-ttl.txt new file mode 100644 index 00000000..18e47602 Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/02-redis-ttl.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/05-db-down-live.txt b/evidence/lab2/level4-2026-10-08_e64b104/05-db-down-live.txt new file mode 100644 index 00000000..68f2fd87 Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/05-db-down-live.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/06-db-down-ready.txt b/evidence/lab2/level4-2026-10-08_e64b104/06-db-down-ready.txt new file mode 100644 index 00000000..7b7c198c Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/06-db-down-ready.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/07-db-down-login.txt b/evidence/lab2/level4-2026-10-08_e64b104/07-db-down-login.txt new file mode 100644 index 00000000..94b5cace Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/07-db-down-login.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/08-db-up-ready.txt b/evidence/lab2/level4-2026-10-08_e64b104/08-db-up-ready.txt new file mode 100644 index 00000000..76110487 Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/08-db-up-ready.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/09-race.txt b/evidence/lab2/level4-2026-10-08_e64b104/09-race.txt new file mode 100644 index 00000000..7278399c Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/09-race.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/10-rollback.txt b/evidence/lab2/level4-2026-10-08_e64b104/10-rollback.txt new file mode 100644 index 00000000..a2e31f66 Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/10-rollback.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/11-explain-first.txt b/evidence/lab2/level4-2026-10-08_e64b104/11-explain-first.txt new file mode 100644 index 00000000..2cfde9ff Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/11-explain-first.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/12-explain-keyset-or.txt b/evidence/lab2/level4-2026-10-08_e64b104/12-explain-keyset-or.txt new file mode 100644 index 00000000..6fb7a584 Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/12-explain-keyset-or.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/13-explain-keyset-tuple.txt b/evidence/lab2/level4-2026-10-08_e64b104/13-explain-keyset-tuple.txt new file mode 100644 index 00000000..0e49cdf2 Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/13-explain-keyset-tuple.txt differ diff --git a/evidence/lab2/level4-2026-10-08_e64b104/14-explain-no-index.txt b/evidence/lab2/level4-2026-10-08_e64b104/14-explain-no-index.txt new file mode 100644 index 00000000..2ad5ddbd Binary files /dev/null and b/evidence/lab2/level4-2026-10-08_e64b104/14-explain-no-index.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/01.1 b/evidence/lab2/track2-2026-10-08_c744ee5/01.1 new file mode 100644 index 00000000..47a0851f --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/01.1 @@ -0,0 +1,2 @@ +узнать актуальные ID чатов +docker compose --env-file .env exec db psql -U messenger -d messenger -c "SELECT id, title FROM chats WHERE title IN ('Huge chat', 'Medium chat 1', 'Small chat 1') ORDER BY title;" \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/02-explain-huge-first.txt b/evidence/lab2/track2-2026-10-08_c744ee5/02-explain-huge-first.txt new file mode 100644 index 00000000..7ce327ed Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/02-explain-huge-first.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/03-explain-huge-or.txt b/evidence/lab2/track2-2026-10-08_c744ee5/03-explain-huge-or.txt new file mode 100644 index 00000000..78010965 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/03-explain-huge-or.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/04-explain-huge-tuple.txt b/evidence/lab2/track2-2026-10-08_c744ee5/04-explain-huge-tuple.txt new file mode 100644 index 00000000..503b7af1 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/04-explain-huge-tuple.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/05-explain-medium-first.txt b/evidence/lab2/track2-2026-10-08_c744ee5/05-explain-medium-first.txt new file mode 100644 index 00000000..9220bbaa Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/05-explain-medium-first.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/06-explain-medium-or.txt b/evidence/lab2/track2-2026-10-08_c744ee5/06-explain-medium-or.txt new file mode 100644 index 00000000..40ef58da Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/06-explain-medium-or.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/07-explain-medium-tuple.txt b/evidence/lab2/track2-2026-10-08_c744ee5/07-explain-medium-tuple.txt new file mode 100644 index 00000000..43373390 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/07-explain-medium-tuple.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/08-explain-small-first.txt b/evidence/lab2/track2-2026-10-08_c744ee5/08-explain-small-first.txt new file mode 100644 index 00000000..516d2432 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/08-explain-small-first.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/09-explain-small-or.txt b/evidence/lab2/track2-2026-10-08_c744ee5/09-explain-small-or.txt new file mode 100644 index 00000000..c92dd0a7 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/09-explain-small-or.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/10-explain-small-tuple.txt b/evidence/lab2/track2-2026-10-08_c744ee5/10-explain-small-tuple.txt new file mode 100644 index 00000000..bd258ef1 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/10-explain-small-tuple.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/11-index-sizes.txt b/evidence/lab2/track2-2026-10-08_c744ee5/11-index-sizes.txt new file mode 100644 index 00000000..539e9264 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/11-index-sizes.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/12-explain-index-a.txt b/evidence/lab2/track2-2026-10-08_c744ee5/12-explain-index-a.txt new file mode 100644 index 00000000..87439789 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/12-explain-index-a.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/13-explain-index-b.txt b/evidence/lab2/track2-2026-10-08_c744ee5/13-explain-index-b.txt new file mode 100644 index 00000000..377bd90a Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/13-explain-index-b.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/14-explain-index-c.txt b/evidence/lab2/track2-2026-10-08_c744ee5/14-explain-index-c.txt new file mode 100644 index 00000000..62aa416a Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/14-explain-index-c.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/15.1 b/evidence/lab2/track2-2026-10-08_c744ee5/15.1 new file mode 100644 index 00000000..f1aa77f0 --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/15.1 @@ -0,0 +1,3 @@ +docker compose --env-file .env exec db psql -U messenger -d messenger -c "DROP INDEX idx_test_c;" +docker compose --env-file .env exec db psql -U messenger -d messenger -c "CREATE INDEX idx_messages_chat_created_asc_id ON messages (chat_id, created_at ASC, id ASC);" +docker compose --env-file .env exec db psql -U messenger -d messenger -c "ANALYZE messages;" \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/15.2 b/evidence/lab2/track2-2026-10-08_c744ee5/15.2 new file mode 100644 index 00000000..223b621c --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/15.2 @@ -0,0 +1,3 @@ +docker compose --env-file .env exec db psql -U messenger -d messenger -c "CREATE INDEX idx_test_b ON messages (chat_id, created_at ASC);" +docker compose --env-file .env exec db psql -U messenger -d messenger -c "CREATE INDEX idx_test_c ON messages (chat_id, id);" +docker compose --env-file .env exec db psql -U messenger -d messenger -c "ANALYZE messages;" \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/16.1 b/evidence/lab2/track2-2026-10-08_c744ee5/16.1 new file mode 100644 index 00000000..20f3e5ca --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/16.1 @@ -0,0 +1 @@ +docker compose --env-file .env exec db psql -U messenger -d messenger -c "DROP INDEX idx_test_b; DROP INDEX idx_test_c;" \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/17-counts-before.txt b/evidence/lab2/track2-2026-10-08_c744ee5/17-counts-before.txt new file mode 100644 index 00000000..4c90edb0 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/17-counts-before.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/18-dump-size.txt b/evidence/lab2/track2-2026-10-08_c744ee5/18-dump-size.txt new file mode 100644 index 00000000..90ae2d13 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/18-dump-size.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/19-restore-time.txt b/evidence/lab2/track2-2026-10-08_c744ee5/19-restore-time.txt new file mode 100644 index 00000000..31b3c527 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/19-restore-time.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/19.1 b/evidence/lab2/track2-2026-10-08_c744ee5/19.1 new file mode 100644 index 00000000..674d4943 --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/19.1 @@ -0,0 +1 @@ +docker compose --env-file .env exec db psql -U messenger -d postgres -c "CREATE DATABASE messenger_restore;" \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/20-counts-after.txt b/evidence/lab2/track2-2026-10-08_c744ee5/20-counts-after.txt new file mode 100644 index 00000000..0b4eb6f5 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/20-counts-after.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/21-sample-original.txt b/evidence/lab2/track2-2026-10-08_c744ee5/21-sample-original.txt new file mode 100644 index 00000000..1105f116 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/21-sample-original.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/22-sample-restored.txt b/evidence/lab2/track2-2026-10-08_c744ee5/22-sample-restored.txt new file mode 100644 index 00000000..b888ff14 Binary files /dev/null and b/evidence/lab2/track2-2026-10-08_c744ee5/22-sample-restored.txt differ diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/23.1 b/evidence/lab2/track2-2026-10-08_c744ee5/23.1 new file mode 100644 index 00000000..a1bfd860 --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/23.1 @@ -0,0 +1 @@ +docker compose --env-file .env exec db psql -U messenger -d postgres -c "DROP DATABASE messenger_restore;" \ No newline at end of file diff --git a/evidence/lab2/track2-2026-10-08_c744ee5/README.md b/evidence/lab2/track2-2026-10-08_c744ee5/README.md new file mode 100644 index 00000000..e559312b --- /dev/null +++ b/evidence/lab2/track2-2026-10-08_c744ee5/README.md @@ -0,0 +1,143 @@ +Трек 2. План запроса и восстановление + +Дата: 2026-10-08 +Commit: c744ee5 +Окружение: Docker Desktop, Windows 11, 4 CPU / 16 GB RAM +Версии: PostgreSQL 16.15, Redis 7.4.11, Java 21, Spring Boot 4.1.1 + +Гипотеза + +1. План keyset-пагинации деградирует линейно с размером чата, если keyset выражен через OR-условие (JPQL-трансляция Hibernate). Tuple-синтаксис (created_at, id) > (?, ?) использует B-tree как диапазон и даёт константную стоимость. +2. Индекс (chat_id, created_at, id) оправдан для keyset, но не бесплатен — каждый дополнительный индекс увеличивает стоимость записи. +3. Логический дамп (pg_dump -Fc) позволяет полностью восстановить БД в новое хранилище с проверяемым RTO. + +Профиль данных + +- Сообщений: 116 011 +- Чатов: 263 +- Пользователей: 49 +- Распределение: Huge chat 50 000, seed_chat 10 000, 5 Medium по 5 000, 250 Small по 100 +- Размер таблицы messages: 15 МБ +- Размер индекса idx_messages_chat_created_asc_id: 8 568 kB +- Размер индекса messages_pkey: 4 376 kB +- Размер БД messenger: 35 МБ + +Методика + +EXPLAIN + +Для трёх чатов разного размера (Huge 50k, Medium 5k, Small 100) сняты три варианта плана: + +1. first page — ORDER BY created_at, id LIMIT 50 без курсора. +2. OR-keyset — как генерирует Hibernate из JPQL: (created_at > X OR (created_at = X AND id > Y)). +3. tuple-keyset — как должно быть: (created_at, id) > (X, Y). + +Команда: EXPLAIN (ANALYZE, BUFFERS) SELECT ... + +Метрика: Buffers: shared hit — сколько страниц (индексных + heap) реально прочитано. Это устойчивее, чем Execution Time, который зависит от кэша. + +Сравнение индексов + +Созданы два альтернативных индекса: + +- A (текущий): (chat_id, created_at ASC, id ASC) — 8 568 kB. +- B: (chat_id, created_at ASC) — 4 384 kB. +- C: (chat_id, id) — 5 368 kB. + +Для каждого — EXPLAIN с tuple-запросом (или эквивалентным для его колонок). После замера индексы удалены. + +Стоимость записи + +3 прогона INSERT 1000 сообщений с 4 индексами, 3 прогона с 2 индексами. Взята медиана. Разница — цена двух лишних индексов. + +Backup и restore + +1. Контрольные точки: count(*) по messages, users, chats; md5(string_agg(id, ',')) по messages. +2. pg_dump -Fc в файл. +3. CREATE DATABASE messenger_restore. +4. pg_restore с таймером (Measure-Command). +5. Сверка count и md5. +6. Выборочная сверка: 3 сообщения по конкретному чату. +7. DROP DATABASE. + +Результаты + +EXPLAIN (ANALYZE, BUFFERS) + +| Чат | Размер | Запрос | План | Buffers | Rows Removed | Time | +|--------|----------|---------|-------------------------|-----------|---------------|---------| +| Huge | 50k | first | Index Scan | 53 | 0 | 0.23 ms | +| Huge | 50k | OR | Index Scan + Filter | 30 514 | 30 208 | 15.9 ms | +| Huge | 50k | tuple | Index Scan + Index Cond | 54 | 0 | 0.27 ms | +| Medium | 5k | first | Index Scan | 52 | 0 | 0.17 ms | +| Medium | 5k | OR | Index Scan + Filter | 3 048 | 3 001 | 1.9 ms | +| Medium | 5k | tuple | Index Scan + Index Cond | 53 | 0 | 0.18 ms | +| Small | 100 | first | Index Scan | 28 | 0 | 0.14 ms | +| Small | 100 | OR | Bitmap Heap + Sort | 27 | 0 | 0.48 ms | +| Small | 100 | tuple | Bitmap Heap + Sort | 24 | 0 | 0.24 ms | + +Вывод 1. OR-keyset деградирует линейно: 50k → 30 514 буферов, 5k → 3 048 буферов. Отношение 10×. Tuple-keyset константен: 54 и 53 буфера. Разница ×565 и ×57 соответственно. + +Вывод 2. На мелких чатах (100 строк) Postgres выбирает Bitmap Heap Scan + Sort вместо Index Scan — планировщик сам решает, что индекс на маленькой выборке не окупается. + +Сравнение индексов + +| Индекс | Определение | Размер | Buffers (Huge, tuple) | +|----------|---------------------------|----------|------------------------| +| A | (chat_id, created_at, id) | 8 568 kB | 54 | +| B | (chat_id, created_at) | 4 384 kB | 53 (по created_at) | +| C | (chat_id, id) | 5 368 kB | 50 (по id) | + +Вывод. Все три индекса дают keyset за ~53 буфера. Но B не может разорвать ties по created_at (два сообщения с одной миллисекундой могут дублироваться или пропускаться при пагинации), C сортирует по UUID вместо времени. Только A даёт стабильный tuple-keyset (created_at, id). Дополнительные 4 МБ оправданы корректностью. + +Стоимость записи + +| Конфигурация | Прогоны (ms) | Медиана | +|----------------|--------------------|----------| +| 4 индекса | 89.4 / 51.5 / 38.8 | ~51 ms | +| 2 индекса | 23.6 / 22.9 / 23.2 | ~23 ms | + +Вывод. Дельта ~28 ms на 1000 строк = ~28 µs/строка за два лишних индекса = ~14 µs за индекс. На учебном объёме это незаметно, но при высоком RPS и больших таблицах каждый индекс должен быть обоснован конкретным запросом. + +Backup и restore + +| Метрика | Значение | +|-----------------------------------------|----------------------------------| +| Count before (messages / users / chats) | 116 011 / 49 / 263 | +| md5 id сообщений before | ca7a05ca849eedb7a4b7abd0044b3322 | +| Размер дампа (-Fc) | 4.6 МБ (сжатие ~8×) | +| RTO (restore) | 1.98 сек | +| Count after | 116 011 / 49 / 263 | +| md5 after | ca7a05ca849eedb7a4b7abd0044b3322 | +| Выборочная сверка (3 сообщения) | id/text/created_at совпали 1-в-1 | + +RTO и RPO + +RTO (Recovery Time Objective) + +Восстановление 35 МБ БД заняло 1.98 сек. Масштабируется ~линейно: 350 МБ → ~20 сек, 3.5 ГБ → ~3.5 мин. Для ускорения: pg_restore -j N (параллельный restore из custom format), больше CPU. На production обычно измеряется не в секундах, а в бизнес-требованиях (например, «восстановиться за 4 часа»), и достигается через реплику + PITR, а не только pg_dump. + +RPO (Recovery Point Objective) + +RPO = время с момента последнего pg_dump. Стратегии: + +| Стратегия | RPO | +|--------------------------|-------------| +| pg_dump раз в сутки | до 24 часов | +| pg_dump раз в час | до 1 часа | +| WAL-архивирование (PITR) | секунды | +| Синхронная репликация | ~0 | + +На учебном стенде RPO не определён (нет расписания дампов). Границы потери данных: + +- Всё, что появилось после последнего дампа — теряется. +- Незакоммиченные транзакции при краше — откатываются автоматически (WAL). +- synchronous_commit = off ускоряет запись, но может потерять последние ~200 мс закоммиченных транзакций при краше ОС или питания. + +Ограничения + +1. JPQL не генерирует tuple-синтаксис. Hibernate транслирует keyset в OR, что даёт линейную деградацию. Обходной путь — native SQL с (created_at, id) > (?, ?). В текущей реализации используется OR-вариант. +2. Тест на одном узле. Нет конкурентной нагрузки, нет параллельных writers, нет replication lag. +3. pg_dump — логический бэкап. На больших БД (десятки ГБ) полный restore занимает часы. Для production: pg_basebackup (физический) + WAL-архив + PITR. +4. Замеры INSERT проведены на горячем кэше с shared_buffers по умолчанию (~128 МБ). На больших объёмах пропорции индексов могут отличаться. +5. Медиана по 3 прогонам — грубая. Для production-замеров нужно ≥10 прогонов и p95. \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..eddabd2e Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ad7845be --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..249efbb0 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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 +# + +############################################################################## +# +# gradlew 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 gradlew +# +# 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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 + + + +# 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" ) + + 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='"-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" \ + -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..a51ec4f5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/scripts/restart.bat b/scripts/restart.bat new file mode 100644 index 00000000..caba6d52 --- /dev/null +++ b/scripts/restart.bat @@ -0,0 +1,2 @@ +@echo off +docker compose --env-file .env restart api db \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..2bb40f48 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +# Restart API and all state stores used in lab2 (Postgres). +# Preserve persistent volumes and data: never `down -v`, never flush or re-seed. +# Exit 0 only after issuing the restart; the test waits for API readiness separately. + +docker compose --env-file .env restart api db \ No newline at end of file diff --git a/scripts/seed_10k.sql b/scripts/seed_10k.sql new file mode 100644 index 00000000..df3cf394 --- /dev/null +++ b/scripts/seed_10k.sql @@ -0,0 +1,21 @@ +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES ('11111111-1111-4111-8111-111111111111', 'seed_user', 'Seed', + '$2a$10$abcdefghijklmnopqrstuv', now()) + ON CONFLICT (username) DO NOTHING; + +INSERT INTO chats (id, title, created_at) +VALUES ('22222222-2222-4222-8222-222222222222', 'seed_chat', now()) + ON CONFLICT (id) DO NOTHING; + +INSERT INTO chat_members (chat_id, user_id) +VALUES ('22222222-2222-4222-8222-222222222222', + '11111111-1111-4111-8111-111111111111') + ON CONFLICT DO NOTHING; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), + '22222222-2222-4222-8222-222222222222', + '11111111-1111-4111-8111-111111111111', + 'msg #' || g || ' ' || repeat('x', 1 + (random()*200)::int), + now() - (random() * interval '30 days') +FROM generate_series(1, 10000) g; \ No newline at end of file diff --git a/scripts/seed_messages.sql b/scripts/seed_messages.sql new file mode 100644 index 00000000..c188dd4a --- /dev/null +++ b/scripts/seed_messages.sql @@ -0,0 +1,24 @@ +-- создаём тестового юзера и чат +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES ('11111111-1111-4111-8111-111111111111', 'seed_user', 'Seed', + '$2a$10$abcdefghijklmnopqrstuv', now()) + ON CONFLICT (username) DO NOTHING; + +INSERT INTO chats (id, title, created_at) +VALUES ('22222222-2222-4222-8222-222222222222', 'seed_chat', now()) + ON CONFLICT (id) DO NOTHING; + +INSERT INTO chat_members (chat_id, user_id, role, joined_at) +VALUES ('22222222-2222-4222-8222-222222222222', + '11111111-1111-4111-8111-111111111111', 'owner', now()) + ON CONFLICT DO NOTHING; + +-- 10000 сообщений с разбросом created_at за последние 30 дней +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + gen_random_uuid(), + '22222222-2222-4222-8222-222222222222', + '11111111-1111-4111-8111-111111111111', + 'msg #' || g || ' ' || repeat('x', 1 + (random()*200)::int), + now() - (random() * interval '30 days') +FROM generate_series(1, 10000) g; \ No newline at end of file diff --git a/scripts/seed_track2.sql b/scripts/seed_track2.sql new file mode 100644 index 00000000..6a8edd03 --- /dev/null +++ b/scripts/seed_track2.sql @@ -0,0 +1,75 @@ +-- Пользователи +INSERT INTO users (id, username, display_name, password_hash, created_at) +SELECT + gen_random_uuid(), + 'u_' || lpad(g::text, 4, '0'), + 'User ' || g, + '$2a$10$abcdefghijklmnopqrstuv', -- фиктивный bcrypt-хеш, не для логина + now() - (random() * interval '60 days') +FROM generate_series(1, 20) g; + +-- Один чат-гигант +INSERT INTO chats (id, title, created_at) +VALUES ('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'Huge chat', now() - interval '60 days'); + +INSERT INTO chat_members (chat_id, user_id) +SELECT 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', id FROM users LIMIT 5; + +-- 50 000 сообщений в гиганта +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + gen_random_uuid(), + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + (SELECT id FROM users ORDER BY random() LIMIT 1), + 'msg #' || g || ' ' || repeat('x', 1 + (random()*100)::int), + now() - (random() * interval '60 days') +FROM generate_series(1, 50000) g; + +-- 5 чатов по 5000 +DO $$ +DECLARE +cid uuid; + i int; +BEGIN +FOR i IN 1..5 LOOP + cid := gen_random_uuid(); +INSERT INTO chats (id, title, created_at) +VALUES (cid, 'Medium chat ' || i, now() - (random() * interval '60 days')); +INSERT INTO chat_members (chat_id, user_id) +SELECT cid, id FROM users LIMIT 3; +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + gen_random_uuid(), cid, + (SELECT id FROM users ORDER BY random() LIMIT 1), + 'm-' || i || '-' || g || ' ' || repeat('x', 1 + (random()*100)::int), + now() - (random() * interval '60 days') +FROM generate_series(1, 5000) g; +END LOOP; +END $$; + +-- 250 чатов по 100 +DO $$ +DECLARE +cid uuid; + i int; +BEGIN +FOR i IN 1..250 LOOP + cid := gen_random_uuid(); +INSERT INTO chats (id, title, created_at) +VALUES (cid, 'Small chat ' || i, now() - (random() * interval '60 days')); +INSERT INTO chat_members (chat_id, user_id) +SELECT cid, id FROM users LIMIT 2; +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + gen_random_uuid(), cid, + (SELECT id FROM users ORDER BY random() LIMIT 1), + 's-' || i || '-' || g, + now() - (random() * interval '60 days') +FROM generate_series(1, 100) g; +END LOOP; +END $$; + +ANALYZE users; +ANALYZE chats; +ANALYZE chat_members; +ANALYZE messages; \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..650573b3 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'messenger-lab1' diff --git a/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java b/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java new file mode 100644 index 00000000..54938665 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/MessengerLab1Application.java @@ -0,0 +1,16 @@ +package ru.mtusi.messenger; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.boot.security.autoconfigure.UserDetailsServiceAutoConfiguration; + +@ConfigurationPropertiesScan +@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class) +public class MessengerLab1Application { + + public static void main(String[] args) { + SpringApplication.run(MessengerLab1Application.class, args); + } + +} diff --git a/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java b/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java new file mode 100644 index 00000000..c3c1d66a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/cache/CacheHealthTracker.java @@ -0,0 +1,19 @@ +package ru.mtusi.messenger.cache; + +import org.springframework.stereotype.Component; + +import java.util.concurrent.atomic.AtomicBoolean; + +@Component +public class CacheHealthTracker { + + private final AtomicBoolean stale = new AtomicBoolean(false); + + public void markStale() { + stale.set(true); + } + + public boolean consumeStale() { + return stale.getAndSet(false); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java b/src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java new file mode 100644 index 00000000..06edae6a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/OpenApiConfig.java @@ -0,0 +1,20 @@ +package ru.mtusi.messenger.config; + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SecurityScheme( + name = "basicAuth", + type = SecuritySchemeType.HTTP, + scheme = "basic" +) +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + scheme = "bearer", + bearerFormat = "opaque session token" +) +public class OpenApiConfig { +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java b/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java new file mode 100644 index 00000000..3a609576 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/RateLimitConfig.java @@ -0,0 +1,25 @@ +package ru.mtusi.messenger.config; + +import io.github.bucket4j.Bandwidth; +import io.github.bucket4j.Bucket; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.mtusi.messenger.config.properties.RateLimitProperties; + +import java.time.Duration; + +@Configuration +@RequiredArgsConstructor +public class RateLimitConfig { + private final RateLimitProperties props; + + @Bean + public Bucket rateLimitBucket() { + Bandwidth limit = Bandwidth.builder() + .capacity(props.ratePerMinute()) + .refillGreedy(props.ratePerMinute(), Duration.ofMinutes(1)) + .build(); + return Bucket.builder().addLimit(limit).build(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/RedisConfig.java b/src/main/java/ru/mtusi/messenger/config/RedisConfig.java new file mode 100644 index 00000000..badf523a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/RedisConfig.java @@ -0,0 +1,105 @@ +package ru.mtusi.messenger.config; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.SocketOptions; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cache.Cache; +import org.springframework.cache.annotation.CachingConfigurer; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.interceptor.CacheErrorHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import ru.mtusi.messenger.cache.CacheHealthTracker; +import ru.mtusi.messenger.config.properties.RedisProperties; +import ru.mtusi.messenger.config.properties.SessionProperties; +import ru.mtusi.messenger.service.SessionService; + +@Slf4j +@Configuration +@EnableCaching +@EnableConfigurationProperties(RedisProperties.class) +@RequiredArgsConstructor +public class RedisConfig implements CachingConfigurer { + private final SessionProperties sessionProperties; + private final RedisProperties redisProperties; + private final CacheHealthTracker cacheHealthTracker; + + @Bean + public RedisConnectionFactory redisConnectionFactory() { + RedisStandaloneConfiguration server = + new RedisStandaloneConfiguration(redisProperties.host(), redisProperties.port()); + + SocketOptions socketOptions = SocketOptions.builder() + .connectTimeout(redisProperties.connectTimeout()) + .keepAlive(SocketOptions.KeepAliveOptions.builder() + .enable() + .idle(redisProperties.keepAliveIdle()) + .interval(redisProperties.keepAliveInterval()) + .count(3) + .build()) + .tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder() + .tcpUserTimeout(redisProperties.tcpUserTimeout()) + .enable() + .build()) + .build(); + + ClientOptions clientOptions = ClientOptions.builder() + .socketOptions(socketOptions) + .autoReconnect(true) + .build(); + + LettuceClientConfiguration client = LettuceClientConfiguration.builder() + .commandTimeout(redisProperties.commandTimeout()) + .shutdownTimeout(redisProperties.shutdownTimeout()) + .clientOptions(clientOptions) + .build(); + + return new LettuceConnectionFactory(server, client); + } + + @Bean + public RedisCacheManager cacheManager(RedisConnectionFactory cf) { + RedisCacheConfiguration cfg = RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(sessionProperties.ttl()) + .disableCachingNullValues() + .serializeValuesWith(RedisSerializationContext.SerializationPair + .fromSerializer(new JacksonJsonRedisSerializer<>(SessionService.SessionRecord.class))); + return RedisCacheManager.builder(cf).cacheDefaults(cfg).build(); + } + + @Override + public CacheErrorHandler errorHandler() { + return new CacheErrorHandler() { + @Override + public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { + cacheHealthTracker.markStale(); + log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { + cacheHealthTracker.markStale(); + log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { + cacheHealthTracker.markStale(); + log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage()); + } + @Override + public void handleCacheClearError(RuntimeException e, Cache cache) { + cacheHealthTracker.markStale(); + log.warn("Cache CLEAR failed ({}): {}", cache.getName(), e.getMessage()); + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java b/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java new file mode 100644 index 00000000..a2233e0c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/SecurityConfig.java @@ -0,0 +1,75 @@ +package ru.mtusi.messenger.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import ru.mtusi.messenger.security.ApiAuthenticationEntryPoint; +import ru.mtusi.messenger.security.SessionAuthenticationFilter; +import ru.mtusi.messenger.security.SessionAuthenticationProvider; +import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; +import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + private final SessionAuthenticationProvider sessionAuthenticationProvider; + private final ApiAuthenticationEntryPoint entryPoint; + + @Bean + public PasswordEncoder passwordEncoder() { + return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(); + } + + @Bean + public AuthenticationManager authenticationManager() { + return new ProviderManager(sessionAuthenticationProvider); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http, + AuthenticationManager authenticationManager, + BearerTokenResolver bearerTokenResolver) throws Exception { + SessionAuthenticationFilter sessionFilter = + new SessionAuthenticationFilter(bearerTokenResolver, authenticationManager); + + http + .csrf(AbstractHttpConfigurer::disable) + .httpBasic(AbstractHttpConfigurer::disable) + .formLogin(AbstractHttpConfigurer::disable) + .logout(AbstractHttpConfigurer::disable) + .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/health/**").permitAll() + .requestMatchers( + "/swagger-ui.html", + "/swagger-ui/**", + "/v3/api-docs", + "/v3/api-docs/**" + ).permitAll() + .requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll() + .requestMatchers(HttpMethod.POST, "/api/v1/auth/sessions").permitAll() + .requestMatchers("/actuator/health", "/actuator/health/**").permitAll() + .anyRequest().authenticated()) + .addFilterBefore(sessionFilter, UsernamePasswordAuthenticationFilter.class) + .exceptionHandling(eh -> eh.authenticationEntryPoint(entryPoint)); + + return http.build(); + } + + @Bean + public BearerTokenResolver bearerTokenResolver() { + return new DefaultBearerTokenResolver(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java new file mode 100644 index 00000000..127495e6 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/AppProperties.java @@ -0,0 +1,8 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.limits") +public record AppProperties( + int maxMessagesPerChat +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java new file mode 100644 index 00000000..39d4646d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/RateLimitProperties.java @@ -0,0 +1,6 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.rate") +public record RateLimitProperties(int ratePerMinute, int retryAfterSeconds) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java new file mode 100644 index 00000000..994ae257 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/RedisProperties.java @@ -0,0 +1,16 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import java.time.Duration; + +@ConfigurationProperties(prefix = "app.redis") +public record RedisProperties( + String host, + int port, + Duration commandTimeout, + Duration connectTimeout, + Duration shutdownTimeout, + Duration keepAliveIdle, + Duration keepAliveInterval, + Duration tcpUserTimeout +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java b/src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java new file mode 100644 index 00000000..6ff06f2f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/config/properties/SessionProperties.java @@ -0,0 +1,10 @@ +package ru.mtusi.messenger.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.time.Duration; + +@ConfigurationProperties(prefix = "app.session") +public record SessionProperties( + Duration ttl +) {} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/AuthApi.java b/src/main/java/ru/mtusi/messenger/controller/AuthApi.java new file mode 100644 index 00000000..9d0626bf --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AuthApi.java @@ -0,0 +1,118 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import ru.mtusi.messenger.dto.SessionDTO; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Auth", description = "Аутентификация: вход по Basic и выдача/отзыв сессионного Bearer-токена.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface AuthApi { + + /** + * POST /api/v1/auth/sessions : Вход: Basic username:password; выдаёт сессию + * + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "createSession", + summary = "Вход: Basic username:password; выдаёт сессию", + tags = { "Auth" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = SessionDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + }, + security = { + @SecurityRequirement(name = "basicAuth") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/auth/sessions", + produces = { "application/json" } + ) + + ResponseEntity createSession( + + ); + + + /** + * DELETE /api/v1/auth/sessions/current : Отозвать текущую сессию + * + * @return Успех (status code 204) + * or Нет действительной аутентификации (status code 401) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "revokeSession", + summary = "Отозвать текущую сессию", + tags = { "Auth" }, + responses = { + @ApiResponse(responseCode = "204", description = "Успех"), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.DELETE, + value = "/api/v1/auth/sessions/current", + produces = { "application/json" } + ) + + ResponseEntity revokeSession( + + ); + +} diff --git a/src/main/java/ru/mtusi/messenger/controller/AuthController.java b/src/main/java/ru/mtusi/messenger/controller/AuthController.java new file mode 100644 index 00000000..5cb66068 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/AuthController.java @@ -0,0 +1,28 @@ +package ru.mtusi.messenger.controller; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.service.AuthService; + +@RestController +@RequiredArgsConstructor +public class AuthController implements AuthApi { + private final AuthService authService; + private final HttpServletRequest request; + + @Override + public ResponseEntity createSession() { + return ResponseEntity.status(HttpStatus.CREATED).body(authService.login(request.getHeader(HttpHeaders.AUTHORIZATION))); + } + + @Override + public ResponseEntity revokeSession() { + authService.logout(); + return ResponseEntity.noContent().build(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/ChatController.java b/src/main/java/ru/mtusi/messenger/controller/ChatController.java new file mode 100644 index 00000000..5eb47727 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/ChatController.java @@ -0,0 +1,35 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.ChatService; + +import java.util.UUID; + +@RestController +@RequiredArgsConstructor +public class ChatController implements ChatsApi { + private final ChatService chatService; + + @Override + public ResponseEntity createChat(ChatDTO chatDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED) + .body(chatService.createChat(principal.userId(), chatDTO)); + } + + @Override + public ResponseEntity getChat(UUID chatId , @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(chatService.getChatDTO(principal.userId(), chatId)); + } + + @Override + public ResponseEntity listChats(Integer limit, String cursor , @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(chatService.listChats(principal.userId(), limit, cursor)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java new file mode 100644 index 00000000..c5b11eaf --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/ChatsApi.java @@ -0,0 +1,215 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.dto.ErrorDTO; +import java.util.UUID; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import jakarta.annotation.Generated; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Chats", description = "Управление чатами и доступ к чатам текущего пользователя.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface ChatsApi { + + /** + * POST /api/v1/chats : Создать чат; вызывающий должен входить в member_ids + * + * @param chatDTO (required) + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "createChat", + summary = "Создать чат; вызывающий должен входить в member_ids", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/chats", + produces = { "application/json" }, + consumes = { "application/json" } + ) + + ResponseEntity createChat( + @Parameter(name = "CreateChatDTO", description = "", required = true) @Valid @RequestBody ChatDTO chatDTO, @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * GET /api/v1/chats/{chat_id} : Получить доступный чат + * + * @param chatId (required) + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "getChatDTO", + summary = "Получить доступный чат", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats/{chat_id}", + produces = { "application/json" } + ) + + ResponseEntity getChat( + @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) @PathVariable("chat_id") UUID chatId, + @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * GET /api/v1/chats : Чаты текущего пользователя + * + * @param limit (optional, default to 50) + * @param cursor (optional) + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "listChats", + summary = "Чаты текущего пользователя", + tags = { "Chats" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ChatPageDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats", + produces = { "application/json" } + ) + + ResponseEntity listChats( + @Min(1) @Max(100) @Parameter(name = "limit", description = "", in = ParameterIn.QUERY) @Valid @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit, + @Size(min = 1) @Parameter(name = "cursor", description = "", in = ParameterIn.QUERY) @Valid @RequestParam(value = "cursor", required = false) String cursor, + @AuthenticationPrincipal SessionPrincipal principal + ); + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/HealthApi.java b/src/main/java/ru/mtusi/messenger/controller/HealthApi.java new file mode 100644 index 00000000..3c4f69f5 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/HealthApi.java @@ -0,0 +1,89 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.annotation.Generated; +import ru.mtusi.messenger.dto.HealthDTO; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Health", description = "Проверки живости и готовности процесса. Публичные, без аутентификации.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface HealthApi { + + /** + * GET /health/live : Процесс жив + * + * @return Успех (status code 200) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "liveness", + summary = "Процесс жив", + tags = { "Health" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/health/live", + produces = { "application/json" } + ) + + ResponseEntity liveness( + + ); + + + /** + * GET /health/ready : Готов принимать трафик + * + * @return Успех (status code 200) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "readiness", + summary = "Готов принимать трафик", + tags = { "Health" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)) + }) + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/health/ready", + produces = { "application/json" } + ) + + ResponseEntity readiness( + + ); + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/HealthController.java b/src/main/java/ru/mtusi/messenger/controller/HealthController.java new file mode 100644 index 00000000..d5b8bb7c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/HealthController.java @@ -0,0 +1,24 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.HealthDTO; +import ru.mtusi.messenger.service.HealthService; + +@RestController +@RequiredArgsConstructor +public class HealthController implements HealthApi { + + private final HealthService healthService; + + @Override + public ResponseEntity liveness() { + return ResponseEntity.ok(healthService.liveness()); + } + + @Override + public ResponseEntity readiness() { + return ResponseEntity.ok(healthService.readiness()); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/MessageController.java b/src/main/java/ru/mtusi/messenger/controller/MessageController.java new file mode 100644 index 00000000..11fc588d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/MessageController.java @@ -0,0 +1,30 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.CreateMessageDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.dto.MessagePageDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.MessageService; + +import java.util.UUID; + +@RestController +@RequiredArgsConstructor +public class MessageController implements MessagesApi { + private final MessageService messageService; + + @Override + public ResponseEntity createMessage(UUID chatId, CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, createMessageDTO)); + } + + @Override + public ResponseEntity listMessages(UUID chatId, Integer limit, String cursor, @AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(messageService.listMessages(principal.userId(), chatId, limit, cursor)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java new file mode 100644 index 00000000..2d59677c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/MessagesApi.java @@ -0,0 +1,136 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import ru.mtusi.messenger.dto.CreateMessageDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.MessagePageDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import java.util.UUID; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import jakarta.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Messages", description = "Отправка и чтение сообщений внутри доступного чата.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface MessagesApi { + + @Operation( + operationId = "createMessage", + summary = "Отправить сообщение", + tags = { "Messages" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = MessageDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/chats/{chat_id}/messages", + produces = { "application/json" }, + consumes = { "application/json" } + ) + ResponseEntity createMessage( + @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) + @PathVariable("chat_id") UUID chatId, + @Parameter(name = "CreateMessageDTO", description = "", required = true) + @Valid @RequestBody CreateMessageDTO createMessageDTO, + @AuthenticationPrincipal SessionPrincipal principal + ); + + @Operation( + operationId = "listMessages", + summary = "Сообщения по (created_at, id) по возрастанию", + tags = { "Messages" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = MessagePageDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/chats/{chat_id}/messages", + produces = { "application/json" } + ) + ResponseEntity listMessages( + @Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH) + @PathVariable("chat_id") UUID chatId, + @Min(1) @Max(100) + @Parameter(name = "limit", description = "", in = ParameterIn.QUERY) + @Valid @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit, + @Size(min = 1) + @Parameter(name = "cursor", description = "", in = ParameterIn.QUERY) + @Valid @RequestParam(value = "cursor", required = false) String cursor, + @AuthenticationPrincipal SessionPrincipal principal + ); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/UserController.java b/src/main/java/ru/mtusi/messenger/controller/UserController.java new file mode 100644 index 00000000..bf4a5907 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/UserController.java @@ -0,0 +1,26 @@ +package ru.mtusi.messenger.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.RestController; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.security.SessionPrincipal; +import ru.mtusi.messenger.service.UserService; + +@RestController +@RequiredArgsConstructor +public class UserController implements UsersApi { + private final UserService userService; + + @Override + public ResponseEntity currentUser(@AuthenticationPrincipal SessionPrincipal principal) { + return ResponseEntity.ok(userService.currentUser(principal.userId())); + } + + @Override + public ResponseEntity registerUser(UserDTO userDTO) { + return ResponseEntity.status(HttpStatus.CREATED).body(userService.registerUser(userDTO)); + } +} diff --git a/src/main/java/ru/mtusi/messenger/controller/UsersApi.java b/src/main/java/ru/mtusi/messenger/controller/UsersApi.java new file mode 100644 index 00000000..7e97abac --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/UsersApi.java @@ -0,0 +1,136 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.10.0). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package ru.mtusi.messenger.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.UserDTO; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import jakarta.validation.Valid; +import jakarta.annotation.Generated; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +@Validated +@Tag(name = "Users", description = "Регистрация пользователей и доступ к профилю текущего пользователя.") +@RequestMapping("${openapi.mTUSIMessenger2.base-path:}") +public interface UsersApi { + + /** + * GET /api/v1/users/me : Текущий пользователь + * + * @return Успех (status code 200) + * or Неверный запрос (status code 400) + * or Нет действительной аутентификации (status code 401) + * or Объект отсутствует или недоступен (status code 404) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "currentUser", + summary = "Текущий пользователь", + tags = { "Users" }, + responses = { + @ApiResponse(responseCode = "200", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + }, + security = { + @SecurityRequirement(name = "bearerAuth") + } + ) + @RequestMapping( + method = RequestMethod.GET, + value = "/api/v1/users/me", + produces = { "application/json" } + ) + + ResponseEntity currentUser( + @AuthenticationPrincipal SessionPrincipal principal + ); + + + /** + * POST /api/v1/users : Создать пользователя + * + * @param userDTO (required) + * @return Успех (status code 201) + * or Неверный запрос (status code 400) + * or Конфликт (status code 409) + * or Ограничение частоты запросов (status code 429) + * or Зависимость недоступна (status code 503) + * or Неожиданная ошибка без внутренних деталей (status code 500) + */ + @Operation( + operationId = "registerUser", + summary = "Создать пользователя", + tags = { "Users" }, + responses = { + @ApiResponse(responseCode = "201", description = "Успех", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDTO.class)) + }), + @ApiResponse(responseCode = "400", description = "Неверный запрос", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "409", description = "Конфликт", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }), + @ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class)) + }) + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/api/v1/users", + produces = { "application/json" }, + consumes = { "application/json" } + ) + + ResponseEntity registerUser( + @Parameter(name = "UserDTO", description = "", required = true) @Valid @RequestBody UserDTO userDTO + ); + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java b/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java new file mode 100644 index 00000000..46a10d19 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/controller/controllerAdvice/GlobalExceptionHandler.java @@ -0,0 +1,147 @@ +package ru.mtusi.messenger.controller.controllerAdvice; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.ConstraintViolationException; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.HandlerMethodValidationException; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import ru.mtusi.messenger.config.properties.RateLimitProperties; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import ru.mtusi.messenger.exception.*; + +@RestControllerAdvice +@RequiredArgsConstructor +public class GlobalExceptionHandler { + private final RateLimitProperties limitProperties; + private final ApiErrorFactory errors; + + @ExceptionHandler(InvalidRequestException.class) + public ResponseEntity invalidRequest(InvalidRequestException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, e.getMessage(), req); + } + + @ExceptionHandler(UnauthorizedException.class) + public ResponseEntity unauthorized(UnauthorizedException e, HttpServletRequest req) { + String scheme = req.getRequestURI().equals("/api/v1/auth/sessions") + ? "Basic" : "Bearer"; + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .header("WWW-Authenticate", scheme + " realm=\"messenger\"") + .body(errors.error(ErrorErrorDTO.CodeEnum.UNAUTHORIZED, e.getMessage(), req)); + } + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity notFound(NotFoundException e, HttpServletRequest req) { + return respond(HttpStatus.NOT_FOUND, ErrorErrorDTO.CodeEnum.NOT_FOUND, e.getMessage(), req); + } + + @ExceptionHandler(ConflictException.class) + public ResponseEntity conflict(ConflictException e, HttpServletRequest req) { + return respond(HttpStatus.CONFLICT, ErrorErrorDTO.CodeEnum.CONFLICT, e.getMessage(), req); + } + + @ExceptionHandler(PayloadTooLargeException.class) + public ResponseEntity payloadTooLarge(PayloadTooLargeException e, HttpServletRequest req) { + return respond(HttpStatus.PAYLOAD_TOO_LARGE, ErrorErrorDTO.CodeEnum.PAYLOAD_TOO_LARGE, e.getMessage(), req); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity validation(MethodArgumentNotValidException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Validation failed", req); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity unreadable(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Malformed request body", req); + } + + @ExceptionHandler(MissingServletRequestParameterException.class) + public ResponseEntity missingParam(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Missing parameter", req); + } + + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity typeMismatch(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Invalid parameter type", req); + } + + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public ResponseEntity mediaType(Exception e, HttpServletRequest req) { + return respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE, + "Unsupported media type", req); + } + + @ExceptionHandler(HandlerMethodValidationException.class) + public ResponseEntity methodValidation(Exception e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Validation failed", req); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public ResponseEntity methodNotAllowed(Exception e, HttpServletRequest req) { + return respond(HttpStatus.METHOD_NOT_ALLOWED, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Method not allowed", req); + } + + @ExceptionHandler(RateLimitedException.class) + public ResponseEntity rateLimited(RateLimitedException e, HttpServletRequest req) { + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .header("Retry-After", String.valueOf(limitProperties.retryAfterSeconds())) + .body(errors.error(ErrorErrorDTO.CodeEnum.RATE_LIMITED, e.getMessage(), req)); + } + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity constraint(ConstraintViolationException e, HttpServletRequest req) { + return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, + "Validation failed", req); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity fallback(Exception e, HttpServletRequest req) { + return respond(HttpStatus.INTERNAL_SERVER_ERROR, ErrorErrorDTO.CodeEnum.INTERNAL_ERROR, + "Internal error", req); + } + + @ExceptionHandler(ServiceUnavailableException.class) + public ResponseEntity serviceUnavailable(ServiceUnavailableException e, HttpServletRequest req) { + return respond(HttpStatus.SERVICE_UNAVAILABLE, + ErrorErrorDTO.CodeEnum.UNAVAILABLE, + e.getMessage(), req); + } + + @ExceptionHandler({ + CannotCreateTransactionException.class, + DataAccessResourceFailureException.class + }) + public ResponseEntity dependencyUnavailable(Exception e, HttpServletRequest req) { + return respond(HttpStatus.SERVICE_UNAVAILABLE, + ErrorErrorDTO.CodeEnum.UNAVAILABLE, + "Dependency unavailable", req); + } + + @ExceptionHandler(DataAccessException.class) + public ResponseEntity dataAccess(DataAccessException e, HttpServletRequest req) { + return respond(HttpStatus.INTERNAL_SERVER_ERROR, + ErrorErrorDTO.CodeEnum.INTERNAL_ERROR, + "Database error", req); + } + + private ResponseEntity respond(HttpStatus status, + ErrorErrorDTO.CodeEnum code, + String message, + HttpServletRequest req) { + return ResponseEntity.status(status).body(errors.error(code, message, req)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java new file mode 100644 index 00000000..f1c436fe --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ChatDTO.java @@ -0,0 +1,149 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import java.time.Instant; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.UUID; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; +import jakarta.annotation.Generated; +import org.hibernate.validator.constraints.CodePointLength; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0") +public class ChatDTO { + + private UUID id; + + private String title; + + @Valid + private List memberIds = new ArrayList<>(); + + private Instant createdAt; + + public ChatDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ChatDTO(String title, List memberIds) { + this.title = title; + this.memberIds = memberIds; + } + + public ChatDTO id(UUID id) { + this.id = id; + return this; + } + + @Valid + @Schema(name = "id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("id") + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public ChatDTO title(String title) { + this.title = title; + return this; + } + + @NotNull + @CodePointLength(min = 1, max = 100) + @Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("title") + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public ChatDTO memberIds(List memberIds) { + this.memberIds = memberIds; + return this; + } + + public ChatDTO addMemberIdsItem(UUID memberIdsItem) { + if (this.memberIds == null) { + this.memberIds = new ArrayList<>(); + } + this.memberIds.add(memberIdsItem); + return this; + } + + @NotNull @Valid @Size(min = 1, max = 100) + @Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("member_ids") + public List getMemberIds() { + return memberIds; + } + + public void setMemberIds(List memberIds) { + this.memberIds = memberIds; + } + + public ChatDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ChatDTO createChat = (ChatDTO) o; + return Objects.equals(this.id, createChat.id) && + Objects.equals(this.title, createChat.title) && + Objects.equals(this.memberIds, createChat.memberIds) && + Objects.equals(this.createdAt, createChat.createdAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, title, memberIds, createdAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ChatDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" title: ").append(toIndentedString(title)).append("\n"); + sb.append(" memberIds: ").append(toIndentedString(memberIds)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java b/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java new file mode 100644 index 00000000..240e39f3 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ChatPageDTO.java @@ -0,0 +1,124 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.ArrayList; +import java.util.List; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * ChatPageDTO + */ + +public class ChatPageDTO { + + @Valid + private List<@Valid ChatDTO> items = new ArrayList<>(); + + private String nextCursor = null; + + public ChatPageDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ChatPageDTO(List<@Valid ChatDTO> items, String nextCursor) { + this.items = items; + this.nextCursor = nextCursor; + } + + public ChatPageDTO items(List<@Valid ChatDTO> items) { + this.items = items; + return this; + } + + public ChatPageDTO addItemsItem(ChatDTO itemsItem) { + if (this.items == null) { + this.items = new ArrayList<>(); + } + this.items.add(itemsItem); + return this; + } + + /** + * Get items + * @return items + */ + @NotNull @Valid + @Schema(name = "items", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("items") + public List<@Valid ChatDTO> getItems() { + return items; + } + + public void setItems(List<@Valid ChatDTO> items) { + this.items = items; + } + + public ChatPageDTO nextCursor(String nextCursor) { + this.nextCursor = nextCursor; + return this; + } + + /** + * Get nextCursor + * @return nextCursor + */ + @JsonInclude(JsonInclude.Include.ALWAYS) + @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("next_cursor") + public String getNextCursor() { + return nextCursor; + } + + public void setNextCursor(String nextCursor) { + this.nextCursor = nextCursor; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ChatPageDTO chatPageDTO = (ChatPageDTO) o; + return Objects.equals(this.items, chatPageDTO.items) && + Objects.equals(this.nextCursor, chatPageDTO.nextCursor); + } + + @Override + public int hashCode() { + return Objects.hash(items, nextCursor); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ChatPageDTO {\n"); + sb.append(" items: ").append(toIndentedString(items)).append("\n"); + sb.append(" nextCursor: ").append(toIndentedString(nextCursor)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java new file mode 100644 index 00000000..718cb0f3 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/CreateMessageDTO.java @@ -0,0 +1,40 @@ +package ru.mtusi.messenger.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import org.hibernate.validator.constraints.CodePointLength; + +import java.util.Objects; + +@Schema(name = "CreateMessage") +public class CreateMessageDTO { + + private String text; + + public CreateMessageDTO() {} + + public CreateMessageDTO text(String text) { + this.text = text; + return this; + } + + @NotNull + @CodePointLength(min = 1, max = 4000) + @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("text") + public String getText() { return text; } + + public void setText(String text) { this.text = text; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CreateMessageDTO d)) return false; + return Objects.equals(text, d.text); + } + + @Override + public int hashCode() { return Objects.hash(text); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java b/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java new file mode 100644 index 00000000..65c09ca9 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ErrorDTO.java @@ -0,0 +1,87 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * ErrorDTO + */ + +public class ErrorDTO { + + private ErrorErrorDTO error; + + public ErrorDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ErrorDTO(ErrorErrorDTO error) { + this.error = error; + } + + public ErrorDTO error(ErrorErrorDTO error) { + this.error = error; + return this; + } + + /** + * Get error + * @return error + */ + @NotNull @Valid + @Schema(name = "error", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("error") + public ErrorErrorDTO getError() { + return error; + } + + public void setError(ErrorErrorDTO error) { + this.error = error; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ErrorDTO errorDTO = (ErrorDTO) o; + return Objects.equals(this.error, errorDTO.error); + } + + @Override + public int hashCode() { + return Objects.hash(error); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ErrorDTO {\n"); + sb.append(" error: ").append(toIndentedString(error)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java b/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java new file mode 100644 index 00000000..6804918b --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/ErrorErrorDTO.java @@ -0,0 +1,178 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * ErrorErrorDTO + */ + +public class ErrorErrorDTO { + + /** + * Gets or Sets code + */ + public enum CodeEnum { + INVALID_REQUEST("invalid_request"), + UNAUTHORIZED("unauthorized"), + NOT_FOUND("not_found"), + CONFLICT("conflict"), + PAYLOAD_TOO_LARGE("payload_too_large"), + UNSUPPORTED_MEDIA_TYPE("unsupported_media_type"), + RATE_LIMITED("rate_limited"), + UNAVAILABLE("unavailable"), + INTERNAL_ERROR("internal_error"); + + private String value; + + CodeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static CodeEnum fromValue(String value) { + for (CodeEnum b : CodeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private CodeEnum code; + + private String message; + + private String requestId; + + public ErrorErrorDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public ErrorErrorDTO(CodeEnum code, String message, String requestId) { + this.code = code; + this.message = message; + this.requestId = requestId; + } + + public ErrorErrorDTO code(CodeEnum code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + */ + @NotNull + @Schema(name = "code", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("code") + public CodeEnum getCode() { + return code; + } + + public void setCode(CodeEnum code) { + this.code = code; + } + + public ErrorErrorDTO message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + */ + @NotNull @Size(min = 1) + @Schema(name = "message", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("message") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public ErrorErrorDTO requestId(String requestId) { + this.requestId = requestId; + return this; + } + + /** + * Get requestId + * @return requestId + */ + @NotNull @Size(min = 1) + @Schema(name = "request_id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("request_id") + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ErrorErrorDTO errorErrorDTO = (ErrorErrorDTO) o; + return Objects.equals(this.code, errorErrorDTO.code) && + Objects.equals(this.message, errorErrorDTO.message) && + Objects.equals(this.requestId, errorErrorDTO.requestId); + } + + @Override + public int hashCode() { + return Objects.hash(code, message, requestId); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ErrorErrorDTO {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append(" requestId: ").append(toIndentedString(requestId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java b/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java new file mode 100644 index 00000000..bd428131 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/HealthDTO.java @@ -0,0 +1,120 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * HealthDTO + */ + +public class HealthDTO { + + /** + * Gets or Sets status + */ + public enum StatusEnum { + OK("ok"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private StatusEnum status; + + public HealthDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public HealthDTO(StatusEnum status) { + this.status = status; + } + + public HealthDTO status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @NotNull + @Schema(name = "status", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HealthDTO healthDTO = (HealthDTO) o; + return Objects.equals(this.status, healthDTO.status); + } + + @Override + public int hashCode() { + return Objects.hash(status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthDTO {\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java new file mode 100644 index 00000000..703b3acd --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/MessageDTO.java @@ -0,0 +1,189 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; +import org.hibernate.validator.constraints.CodePointLength; + +import java.time.Instant; +import java.util.UUID; + +/** + * MessageDTO + */ + +public class MessageDTO { + + private UUID id; + + private UUID chatId; + + private UUID senderId; + + private String text; + + private Instant createdAt; + + public MessageDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public MessageDTO(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) { + this.id = id; + this.chatId = chatId; + this.senderId = senderId; + this.text = text; + this.createdAt = createdAt; + } + + public MessageDTO id(UUID id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @NotNull @Valid + @Schema(name = "id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("id") + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public MessageDTO chatId(UUID chatId) { + this.chatId = chatId; + return this; + } + + /** + * Get chatId + * @return chatId + */ + @NotNull @Valid + @Schema(name = "chat_id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("chat_id") + public UUID getChatId() { + return chatId; + } + + public void setChatId(UUID chatId) { + this.chatId = chatId; + } + + public MessageDTO senderId(UUID senderId) { + this.senderId = senderId; + return this; + } + + /** + * Get senderId + * @return senderId + */ + @NotNull @Valid + @Schema(name = "sender_id", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("sender_id") + public UUID getSenderId() { + return senderId; + } + + public void setSenderId(UUID senderId) { + this.senderId = senderId; + } + + public MessageDTO text(String text) { + this.text = text; + return this; + } + + /** + * Get text + * @return text + */ + @NotNull + @CodePointLength(min = 1, max = 4000) + @Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("text") + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public MessageDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * Get createdAt + * @return createdAt + */ + @NotNull @Valid + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MessageDTO messageDTO = (MessageDTO) o; + return Objects.equals(this.id, messageDTO.id) && + Objects.equals(this.chatId, messageDTO.chatId) && + Objects.equals(this.senderId, messageDTO.senderId) && + Objects.equals(this.text, messageDTO.text) && + Objects.equals(this.createdAt, messageDTO.createdAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, chatId, senderId, text, createdAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MessageDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" chatId: ").append(toIndentedString(chatId)).append("\n"); + sb.append(" senderId: ").append(toIndentedString(senderId)).append("\n"); + sb.append(" text: ").append(toIndentedString(text)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java b/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java new file mode 100644 index 00000000..2c44c67e --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/MessagePageDTO.java @@ -0,0 +1,125 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.ArrayList; +import java.util.List; +import ru.mtusi.messenger.dto.MessageDTO; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * MessagePageDTO + */ + +public class MessagePageDTO { + + @Valid + private List<@Valid MessageDTO> items = new ArrayList<>(); + + private String nextCursor = null; + + public MessagePageDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public MessagePageDTO(List<@Valid MessageDTO> items, String nextCursor) { + this.items = items; + this.nextCursor = nextCursor; + } + + public MessagePageDTO items(List<@Valid MessageDTO> items) { + this.items = items; + return this; + } + + public MessagePageDTO addItemsItem(MessageDTO itemsItem) { + if (this.items == null) { + this.items = new ArrayList<>(); + } + this.items.add(itemsItem); + return this; + } + + /** + * Get items + * @return items + */ + @NotNull @Valid + @Schema(name = "items", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("items") + public List<@Valid MessageDTO> getItems() { + return items; + } + + public void setItems(List<@Valid MessageDTO> items) { + this.items = items; + } + + public MessagePageDTO nextCursor(String nextCursor) { + this.nextCursor = nextCursor; + return this; + } + + /** + * Get nextCursor + * @return nextCursor + */ + @JsonInclude(JsonInclude.Include.ALWAYS) + @Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("next_cursor") + public String getNextCursor() { + return nextCursor; + } + + public void setNextCursor(String nextCursor) { + this.nextCursor = nextCursor; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MessagePageDTO messagePageDTO = (MessagePageDTO) o; + return Objects.equals(this.items, messagePageDTO.items) && + Objects.equals(this.nextCursor, messagePageDTO.nextCursor); + } + + @Override + public int hashCode() { + return Objects.hash(items, nextCursor); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MessagePageDTO {\n"); + sb.append(" items: ").append(toIndentedString(items)).append("\n"); + sb.append(" nextCursor: ").append(toIndentedString(nextCursor)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java b/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java new file mode 100644 index 00000000..bc1f0772 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/SessionDTO.java @@ -0,0 +1,198 @@ +package ru.mtusi.messenger.dto; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.Instant; +import ru.mtusi.messenger.dto.UserDTO; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.*; + +/** + * SessionDTO + */ + +public class SessionDTO { + + private String token; + + /** + * Gets or Sets tokenType + */ + public enum TokenTypeEnum { + BEARER("Bearer"); + + private String value; + + TokenTypeEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TokenTypeEnum fromValue(String value) { + for (TokenTypeEnum b : TokenTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private TokenTypeEnum tokenType; + + private Instant expiresAt; + + private UserDTO user; + + public SessionDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public SessionDTO(String token, TokenTypeEnum tokenType, Instant expiresAt, UserDTO user) { + this.token = token; + this.tokenType = tokenType; + this.expiresAt = expiresAt; + this.user = user; + } + + public SessionDTO token(String token) { + this.token = token; + return this; + } + + /** + * Get token + * @return token + */ + @NotNull @Size(min = 32) + @Schema(name = "token", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("token") + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public SessionDTO tokenType(TokenTypeEnum tokenType) { + this.tokenType = tokenType; + return this; + } + + /** + * Get tokenType + * @return tokenType + */ + @NotNull + @Schema(name = "token_type", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("token_type") + public TokenTypeEnum getTokenType() { + return tokenType; + } + + public void setTokenType(TokenTypeEnum tokenType) { + this.tokenType = tokenType; + } + + public SessionDTO expiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + return this; + } + + /** + * Get expiresAt + * @return expiresAt + */ + @NotNull @Valid + @Schema(name = "expires_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("expires_at") + public Instant getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + } + + public SessionDTO user(UserDTO user) { + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @NotNull @Valid + @Schema(name = "user", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("user") + public UserDTO getUser() { + return user; + } + + public void setUser(UserDTO user) { + this.user = user; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SessionDTO sessionDTO = (SessionDTO) o; + return Objects.equals(this.token, sessionDTO.token) && + Objects.equals(this.tokenType, sessionDTO.tokenType) && + Objects.equals(this.expiresAt, sessionDTO.expiresAt) && + Objects.equals(this.user, sessionDTO.user); + } + + @Override + public int hashCode() { + return Objects.hash(token, tokenType, expiresAt, user); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SessionDTO {\n"); + sb.append(" token: ").append(toIndentedString(token)).append("\n"); + sb.append(" tokenType: ").append(toIndentedString(tokenType)).append("\n"); + sb.append(" expiresAt: ").append(toIndentedString(expiresAt)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/dto/UserDTO.java b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java new file mode 100644 index 00000000..85976360 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/dto/UserDTO.java @@ -0,0 +1,183 @@ +package ru.mtusi.messenger.dto; + +import java.time.Instant; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.Valid; +import jakarta.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; +import org.hibernate.validator.constraints.CodePointLength; + +import java.util.*; + +/** + * UserDTO + */ + +public class UserDTO { + + private UUID id; + + private String username; + + private String displayName; + + private String password; + + private Instant createdAt; + + public UserDTO() { + super(); + } + + /** + * Constructor with only required parameters + */ + public UserDTO(String username, String displayName, String password) { + this.username = username; + this.displayName = displayName; + this.password = password; + } + + public UserDTO username(String username) { + this.username = username; + return this; + } + + @Valid + @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("id") + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UserDTO id(UUID id) { + this.id = id; + return this; + } + + /** + * Get username + * @return username + */ + @NotNull @Pattern(regexp = "^[a-z0-9_]{3,32}$") + @Schema(name = "username", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("username") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public UserDTO displayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get displayName + * @return displayName + */ + @NotNull + @CodePointLength(min = 1, max = 100) + @Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("display_name") + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public UserDTO password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + */ + @NotNull + @CodePointLength(min = 1, max = 100) + @Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("password") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public UserDTO createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * Get createdAt + * @return createdAt + */ + @Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("created_at") + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserDTO userDTO = (UserDTO) o; + return Objects.equals(this.id, userDTO.id) && + Objects.equals(this.username, userDTO.username) && + Objects.equals(this.displayName, userDTO.displayName) && + Objects.equals(this.password, userDTO.password) && + Objects.equals(this.createdAt, userDTO.createdAt); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, displayName, password, createdAt); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserDTO {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java b/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java new file mode 100644 index 00000000..26b98d56 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ApiErrorFactory.java @@ -0,0 +1,74 @@ +package ru.mtusi.messenger.exception; + +import tools.jackson.databind.ObjectMapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.slf4j.MDC; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ErrorDTO; +import ru.mtusi.messenger.dto.ErrorErrorDTO; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +@Component +@RequiredArgsConstructor +public class ApiErrorFactory { + private static final String DEFAULT_MESSAGE = "Error"; + private static final String REQUEST_ID_ATTR = "requestId"; + private static final String REQUEST_ID_MDC = "requestId"; + + private final ObjectMapper objectMapper; + + public ErrorDTO error(ErrorErrorDTO.CodeEnum code, String message, HttpServletRequest request) { + ErrorErrorDTO inner = new ErrorErrorDTO(); + inner.setCode(code); + inner.setMessage(normalizeMessage(message)); + inner.setRequestId(resolveRequestId(request)); + + ErrorDTO outer = new ErrorDTO(); + outer.setError(inner); + return outer; + } + + public void writeError(HttpServletResponse response, + HttpServletRequest request, + HttpStatus status, + String wwwAuthenticate, + ErrorErrorDTO.CodeEnum code, + String message) throws IOException { + String requestId = resolveRequestId(request); + response.setStatus(status.value()); + response.setHeader("X-Request-Id", requestId); + if (wwwAuthenticate != null) { + response.setHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); + } + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + objectMapper.writeValue(response.getWriter(), error(code, message, request)); + } + + public String resolveRequestId(HttpServletRequest request) { + Object attr = request.getAttribute(REQUEST_ID_ATTR); + if (attr instanceof String s && !s.isBlank()) { + return s; + } + String mdc = MDC.get(REQUEST_ID_MDC); + if (mdc != null && !mdc.isBlank()) { + request.setAttribute(REQUEST_ID_ATTR, mdc); + return mdc; + } + String generated = UUID.randomUUID().toString(); + request.setAttribute(REQUEST_ID_ATTR, generated); + return generated; + } + + private String normalizeMessage(String message) { + return (message == null || message.isBlank()) ? DEFAULT_MESSAGE : message; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/ConflictException.java b/src/main/java/ru/mtusi/messenger/exception/ConflictException.java new file mode 100644 index 00000000..aa0a2bff --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ConflictException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class ConflictException extends RuntimeException { + public ConflictException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java b/src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java new file mode 100644 index 00000000..a4d7792a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/InvalidRequestException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class InvalidRequestException extends RuntimeException { + public InvalidRequestException(String message) { super(message); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java b/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java new file mode 100644 index 00000000..6055db37 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/NotFoundException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class NotFoundException extends RuntimeException { + public NotFoundException(String message) { super(message); } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java b/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java new file mode 100644 index 00000000..2493a9eb --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/PayloadTooLargeException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class PayloadTooLargeException extends RuntimeException { + public PayloadTooLargeException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java b/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java new file mode 100644 index 00000000..3c1ab32b --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/RateLimitedException.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.exception; + +public class RateLimitedException extends RuntimeException { + public RateLimitedException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java b/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java new file mode 100644 index 00000000..da565290 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/ServiceUnavailableException.java @@ -0,0 +1,7 @@ +package ru.mtusi.messenger.exception; + +public class ServiceUnavailableException extends RuntimeException { + public ServiceUnavailableException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java b/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java new file mode 100644 index 00000000..a086273a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/exception/UnauthorizedException.java @@ -0,0 +1,5 @@ +package ru.mtusi.messenger.exception; + +public class UnauthorizedException extends RuntimeException { + public UnauthorizedException(String message) { super(message); } +} diff --git a/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java b/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java new file mode 100644 index 00000000..2476160b --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/RateLimitFilter.java @@ -0,0 +1,49 @@ +package ru.mtusi.messenger.filter; + +import io.github.bucket4j.Bucket; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import ru.mtusi.messenger.config.properties.RateLimitProperties; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import ru.mtusi.messenger.exception.ApiErrorFactory; + +import java.io.IOException; + +@Component +@Order(2) +@RequiredArgsConstructor +public class RateLimitFilter extends OncePerRequestFilter { + private final RateLimitProperties limitProperties; + private final Bucket bucket; + private final ApiErrorFactory errors; + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, + FilterChain chain) throws ServletException, IOException { + if (!req.getRequestURI().startsWith("/api/")) { + chain.doFilter(req, res); + return; + } + + if (bucket.tryConsume(1)) { + chain.doFilter(req, res); + return; + } + + res.setHeader("Retry-After", String.valueOf(limitProperties.retryAfterSeconds())); + errors.writeError( + res, + req, + HttpStatus.TOO_MANY_REQUESTS, + null, + ErrorErrorDTO.CodeEnum.RATE_LIMITED, + "Rate limit exceeded. Try again later."); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java b/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java new file mode 100644 index 00000000..54668db8 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/filter/RequestIdFilter.java @@ -0,0 +1,35 @@ +package ru.mtusi.messenger.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.MDC; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.UUID; + +@Component +@Order(1) +public class RequestIdFilter extends OncePerRequestFilter { + + public static final String INSTANCE_ID = UUID.randomUUID().toString(); + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, + FilterChain chain) throws ServletException, IOException { + String rid = UUID.randomUUID().toString(); + res.setHeader("X-Request-Id", rid); + res.setHeader("X-Instance-Id", INSTANCE_ID); + req.setAttribute("requestId", rid); + MDC.put("requestId", rid); + try { + chain.doFilter(req, res); + } finally { + MDC.clear(); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java new file mode 100644 index 00000000..012a5d73 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/ChatMapper.java @@ -0,0 +1,34 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Named; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.User; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Mapper(componentModel = "spring") +public interface ChatMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "members", ignore = true) + @Mapping(target = "messages", ignore = true) + Chat toChat(ChatDTO dto); + + @Mapping(target = "memberIds", source = "members", qualifiedByName = "usersToIds") + ChatDTO toChatDto(Chat chat); + + @Named("usersToIds") + default List usersToIds(Set users) { + if (users == null) return new ArrayList<>(); + List ids = new ArrayList<>(users.size()); + for (User u : users) ids.add(u.getId()); + return ids; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java new file mode 100644 index 00000000..393f23e4 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/MessageMapper.java @@ -0,0 +1,23 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import ru.mtusi.messenger.dto.CreateMessageDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.model.Message; + +@Mapper(componentModel = "spring") +public interface MessageMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "chat", ignore = true) + @Mapping(target = "sender", ignore = true) + @Mapping(target = "createdAt", ignore = true) + Message toMessage(MessageDTO dto); + + @Mapping(target = "chatId", source = "chat.id") + @Mapping(target = "senderId", source = "sender.id") + MessageDTO toMessageDTO(Message entity); + + Message toMessage(CreateMessageDTO dto); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java b/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java new file mode 100644 index 00000000..83478e43 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/SessionMapper.java @@ -0,0 +1,17 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.model.Session; + +@Mapper(componentModel = "spring") +public interface SessionMapper { + + @Mapping(target = "token", source = "tokenRaw") + @Mapping(target = "tokenType", expression = "java(ru.mtusi.messenger.dto.SessionDTO.TokenTypeEnum.BEARER)") + @Mapping(target = "expiresAt", source = "session.expiresAt") + @Mapping(target = "user", source = "userDTO") + SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java b/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java new file mode 100644 index 00000000..74380480 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/mapper/UserMapper.java @@ -0,0 +1,20 @@ +package ru.mtusi.messenger.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.model.User; + +@Mapper(componentModel = "spring") +public interface UserMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "passwordHash", ignore = true) + @Mapping(target = "chats", ignore = true) + @Mapping(target = "messages", ignore = true) + User toUser(UserDTO dto); + + @Mapping(target = "password", ignore = true) + UserDTO toUserDto(User user); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Chat.java b/src/main/java/ru/mtusi/messenger/model/Chat.java new file mode 100644 index 00000000..9fbb85f2 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Chat.java @@ -0,0 +1,53 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Entity +@Table(name = "chats") +@Getter +@Setter +@NoArgsConstructor +public class Chat { + + @Id + @Column(nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(nullable = false, length = 100) + private String title; + + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt; + + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable( + name = "chat_members", + joinColumns = @JoinColumn(name = "chat_id"), + inverseJoinColumns = @JoinColumn(name = "user_id") + ) + private Set members = new HashSet<>(); + + @OneToMany( + mappedBy = "chat", + fetch = FetchType.LAZY, + cascade = CascadeType.ALL, + orphanRemoval = true + ) + @OrderBy("createdAt ASC, id ASC") + private List messages = new ArrayList<>(); + + @PrePersist + private void onCreate() { + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Message.java b/src/main/java/ru/mtusi/messenger/model/Message.java new file mode 100644 index 00000000..b4a368d1 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Message.java @@ -0,0 +1,40 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Entity +@Table(name = "messages") +@Getter +@Setter +@NoArgsConstructor +public class Message { + + @Id + @Column(nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "chat_id", nullable = false) + private Chat chat; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "sender_id", nullable = false) + private User sender; + + @Column(nullable = false, length = 4000) + private String text; + + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt; + + @PrePersist + private void onCreate() { + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/Session.java b/src/main/java/ru/mtusi/messenger/model/Session.java new file mode 100644 index 00000000..4a2124dd --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/Session.java @@ -0,0 +1,42 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Entity +@Table(name = "sessions") +@Getter +@Setter +@NoArgsConstructor +public class Session { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(name = "user_id", nullable = false) + private UUID userId; + + @Column(name = "token_hash", nullable = false, unique = true) + private byte[] tokenHash; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + @Column(name = "expires_at", nullable = false) + private Instant expiresAt; + + @Column(name = "revoked_at") + private Instant revokedAt; + + @PrePersist + private void onCreate() { + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } + +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/model/User.java b/src/main/java/ru/mtusi/messenger/model/User.java new file mode 100644 index 00000000..21386805 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/model/User.java @@ -0,0 +1,48 @@ +package ru.mtusi.messenger.model; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +@Entity +@Table(name = "users") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class User{ + + @Id() + @Column(nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(nullable = false, unique = true, length = 32) + private String username; + + @Column(name = "display_name", nullable = false, length = 100) + private String displayName; + + @Column(name = "password_hash", nullable = false, length = 255) + private String passwordHash; + + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt; + + @ManyToMany(mappedBy = "members", fetch = FetchType.LAZY) + private Set chats = new HashSet<>(); + + @OneToMany(mappedBy = "sender", fetch = FetchType.LAZY) + private Set messages = new HashSet<>(); + + @PrePersist + private void onCreate() { + this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java b/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java new file mode 100644 index 00000000..0ed58876 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/ChatRepository.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.mtusi.messenger.model.Chat; + +import org.springframework.data.domain.Pageable; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public interface ChatRepository extends JpaRepository { + + @EntityGraph(attributePaths = "members") + @Query(""" + select distinct c from Chat c + join c.members m + where m.id = :userId + order by c.createdAt asc, c.id asc + """) + List findPageByMember(@Param("userId") UUID userId, + Pageable pageable); + + @EntityGraph(attributePaths = "members") + @Query(""" + select distinct c from Chat c + join c.members m + where m.id = :userId + and (c.createdAt > :cursorCreated + or (c.createdAt = :cursorCreated and c.id > :cursorId)) + order by c.createdAt asc, c.id asc + """) + List findPageByMemberAfterCursor(@Param("userId") UUID userId, + @Param("cursorCreated") Instant cursorCreated, + @Param("cursorId") UUID cursorId, + Pageable pageable); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java b/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java new file mode 100644 index 00000000..35134b4a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/MessageRepository.java @@ -0,0 +1,39 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.mtusi.messenger.model.Message; + +import org.springframework.data.domain.Pageable; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public interface MessageRepository extends JpaRepository { + + long countByChatId(UUID chatId); + + @EntityGraph(attributePaths = "sender") + @Query(""" + select m from Message m + where m.chat.id = :chatId + order by m.createdAt asc, m.id asc + """) + List findPageByChat(@Param("chatId") UUID chatId, + Pageable pageable); + + @EntityGraph(attributePaths = "sender") + @Query(""" + select m from Message m + where m.chat.id = :chatId + and (m.createdAt > :cursorCreated + or (m.createdAt = :cursorCreated and m.id > :cursorId)) + order by m.createdAt asc, m.id asc + """) + List findPageByChatAfterCursor(@Param("chatId") UUID chatId, + @Param("cursorCreated") Instant cursorCreated, + @Param("cursorId") UUID cursorId, + Pageable pageable); +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java b/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java new file mode 100644 index 00000000..2fc1dce7 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/SessionRepository.java @@ -0,0 +1,12 @@ +package ru.mtusi.messenger.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.mtusi.messenger.model.Session; + +import java.util.Optional; +import java.util.UUID; + +public interface SessionRepository extends JpaRepository { + Optional findByTokenHash(byte[] tokenHash); + +} diff --git a/src/main/java/ru/mtusi/messenger/repository/UserRepository.java b/src/main/java/ru/mtusi/messenger/repository/UserRepository.java new file mode 100644 index 00000000..9a9a6d4a --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/repository/UserRepository.java @@ -0,0 +1,23 @@ +package ru.mtusi.messenger.repository; + + +import jakarta.persistence.LockModeType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.mtusi.messenger.model.User; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +public interface UserRepository extends JpaRepository { + + Optional findByUsername(String username); + + @Lock(LockModeType.PESSIMISTIC_READ) + @Query("select u from User u where u.id in :ids") + Set findAllByIdForShare(@Param("ids") Set ids); +} diff --git a/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java b/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java new file mode 100644 index 00000000..e2f4d10f --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/ApiAuthenticationEntryPoint.java @@ -0,0 +1,32 @@ +package ru.mtusi.messenger.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ErrorErrorDTO; +import ru.mtusi.messenger.exception.ApiErrorFactory; + +import java.io.IOException; + +@Component +@RequiredArgsConstructor +public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint { + private final ApiErrorFactory errors; + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { + String scheme = request.getRequestURI().equals("/api/v1/auth/sessions") ? "Basic" : "Bearer"; + + errors.writeError( + response, + request, + HttpStatus.UNAUTHORIZED, + scheme + " realm=\"messenger\"", + ErrorErrorDTO.CodeEnum.UNAUTHORIZED, + "No valid authentication"); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java b/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java new file mode 100644 index 00000000..116ad7c0 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/BasicCredentials.java @@ -0,0 +1,28 @@ +package ru.mtusi.messenger.security; + +import ru.mtusi.messenger.exception.UnauthorizedException; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +public record BasicCredentials(String username, String password) { + + public static BasicCredentials parse(String header) { + if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) { + throw new UnauthorizedException("Basic authentication required"); + } + String decoded; + try { + decoded = new String( + Base64.getDecoder().decode(header.substring(6).trim()), + StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw new UnauthorizedException("Invalid Basic encoding"); + } + int i = decoded.indexOf(':'); + if (i < 0) { + throw new UnauthorizedException("Invalid Basic credentials"); + } + return new BasicCredentials(decoded.substring(0, i), decoded.substring(i + 1)); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java new file mode 100644 index 00000000..6bfe5d00 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationFilter.java @@ -0,0 +1,45 @@ +package ru.mtusi.messenger.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@RequiredArgsConstructor +public class SessionAuthenticationFilter extends OncePerRequestFilter { + private final BearerTokenResolver bearerTokenResolver; + private final AuthenticationManager authenticationManager; + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain chain) throws ServletException, IOException { + try { + String token = bearerTokenResolver.resolve(request); + if (token != null && !token.isBlank()) { + try { + Authentication auth = authenticationManager.authenticate( + new SessionAuthenticationToken(token)); + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(auth); + SecurityContextHolder.setContext(context); + } catch (AuthenticationException e) { + SecurityContextHolder.clearContext(); + } + } + chain.doFilter(request, response); + } finally { + SecurityContextHolder.clearContext(); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java new file mode 100644 index 00000000..d1d5ee56 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationProvider.java @@ -0,0 +1,33 @@ +package ru.mtusi.messenger.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.service.SessionService; + +@Component +@RequiredArgsConstructor +public class SessionAuthenticationProvider implements AuthenticationProvider { + private final SessionService sessionService; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String token = (String) authentication.getCredentials(); + try { + var rec = sessionService.requireActive(token); + return new SessionAuthenticationToken( + new SessionPrincipal(rec.userId(), rec.sessionId())); + } catch (UnauthorizedException e) { + throw new BadCredentialsException(e.getMessage(), e); + } + } + + @Override + public boolean supports(Class authentication) { + return SessionAuthenticationToken.class.isAssignableFrom(authentication); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java new file mode 100644 index 00000000..f5e9977d --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionAuthenticationToken.java @@ -0,0 +1,34 @@ +package ru.mtusi.messenger.security; + +import org.springframework.security.authentication.AbstractAuthenticationToken; + +import java.util.List; + +public class SessionAuthenticationToken extends AbstractAuthenticationToken { + private final String rawToken; + private final SessionPrincipal principal; + + public SessionAuthenticationToken(String rawToken) { + super(List.of()); + this.rawToken = rawToken; + this.principal = null; + setAuthenticated(false); + } + + public SessionAuthenticationToken(SessionPrincipal principal) { + super(List.of()); + this.rawToken = null; + this.principal = principal; + setAuthenticated(true); + } + + @Override + public Object getCredentials() { + return rawToken; + } + + @Override + public Object getPrincipal() { + return principal; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java b/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java new file mode 100644 index 00000000..8bcae0eb --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/security/SessionPrincipal.java @@ -0,0 +1,6 @@ +package ru.mtusi.messenger.security; + +import java.util.UUID; + +public record SessionPrincipal(UUID userId, UUID sessionId) { +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/AuthService.java b/src/main/java/ru/mtusi/messenger/service/AuthService.java new file mode 100644 index 00000000..04d5b683 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/AuthService.java @@ -0,0 +1,32 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.security.BasicCredentials; +import ru.mtusi.messenger.security.SessionPrincipal; + +@Service +@RequiredArgsConstructor +public class AuthService { + private final UserService userService; + private final SessionService sessionService; + + public SessionDTO login(String authorizationHeader) { + var creds = BasicCredentials.parse(authorizationHeader); + UserDTO userDTO = userService.authenticate(creds.username(), creds.password()); + return sessionService.createSession(userDTO); + } + + public void logout() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || !(auth.getPrincipal() instanceof SessionPrincipal sp)) { + throw new UnauthorizedException("No active session"); + } + sessionService.revoke(sp.sessionId()); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/ChatService.java b/src/main/java/ru/mtusi/messenger/service/ChatService.java new file mode 100644 index 00000000..c8b69b7b --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/ChatService.java @@ -0,0 +1,129 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.dto.ChatPageDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.mapper.ChatMapper; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.ChatRepository; +import ru.mtusi.messenger.validation.ChatValidator; +import ru.mtusi.messenger.util.CursorCodec; + +import java.util.*; + +@Service +@Slf4j +@RequiredArgsConstructor +public class ChatService { + private final ChatMapper chatMapper; + private final ChatValidator chatValidator; + private final ChatRepository chatRepository; + + @Transactional + public ChatDTO createChat(UUID caller, ChatDTO chatDTO) { + Set members = chatValidator.validateCreate(caller, chatDTO); + Chat chat = buildChat(chatDTO, members); + chat = persistChat(chat); + return chatMapper.toChatDto(chat); + } + + private Chat buildChat(ChatDTO chatDTO, Set members) { + Chat chat = chatMapper.toChat(chatDTO); + chat.setMembers(members); + return chat; + } + + private Chat persistChat(Chat chat) { + try { + return chatRepository.saveAndFlush(chat); + } catch (DataIntegrityViolationException e) { + throw new InvalidRequestException("Cannot create chat: invalid data"); + } + } + + @Transactional(readOnly = true) + public ChatDTO getChatDTO(UUID caller, UUID chatId) { + Chat chat = requireChatForMember(caller, chatId); + return chatMapper.toChatDto(chat); + } + + @Transactional(readOnly = true) + public Chat getChat(UUID caller, UUID chatId) { + return requireChatForMember(caller, chatId); + } + + private Chat requireChatForMember(UUID caller, UUID chatId) { + Chat chat = chatRepository.findById(chatId) + .orElseThrow(() -> new NotFoundException("Chat not found")); + if (chat.getMembers().stream().noneMatch(m -> m.getId().equals(caller))) { + throw new NotFoundException("Chat not found"); + } + return chat; + } + + @Transactional(readOnly = true) + public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) { + int size = resolveSize(limit); + CursorCodec.Cursor decoded = parseChatsCursor(cursor); + List rows = loadChatPage(userId, decoded, size); + return buildPage(rows, size); + } + + private int resolveSize(Integer limit) { + return (limit == null) ? 50 : limit; + } + + private List loadChatPage(UUID userId, CursorCodec.Cursor cursor, int size) { + if (cursor == null) { + return chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1)); + } + return chatRepository.findPageByMemberAfterCursor( + userId, + cursor.boundary().createdAt(), + cursor.boundary().id(), + Pageable.ofSize(size + 1)); + } + + private CursorCodec.Cursor parseChatsCursor(String cursor) { + if (cursor == null || cursor.isBlank()) { + return null; + } + CursorCodec.Cursor decoded = CursorCodec.decode(cursor); + if (decoded.scopeId() != null) { + throw new InvalidRequestException("Invalid cursor"); + } + return decoded; + } + + private ChatPageDTO buildPage(List rows, int size) { + List items = rows.stream() + .limit(size) + .map(chatMapper::toChatDto) + .toList(); + + ChatPageDTO page = new ChatPageDTO(); + page.setItems(items); + page.setNextCursor(buildNextCursor(rows, size)); + return page; + } + + private String buildNextCursor(List rows, int size) { + if (rows.size() <= size) { + return null; + } + Chat last = rows.get(size - 1); + return CursorCodec.encode(null, boundaryOf(last)); + } + + private CursorCodec.PageBoundary boundaryOf(Chat chat) { + return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId()); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/HealthService.java b/src/main/java/ru/mtusi/messenger/service/HealthService.java new file mode 100644 index 00000000..3269338c --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/HealthService.java @@ -0,0 +1,31 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import ru.mtusi.messenger.dto.HealthDTO; +import ru.mtusi.messenger.exception.ServiceUnavailableException; + +@Service +@RequiredArgsConstructor +public class HealthService { + + private final JdbcTemplate jdbcTemplate; + + public HealthDTO readiness() { + try { + jdbcTemplate.queryForObject("SELECT 1", Integer.class); + } catch (Exception e) { + throw new ServiceUnavailableException("Database unavailable"); + } + HealthDTO h = new HealthDTO(); + h.setStatus(HealthDTO.StatusEnum.OK); + return h; + } + + public HealthDTO liveness() { + HealthDTO h = new HealthDTO(); + h.setStatus(HealthDTO.StatusEnum.OK); + return h; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/MessageService.java b/src/main/java/ru/mtusi/messenger/service/MessageService.java new file mode 100644 index 00000000..637862e7 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/MessageService.java @@ -0,0 +1,111 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.config.properties.AppProperties; +import ru.mtusi.messenger.dto.CreateMessageDTO; +import ru.mtusi.messenger.dto.MessageDTO; +import ru.mtusi.messenger.dto.MessagePageDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.exception.PayloadTooLargeException; +import ru.mtusi.messenger.mapper.ChatMapper; +import ru.mtusi.messenger.mapper.MessageMapper; +import ru.mtusi.messenger.model.Chat; +import ru.mtusi.messenger.model.Message; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.MessageRepository; +import ru.mtusi.messenger.util.CursorCodec; + +import java.util.List; +import java.util.UUID; + +@Service +@Slf4j +@RequiredArgsConstructor +public class MessageService { + private final ChatMapper chatMapper; + private final MessageRepository messageRepository; + private final ChatService chatService; + private final UserService userService; + private final MessageMapper messageMapper; + private final AppProperties appProperties; + + @Transactional + public MessageDTO createMessage(UUID senderId, UUID chatId, CreateMessageDTO createMessageDTO) { + Chat chat = chatService.getChat(senderId, chatId);; + validateCreate(chatId, createMessageDTO); + User sender = userService.getReferenceUserById(senderId); + Message message = buildMessage(createMessageDTO, sender, chat); + try { + message = messageRepository.saveAndFlush(message); + } catch (DataIntegrityViolationException e) { + throw new NotFoundException("Cannot create message: referenced entity is missing"); + } + + log.info("Created message id={} in chat={}", message.getId(), chatId); + return messageMapper.toMessageDTO(message); + } + + private void validateCreate(UUID chatId, CreateMessageDTO dto) { + if (dto.getText() == null || dto.getText().isBlank()) { + throw new InvalidRequestException("Empty text"); + } + if (messageRepository.countByChatId(chatId) >= appProperties.maxMessagesPerChat()) { + throw new PayloadTooLargeException("Chat history limit reached"); + } + } + + private Message buildMessage(CreateMessageDTO createMessageDTO, User sender, Chat chat) { + Message message = messageMapper.toMessage(createMessageDTO); + message.setChat(chat); + message.setSender(sender); + return message; + } + + @Transactional(readOnly = true) + public MessagePageDTO listMessages(UUID userId, UUID chatId, Integer limit, String cursor) { + int size = (limit == null) ? 50 : limit; + chatService.getChatDTO(userId, chatId); + CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId); + List rows = (decoded == null) ? messageRepository.findPageByChat(chatId, Pageable.ofSize(size + 1)) + : messageRepository.findPageByChatAfterCursor(chatId, decoded.boundary().createdAt(), decoded.boundary().id(), Pageable.ofSize(size + 1)); + return buildPage(rows, size, chatId); + } + + private CursorCodec.Cursor parseMessagesCursor(String cursor, UUID chatId) { + if (cursor == null || cursor.isBlank()) { + return null; + } + CursorCodec.Cursor decoded = CursorCodec.decode(cursor); + if (decoded.scopeId() == null || !decoded.scopeId().equals(chatId)) { + throw new InvalidRequestException("Cursor from another chat"); + } + return decoded; + } + + private MessagePageDTO buildPage(List rows, int size, UUID chatId) { + List items = rows.stream() + .limit(size) + .map(messageMapper::toMessageDTO) + .toList(); + + MessagePageDTO page = new MessagePageDTO(); + page.setItems(items); + page.setNextCursor(buildNextCursor(rows, size, chatId)); + return page; + } + + private String buildNextCursor(List rows, int size, UUID chatId) { + if (rows.size() <= size) { + return null; + } + Message last = rows.get(size - 1); + return CursorCodec.encode(chatId, new CursorCodec.PageBoundary( + last.getCreatedAt(), last.getId())); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java b/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java new file mode 100644 index 00000000..8573e426 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/SessionCacheService.java @@ -0,0 +1,65 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.cache.CacheHealthTracker; +import ru.mtusi.messenger.repository.SessionRepository; + +@Slf4j +@Service +@RequiredArgsConstructor +public class SessionCacheService { + + public static final String SESSIONS = "sessions"; + + private final SessionRepository sessionRepository; + private final CacheManager cacheManager; + private final CacheHealthTracker cacheHealthTracker; + + @Cacheable(value = SESSIONS, key = "#hex", unless = "#result == null") + @Transactional(readOnly = true) + public SessionService.SessionRecord lookupByHash(String hex) { + byte[] hash = hexToBytes(hex); + return sessionRepository.findByTokenHash(hash) + .filter(s -> s.getRevokedAt() == null) + .map(s -> new SessionService.SessionRecord( + s.getId(), s.getUserId(), s.getExpiresAt())) + .orElse(null); + } + + @CacheEvict(value = SESSIONS, key = "#hex") + public void evict(String hex) { + } + + public void dropCacheIfStale() { + if (!cacheHealthTracker.consumeStale()) { + return; + } + try { + Cache cache = cacheManager.getCache(SESSIONS); + if (cache != null) { + cache.clear(); + } + log.info("Cache '{}' cleared after stale flag", SESSIONS); + } catch (RuntimeException e) { + log.warn("Cache clear failed: {}", e.getMessage()); + cacheHealthTracker.markStale(); + } + } + + private static byte[] hexToBytes(String hex) { + int len = hex.length(); + byte[] out = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + out[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + + Character.digit(hex.charAt(i + 1), 16)); + } + return out; + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/SessionService.java b/src/main/java/ru/mtusi/messenger/service/SessionService.java new file mode 100644 index 00000000..fe6f5557 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/SessionService.java @@ -0,0 +1,81 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.config.properties.SessionProperties; +import ru.mtusi.messenger.dto.SessionDTO; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.mapper.SessionMapper; +import ru.mtusi.messenger.model.Session; +import ru.mtusi.messenger.repository.SessionRepository; +import ru.mtusi.messenger.util.TokenGenerator; +import ru.mtusi.messenger.util.TokenHasher; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Slf4j +@RequiredArgsConstructor +@Service +public class SessionService { + private final TokenGenerator tokenGenerator; + private final TokenHasher tokenHasher; + private final SessionProperties sessionProperties; + private final SessionRepository sessionRepository; + private final SessionMapper sessionMapper; + private final SessionCacheService sessionCacheService; + + @Transactional + public SessionDTO createSession(UserDTO userDTO) { + String token = tokenGenerator.generate(); + Session session = sessionRepository.save(buildSession(userDTO,token)); + return sessionMapper.toSessionDTO(session, token, userDTO); + } + + public SessionRecord requireActive(String token) { + sessionCacheService.dropCacheIfStale(); + String hex = tokenHasher.hash(token); + SessionRecord record = sessionCacheService.lookupByHash(hex); + requireNotExpired(record, hex); + return record; + } + + private void requireNotExpired(SessionRecord record, String hex) { + if (record == null || isExpired(record)) { + sessionCacheService.evict(hex); + throw new UnauthorizedException("Invalid or expired session"); + } + } + + private boolean isExpired(SessionRecord record) { + return record.expiresAt().isBefore(Instant.now()); + } + + @Transactional + public void revoke(UUID sessionId) { + sessionRepository.findById(sessionId).ifPresent(this::markRevokedAndEvict); + } + + private void markRevokedAndEvict(Session session) { + if (session.getRevokedAt() == null) { + session.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS)); + } + sessionCacheService.evict(tokenHasher.hash(session.getTokenHash())); + } + + private Session buildSession(UserDTO userDTO, String token) { + Session session = new Session(); + session.setUserId(userDTO.getId()); + session.setTokenHash(tokenHasher.sha256(token)); + session.setExpiresAt(Instant.now() + .plus(sessionProperties.ttl()) + .truncatedTo(ChronoUnit.MILLIS)); + return session; + } + + public record SessionRecord(UUID sessionId, UUID userId, Instant expiresAt) {} +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/service/UserService.java b/src/main/java/ru/mtusi/messenger/service/UserService.java new file mode 100644 index 00000000..37bce670 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/service/UserService.java @@ -0,0 +1,83 @@ +package ru.mtusi.messenger.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.mtusi.messenger.dto.UserDTO; +import ru.mtusi.messenger.exception.ConflictException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.exception.UnauthorizedException; +import ru.mtusi.messenger.mapper.UserMapper; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.repository.UserRepository; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +@Slf4j +public class UserService { + private final PasswordEncoder passwordEncoder; + private final UserMapper userMapper; + private final UserRepository userRepository; + + @Transactional + public Set requireUsers(Collection ids) { + Set uniqueIds = new HashSet<>(ids); + Set users = userRepository.findAllByIdForShare(uniqueIds); + if (users.size() != uniqueIds.size()) { + throw new NotFoundException("Users not found: " + findMissing(uniqueIds, users)); + } + return users; + } + + private Set findMissing(Set requested, Set found) { + Set foundIds = found.stream() + .map(User::getId) + .collect(Collectors.toSet()); + + Set missing = new HashSet<>(requested); + missing.removeAll(foundIds); + return missing; + } + + @Transactional(readOnly = true) + public UserDTO authenticate(String username, String password) { + User user = userRepository.findByUsername(username).orElseThrow(() -> new UnauthorizedException("Bad credentials")); + + if (!passwordEncoder.matches(password, user.getPasswordHash())) { + throw new UnauthorizedException("Bad credentials"); + } + return userMapper.toUserDto(user); + } + + @Transactional + public UserDTO registerUser(UserDTO userDTO) { + User user = userMapper.toUser(userDTO); + user.setPasswordHash(passwordEncoder.encode(userDTO.getPassword())); + try { + return userMapper.toUserDto(userRepository.saveAndFlush(user)); + } catch (DataIntegrityViolationException exception) { + throw new ConflictException("Username already exists"); + } + } + + @Transactional(readOnly = true) + public UserDTO currentUser(UUID userId) { + return userMapper.toUserDto(userRepository.findById(userId).orElseThrow(() -> + new NotFoundException("User not found") + )); + } + + @Transactional + public User getReferenceUserById(UUID senderId) { + return userRepository.getReferenceById(senderId); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/CursorCodec.java b/src/main/java/ru/mtusi/messenger/util/CursorCodec.java new file mode 100644 index 00000000..860d4029 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/CursorCodec.java @@ -0,0 +1,37 @@ +package ru.mtusi.messenger.util; + +import ru.mtusi.messenger.exception.InvalidRequestException; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.UUID; + +public final class CursorCodec { + + private CursorCodec() {} + + public record PageBoundary(Instant createdAt, UUID id) {} + + public record Cursor(UUID scopeId, PageBoundary boundary) {} + + public static String encode(UUID scopeId, PageBoundary boundary) { + String raw = (scopeId == null ? "" : scopeId.toString()) + + "|" + boundary.createdAt() + "|" + boundary.id(); + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + } + + public static Cursor decode(String cursor) { + try { + String raw = new String(Base64.getUrlDecoder().decode(cursor), StandardCharsets.UTF_8); + String[] p = raw.split("\\|", -1); + UUID scopeId = p[0].isEmpty() ? null : UUID.fromString(p[0]); + PageBoundary boundary = new PageBoundary( + Instant.parse(p[1]), UUID.fromString(p[2])); + return new Cursor(scopeId, boundary); + } catch (Exception e) { + throw new InvalidRequestException("Invalid cursor"); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java b/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java new file mode 100644 index 00000000..fa000c45 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/TokenGenerator.java @@ -0,0 +1,17 @@ +package ru.mtusi.messenger.util; + +import org.springframework.stereotype.Component; + +import java.security.SecureRandom; +import java.util.Base64; + +@Component +public class TokenGenerator { + private final SecureRandom rng = new SecureRandom(); + + public String generate() { + byte[] raw = new byte[32]; + rng.nextBytes(raw); + return Base64.getUrlEncoder().withoutPadding().encodeToString(raw); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/util/TokenHasher.java b/src/main/java/ru/mtusi/messenger/util/TokenHasher.java new file mode 100644 index 00000000..c63ea7f6 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/util/TokenHasher.java @@ -0,0 +1,37 @@ +package ru.mtusi.messenger.util; + +import org.springframework.stereotype.Component; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +@Component("tokenHasher") +public class TokenHasher { + + public byte[] sha256(String token) { + try { + return MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.UTF_8)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 not available", e); + } + } + + public String hash(String token) { + return toHex(sha256(token)); + } + + public String hash(byte[] bytes) { + return toHex(bytes); + } + + private String toHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + sb.append(Character.forDigit((b >> 4) & 0xF, 16)); + sb.append(Character.forDigit(b & 0xF, 16)); + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java b/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java new file mode 100644 index 00000000..b954e5b8 --- /dev/null +++ b/src/main/java/ru/mtusi/messenger/validation/ChatValidator.java @@ -0,0 +1,66 @@ +package ru.mtusi.messenger.validation; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import ru.mtusi.messenger.dto.ChatDTO; +import ru.mtusi.messenger.exception.InvalidRequestException; +import ru.mtusi.messenger.exception.NotFoundException; +import ru.mtusi.messenger.model.User; +import ru.mtusi.messenger.service.UserService; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Component +@RequiredArgsConstructor +public class ChatValidator { + + private final UserService userService; + + public Set validateCreate(UUID caller, ChatDTO chatDTO) { + List memberIds = chatDTO.getMemberIds(); + String title = chatDTO.getTitle(); + + requireNotBlank(title, "Title must not be blank"); + requireNonEmpty(memberIds, "member_ids must not be empty"); + requireNoDuplicates(memberIds, "member_ids contains duplicates"); + requireContains(memberIds, caller, "Вызывающий должен быть участником"); + + return requireAllUsersExist(memberIds); + } + + private void requireNotBlank(String value, String message) { + if (value == null || value.trim().isEmpty()) { + throw new InvalidRequestException(message); + } + } + + private void requireNonEmpty(List ids, String message) { + if (ids == null || ids.isEmpty()) { + throw new InvalidRequestException(message); + } + } + + private void requireNoDuplicates(List ids, String message) { + Set unique = new HashSet<>(ids); + if (unique.size() != ids.size()) { + throw new InvalidRequestException(message); + } + } + + private void requireContains(List ids, UUID value, String message) { + if (!ids.contains(value)) { + throw new InvalidRequestException(message); + } + } + + private Set requireAllUsersExist(List ids) { + try { + return userService.requireUsers(ids); + } catch (NotFoundException e) { + throw new InvalidRequestException(e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 00000000..3f85cde9 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,85 @@ +spring: + application: + name: messenger-lab2 + config: + import: "optional:configtree:/run/secrets/" + lifecycle: + timeout-per-shutdown-phase: 10s + jackson: + default-property-inclusion: non_null + deserialization: + fail-on-unknown-properties: true + datasource: + driver-class-name: org.postgresql.Driver + url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/messenger} + username: ${SPRING_DATASOURCE_USERNAME:messenger} + password: ${SPRING_DATASOURCE_PASSWORD:change-me-local-only} + hikari: + connection-timeout: 2000 + validation-timeout: 1000 + maximum-pool-size: 10 + minimum-idle: 2 + idle-timeout: 60000 + max-lifetime: 1800000 + jpa: + hibernate: + ddl-auto: validate + open-in-view: false + properties: + hibernate: + jdbc: + time_zone: UTC + dialect: org.hibernate.dialect.PostgreSQLDialect + flyway: + enabled: true + locations: classpath:db/migration + data: + redis: + host: ${SPRING_DATA_REDIS_HOST:localhost} + port: ${SPRING_DATA_REDIS_PORT:6379} + cache: + type: redis + +server: + address: ${APP_HOST:0.0.0.0} + port: ${APP_PORT:8080} + shutdown: graceful + +management: + endpoints: + web: + exposure: + include: health,metrics,caches + endpoint: + health: + probes: + enabled: true + show-details: always + caches: + enabled: true + + +app: + limits: + max-messages-per-chat: ${MAX_MESSAGES_PER_CHAT:10000} + rate: + rate-per-minute: ${RATE_PER_MINUTE:600} + retry-after-seconds: ${RETRY_AFTER_SECONDS:60} + session: + ttl: ${SESSION_TTL_SECONDS:400}s + redis: + host: ${SPRING_DATA_REDIS_HOST:localhost} + port: ${SPRING_DATA_REDIS_PORT:6379} + command-timeout: ${REDIS_COMMAND_TIMEOUT:500ms} + connect-timeout: ${REDIS_CONNECT_TIMEOUT:500ms} + shutdown-timeout: ${REDIS_SHUTDOWN_TIMEOUT:100ms} + keep-alive-idle: ${REDIS_KEEP_ALIVE_IDLE:30s} + keep-alive-interval: ${REDIS_KEEP_ALIVE_INTERVAL:10s} + tcp-user-timeout: ${REDIS_TCP_USER_TIMEOUT:10s} + +logging: + pattern: + console: "%d{ISO8601} %-5level [%X{requestId}] %logger{20} - %msg%n" + level: + org.springframework.cache: TRACE + org.springframework.cache.interceptor: TRACE \ No newline at end of file diff --git a/src/main/resources/db/migration/V1__init.sql b/src/main/resources/db/migration/V1__init.sql new file mode 100644 index 00000000..dc3eb522 --- /dev/null +++ b/src/main/resources/db/migration/V1__init.sql @@ -0,0 +1,79 @@ +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; + +-- ---------- users ---------- +CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + username VARCHAR(32) NOT NULL, + display_name VARCHAR(100) NOT NULL, + password_hash VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT uq_users_username UNIQUE (username), + CONSTRAINT ck_users_username_format + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT ck_users_display_name_not_blank + CHECK (length(btrim(display_name)) > 0) +); + +-- ---------- chats ---------- +CREATE TABLE chats ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + title VARCHAR(100) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_chats_title_not_blank CHECK (length(btrim(title)) > 0) +); + +-- ---------- chat_members ---------- +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) +); + +-- ---------- messages ---------- +CREATE TABLE messages ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + text VARCHAR(4000) NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT ck_messages_text_not_blank CHECK (length(btrim(text)) > 0) +); + +-- ---------- sessions ---------- +CREATE TABLE sessions ( + id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ, + CONSTRAINT uq_sessions_token_hash UNIQUE (token_hash), + CONSTRAINT ck_sessions_expiry CHECK (expires_at > created_at), + CONSTRAINT ck_sessions_token_len CHECK (octet_length(token_hash) = 32) +); + +-- ========================================================= +-- Indexes (critical for keyset pagination & EXPLAIN on lab5) +-- ========================================================= + +-- Keyset pagination: ORDER BY created_at ASC, id ASC (JPQL uses ASC) +CREATE INDEX idx_messages_chat_created_asc_id + ON messages (chat_id, created_at ASC, id ASC); + +-- "My chats" list (listChats) +CREATE INDEX idx_chat_members_user + ON chat_members (user_id); + +-- For chats list pagination: ORDER BY created_at ASC, id ASC +CREATE INDEX idx_chats_created_asc_id + ON chats (created_at ASC, id ASC); + +-- Active sessions per user (logout-all / audit) +CREATE INDEX idx_sessions_user_active + ON sessions (user_id) + WHERE revoked_at IS NULL; + +-- Cleanup of expired sessions +CREATE INDEX idx_sessions_expires_active + ON sessions (expires_at) + WHERE revoked_at IS NULL; \ No newline at end of file diff --git a/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java b/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java new file mode 100644 index 00000000..2da5d512 --- /dev/null +++ b/src/test/java/ru/mtusi/messenger/MessengerLab1ApplicationTests.java @@ -0,0 +1,13 @@ +package ru.mtusi.messenger; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MessengerLab1ApplicationTests { + + @Test + void contextLoads() { + } + +}